[docs] Fix build-docs.sh
[llvm-project.git] / clang / lib / Serialization / ASTWriter.cpp
blob838c6e306cfb09e858d733c4752063003663ad98
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/Optional.h"
81 #include "llvm/ADT/PointerIntPair.h"
82 #include "llvm/ADT/STLExtras.h"
83 #include "llvm/ADT/ScopeExit.h"
84 #include "llvm/ADT/SmallPtrSet.h"
85 #include "llvm/ADT/SmallString.h"
86 #include "llvm/ADT/SmallVector.h"
87 #include "llvm/ADT/StringMap.h"
88 #include "llvm/ADT/StringRef.h"
89 #include "llvm/Bitstream/BitCodes.h"
90 #include "llvm/Bitstream/BitstreamWriter.h"
91 #include "llvm/Support/Casting.h"
92 #include "llvm/Support/Compression.h"
93 #include "llvm/Support/DJB.h"
94 #include "llvm/Support/Endian.h"
95 #include "llvm/Support/EndianStream.h"
96 #include "llvm/Support/Error.h"
97 #include "llvm/Support/ErrorHandling.h"
98 #include "llvm/Support/LEB128.h"
99 #include "llvm/Support/MemoryBuffer.h"
100 #include "llvm/Support/OnDiskHashTable.h"
101 #include "llvm/Support/Path.h"
102 #include "llvm/Support/SHA1.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 <deque>
112 #include <limits>
113 #include <memory>
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 *> GetAllModuleMaps(const HeaderSearch &HS,
165 Module *RootModule) {
166 std::set<const FileEntry *> ModuleMaps{};
167 std::set<const Module *> ProcessedModules;
168 SmallVector<const Module *> ModulesToProcess{RootModule};
170 SmallVector<const FileEntry *, 16> FilesByUID;
171 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
173 if (FilesByUID.size() > HS.header_file_size())
174 FilesByUID.resize(HS.header_file_size());
176 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
177 const FileEntry *File = FilesByUID[UID];
178 if (!File)
179 continue;
181 const HeaderFileInfo *HFI =
182 HS.getExistingFileInfo(File, /*WantExternal*/ false);
183 if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
184 continue;
186 for (const auto &KH : HS.findAllModulesForHeader(File)) {
187 if (!KH.getModule())
188 continue;
189 ModulesToProcess.push_back(KH.getModule());
193 while (!ModulesToProcess.empty()) {
194 auto *CurrentModule = ModulesToProcess.pop_back_val();
195 ProcessedModules.insert(CurrentModule);
197 auto *ModuleMapFile =
198 HS.getModuleMap().getModuleMapFileForUniquing(CurrentModule);
199 if (!ModuleMapFile) {
200 continue;
203 ModuleMaps.insert(ModuleMapFile);
205 for (auto *ImportedModule : (CurrentModule)->Imports) {
206 if (!ImportedModule ||
207 ProcessedModules.find(ImportedModule) != ProcessedModules.end()) {
208 continue;
210 ModulesToProcess.push_back(ImportedModule);
213 for (const Module *UndeclaredModule : CurrentModule->UndeclaredUses)
214 if (UndeclaredModule &&
215 ProcessedModules.find(UndeclaredModule) == ProcessedModules.end())
216 ModulesToProcess.push_back(UndeclaredModule);
219 return ModuleMaps;
222 class ASTTypeWriter {
223 ASTWriter &Writer;
224 ASTWriter::RecordData Record;
225 ASTRecordWriter BasicWriter;
227 public:
228 ASTTypeWriter(ASTWriter &Writer)
229 : Writer(Writer), BasicWriter(Writer, Record) {}
231 uint64_t write(QualType T) {
232 if (T.hasLocalNonFastQualifiers()) {
233 Qualifiers Qs = T.getLocalQualifiers();
234 BasicWriter.writeQualType(T.getLocalUnqualifiedType());
235 BasicWriter.writeQualifiers(Qs);
236 return BasicWriter.Emit(TYPE_EXT_QUAL, Writer.getTypeExtQualAbbrev());
239 const Type *typePtr = T.getTypePtr();
240 serialization::AbstractTypeWriter<ASTRecordWriter> atw(BasicWriter);
241 atw.write(typePtr);
242 return BasicWriter.Emit(getTypeCodeForTypeClass(typePtr->getTypeClass()),
243 /*abbrev*/ 0);
247 class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
248 using LocSeq = SourceLocationSequence;
250 ASTRecordWriter &Record;
251 LocSeq *Seq;
253 void addSourceLocation(SourceLocation Loc) {
254 Record.AddSourceLocation(Loc, Seq);
256 void addSourceRange(SourceRange Range) { Record.AddSourceRange(Range, Seq); }
258 public:
259 TypeLocWriter(ASTRecordWriter &Record, LocSeq *Seq)
260 : Record(Record), Seq(Seq) {}
262 #define ABSTRACT_TYPELOC(CLASS, PARENT)
263 #define TYPELOC(CLASS, PARENT) \
264 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
265 #include "clang/AST/TypeLocNodes.def"
267 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
268 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
271 } // namespace
273 void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
274 // nothing to do
277 void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
278 addSourceLocation(TL.getBuiltinLoc());
279 if (TL.needsExtraLocalData()) {
280 Record.push_back(TL.getWrittenTypeSpec());
281 Record.push_back(static_cast<uint64_t>(TL.getWrittenSignSpec()));
282 Record.push_back(static_cast<uint64_t>(TL.getWrittenWidthSpec()));
283 Record.push_back(TL.hasModeAttr());
287 void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
288 addSourceLocation(TL.getNameLoc());
291 void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
292 addSourceLocation(TL.getStarLoc());
295 void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
296 // nothing to do
299 void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
300 // nothing to do
303 void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
304 addSourceLocation(TL.getCaretLoc());
307 void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
308 addSourceLocation(TL.getAmpLoc());
311 void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
312 addSourceLocation(TL.getAmpAmpLoc());
315 void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
316 addSourceLocation(TL.getStarLoc());
317 Record.AddTypeSourceInfo(TL.getClassTInfo());
320 void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
321 addSourceLocation(TL.getLBracketLoc());
322 addSourceLocation(TL.getRBracketLoc());
323 Record.push_back(TL.getSizeExpr() ? 1 : 0);
324 if (TL.getSizeExpr())
325 Record.AddStmt(TL.getSizeExpr());
328 void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
329 VisitArrayTypeLoc(TL);
332 void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
333 VisitArrayTypeLoc(TL);
336 void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
337 VisitArrayTypeLoc(TL);
340 void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
341 DependentSizedArrayTypeLoc TL) {
342 VisitArrayTypeLoc(TL);
345 void TypeLocWriter::VisitDependentAddressSpaceTypeLoc(
346 DependentAddressSpaceTypeLoc TL) {
347 addSourceLocation(TL.getAttrNameLoc());
348 SourceRange range = TL.getAttrOperandParensRange();
349 addSourceLocation(range.getBegin());
350 addSourceLocation(range.getEnd());
351 Record.AddStmt(TL.getAttrExprOperand());
354 void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
355 DependentSizedExtVectorTypeLoc TL) {
356 addSourceLocation(TL.getNameLoc());
359 void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
360 addSourceLocation(TL.getNameLoc());
363 void TypeLocWriter::VisitDependentVectorTypeLoc(
364 DependentVectorTypeLoc TL) {
365 addSourceLocation(TL.getNameLoc());
368 void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
369 addSourceLocation(TL.getNameLoc());
372 void TypeLocWriter::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
373 addSourceLocation(TL.getAttrNameLoc());
374 SourceRange range = TL.getAttrOperandParensRange();
375 addSourceLocation(range.getBegin());
376 addSourceLocation(range.getEnd());
377 Record.AddStmt(TL.getAttrRowOperand());
378 Record.AddStmt(TL.getAttrColumnOperand());
381 void TypeLocWriter::VisitDependentSizedMatrixTypeLoc(
382 DependentSizedMatrixTypeLoc TL) {
383 addSourceLocation(TL.getAttrNameLoc());
384 SourceRange range = TL.getAttrOperandParensRange();
385 addSourceLocation(range.getBegin());
386 addSourceLocation(range.getEnd());
387 Record.AddStmt(TL.getAttrRowOperand());
388 Record.AddStmt(TL.getAttrColumnOperand());
391 void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
392 addSourceLocation(TL.getLocalRangeBegin());
393 addSourceLocation(TL.getLParenLoc());
394 addSourceLocation(TL.getRParenLoc());
395 addSourceRange(TL.getExceptionSpecRange());
396 addSourceLocation(TL.getLocalRangeEnd());
397 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
398 Record.AddDeclRef(TL.getParam(i));
401 void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
402 VisitFunctionTypeLoc(TL);
405 void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
406 VisitFunctionTypeLoc(TL);
409 void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
410 addSourceLocation(TL.getNameLoc());
413 void TypeLocWriter::VisitUsingTypeLoc(UsingTypeLoc TL) {
414 addSourceLocation(TL.getNameLoc());
417 void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
418 addSourceLocation(TL.getNameLoc());
421 void TypeLocWriter::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
422 if (TL.getNumProtocols()) {
423 addSourceLocation(TL.getProtocolLAngleLoc());
424 addSourceLocation(TL.getProtocolRAngleLoc());
426 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
427 addSourceLocation(TL.getProtocolLoc(i));
430 void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
431 addSourceLocation(TL.getTypeofLoc());
432 addSourceLocation(TL.getLParenLoc());
433 addSourceLocation(TL.getRParenLoc());
436 void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
437 addSourceLocation(TL.getTypeofLoc());
438 addSourceLocation(TL.getLParenLoc());
439 addSourceLocation(TL.getRParenLoc());
440 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
443 void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
444 addSourceLocation(TL.getDecltypeLoc());
445 addSourceLocation(TL.getRParenLoc());
448 void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
449 addSourceLocation(TL.getKWLoc());
450 addSourceLocation(TL.getLParenLoc());
451 addSourceLocation(TL.getRParenLoc());
452 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
455 void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
456 addSourceLocation(TL.getNameLoc());
457 Record.push_back(TL.isConstrained());
458 if (TL.isConstrained()) {
459 Record.AddNestedNameSpecifierLoc(TL.getNestedNameSpecifierLoc());
460 addSourceLocation(TL.getTemplateKWLoc());
461 addSourceLocation(TL.getConceptNameLoc());
462 Record.AddDeclRef(TL.getFoundDecl());
463 addSourceLocation(TL.getLAngleLoc());
464 addSourceLocation(TL.getRAngleLoc());
465 for (unsigned I = 0; I < TL.getNumArgs(); ++I)
466 Record.AddTemplateArgumentLocInfo(TL.getTypePtr()->getArg(I).getKind(),
467 TL.getArgLocInfo(I));
469 Record.push_back(TL.isDecltypeAuto());
470 if (TL.isDecltypeAuto())
471 addSourceLocation(TL.getRParenLoc());
474 void TypeLocWriter::VisitDeducedTemplateSpecializationTypeLoc(
475 DeducedTemplateSpecializationTypeLoc TL) {
476 addSourceLocation(TL.getTemplateNameLoc());
479 void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
480 addSourceLocation(TL.getNameLoc());
483 void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
484 addSourceLocation(TL.getNameLoc());
487 void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
488 Record.AddAttr(TL.getAttr());
491 void TypeLocWriter::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
492 // Nothing to do.
495 void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
496 addSourceLocation(TL.getNameLoc());
499 void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
500 SubstTemplateTypeParmTypeLoc TL) {
501 addSourceLocation(TL.getNameLoc());
504 void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
505 SubstTemplateTypeParmPackTypeLoc TL) {
506 addSourceLocation(TL.getNameLoc());
509 void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
510 TemplateSpecializationTypeLoc TL) {
511 addSourceLocation(TL.getTemplateKeywordLoc());
512 addSourceLocation(TL.getTemplateNameLoc());
513 addSourceLocation(TL.getLAngleLoc());
514 addSourceLocation(TL.getRAngleLoc());
515 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
516 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
517 TL.getArgLoc(i).getLocInfo());
520 void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
521 addSourceLocation(TL.getLParenLoc());
522 addSourceLocation(TL.getRParenLoc());
525 void TypeLocWriter::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
526 addSourceLocation(TL.getExpansionLoc());
529 void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
530 addSourceLocation(TL.getElaboratedKeywordLoc());
531 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
534 void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
535 addSourceLocation(TL.getNameLoc());
538 void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
539 addSourceLocation(TL.getElaboratedKeywordLoc());
540 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
541 addSourceLocation(TL.getNameLoc());
544 void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
545 DependentTemplateSpecializationTypeLoc TL) {
546 addSourceLocation(TL.getElaboratedKeywordLoc());
547 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
548 addSourceLocation(TL.getTemplateKeywordLoc());
549 addSourceLocation(TL.getTemplateNameLoc());
550 addSourceLocation(TL.getLAngleLoc());
551 addSourceLocation(TL.getRAngleLoc());
552 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
553 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
554 TL.getArgLoc(I).getLocInfo());
557 void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
558 addSourceLocation(TL.getEllipsisLoc());
561 void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
562 addSourceLocation(TL.getNameLoc());
565 void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
566 Record.push_back(TL.hasBaseTypeAsWritten());
567 addSourceLocation(TL.getTypeArgsLAngleLoc());
568 addSourceLocation(TL.getTypeArgsRAngleLoc());
569 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
570 Record.AddTypeSourceInfo(TL.getTypeArgTInfo(i));
571 addSourceLocation(TL.getProtocolLAngleLoc());
572 addSourceLocation(TL.getProtocolRAngleLoc());
573 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
574 addSourceLocation(TL.getProtocolLoc(i));
577 void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
578 addSourceLocation(TL.getStarLoc());
581 void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
582 addSourceLocation(TL.getKWLoc());
583 addSourceLocation(TL.getLParenLoc());
584 addSourceLocation(TL.getRParenLoc());
587 void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) {
588 addSourceLocation(TL.getKWLoc());
591 void TypeLocWriter::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {
592 addSourceLocation(TL.getNameLoc());
594 void TypeLocWriter::VisitDependentBitIntTypeLoc(
595 clang::DependentBitIntTypeLoc TL) {
596 addSourceLocation(TL.getNameLoc());
599 void ASTWriter::WriteTypeAbbrevs() {
600 using namespace llvm;
602 std::shared_ptr<BitCodeAbbrev> Abv;
604 // Abbreviation for TYPE_EXT_QUAL
605 Abv = std::make_shared<BitCodeAbbrev>();
606 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
607 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
608 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Quals
609 TypeExtQualAbbrev = Stream.EmitAbbrev(std::move(Abv));
612 //===----------------------------------------------------------------------===//
613 // ASTWriter Implementation
614 //===----------------------------------------------------------------------===//
616 static void EmitBlockID(unsigned ID, const char *Name,
617 llvm::BitstreamWriter &Stream,
618 ASTWriter::RecordDataImpl &Record) {
619 Record.clear();
620 Record.push_back(ID);
621 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
623 // Emit the block name if present.
624 if (!Name || Name[0] == 0)
625 return;
626 Record.clear();
627 while (*Name)
628 Record.push_back(*Name++);
629 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
632 static void EmitRecordID(unsigned ID, const char *Name,
633 llvm::BitstreamWriter &Stream,
634 ASTWriter::RecordDataImpl &Record) {
635 Record.clear();
636 Record.push_back(ID);
637 while (*Name)
638 Record.push_back(*Name++);
639 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
642 static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
643 ASTWriter::RecordDataImpl &Record) {
644 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
645 RECORD(STMT_STOP);
646 RECORD(STMT_NULL_PTR);
647 RECORD(STMT_REF_PTR);
648 RECORD(STMT_NULL);
649 RECORD(STMT_COMPOUND);
650 RECORD(STMT_CASE);
651 RECORD(STMT_DEFAULT);
652 RECORD(STMT_LABEL);
653 RECORD(STMT_ATTRIBUTED);
654 RECORD(STMT_IF);
655 RECORD(STMT_SWITCH);
656 RECORD(STMT_WHILE);
657 RECORD(STMT_DO);
658 RECORD(STMT_FOR);
659 RECORD(STMT_GOTO);
660 RECORD(STMT_INDIRECT_GOTO);
661 RECORD(STMT_CONTINUE);
662 RECORD(STMT_BREAK);
663 RECORD(STMT_RETURN);
664 RECORD(STMT_DECL);
665 RECORD(STMT_GCCASM);
666 RECORD(STMT_MSASM);
667 RECORD(EXPR_PREDEFINED);
668 RECORD(EXPR_DECL_REF);
669 RECORD(EXPR_INTEGER_LITERAL);
670 RECORD(EXPR_FIXEDPOINT_LITERAL);
671 RECORD(EXPR_FLOATING_LITERAL);
672 RECORD(EXPR_IMAGINARY_LITERAL);
673 RECORD(EXPR_STRING_LITERAL);
674 RECORD(EXPR_CHARACTER_LITERAL);
675 RECORD(EXPR_PAREN);
676 RECORD(EXPR_PAREN_LIST);
677 RECORD(EXPR_UNARY_OPERATOR);
678 RECORD(EXPR_SIZEOF_ALIGN_OF);
679 RECORD(EXPR_ARRAY_SUBSCRIPT);
680 RECORD(EXPR_CALL);
681 RECORD(EXPR_MEMBER);
682 RECORD(EXPR_BINARY_OPERATOR);
683 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
684 RECORD(EXPR_CONDITIONAL_OPERATOR);
685 RECORD(EXPR_IMPLICIT_CAST);
686 RECORD(EXPR_CSTYLE_CAST);
687 RECORD(EXPR_COMPOUND_LITERAL);
688 RECORD(EXPR_EXT_VECTOR_ELEMENT);
689 RECORD(EXPR_INIT_LIST);
690 RECORD(EXPR_DESIGNATED_INIT);
691 RECORD(EXPR_DESIGNATED_INIT_UPDATE);
692 RECORD(EXPR_IMPLICIT_VALUE_INIT);
693 RECORD(EXPR_NO_INIT);
694 RECORD(EXPR_VA_ARG);
695 RECORD(EXPR_ADDR_LABEL);
696 RECORD(EXPR_STMT);
697 RECORD(EXPR_CHOOSE);
698 RECORD(EXPR_GNU_NULL);
699 RECORD(EXPR_SHUFFLE_VECTOR);
700 RECORD(EXPR_BLOCK);
701 RECORD(EXPR_GENERIC_SELECTION);
702 RECORD(EXPR_OBJC_STRING_LITERAL);
703 RECORD(EXPR_OBJC_BOXED_EXPRESSION);
704 RECORD(EXPR_OBJC_ARRAY_LITERAL);
705 RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
706 RECORD(EXPR_OBJC_ENCODE);
707 RECORD(EXPR_OBJC_SELECTOR_EXPR);
708 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
709 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
710 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
711 RECORD(EXPR_OBJC_KVC_REF_EXPR);
712 RECORD(EXPR_OBJC_MESSAGE_EXPR);
713 RECORD(STMT_OBJC_FOR_COLLECTION);
714 RECORD(STMT_OBJC_CATCH);
715 RECORD(STMT_OBJC_FINALLY);
716 RECORD(STMT_OBJC_AT_TRY);
717 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
718 RECORD(STMT_OBJC_AT_THROW);
719 RECORD(EXPR_OBJC_BOOL_LITERAL);
720 RECORD(STMT_CXX_CATCH);
721 RECORD(STMT_CXX_TRY);
722 RECORD(STMT_CXX_FOR_RANGE);
723 RECORD(EXPR_CXX_OPERATOR_CALL);
724 RECORD(EXPR_CXX_MEMBER_CALL);
725 RECORD(EXPR_CXX_REWRITTEN_BINARY_OPERATOR);
726 RECORD(EXPR_CXX_CONSTRUCT);
727 RECORD(EXPR_CXX_TEMPORARY_OBJECT);
728 RECORD(EXPR_CXX_STATIC_CAST);
729 RECORD(EXPR_CXX_DYNAMIC_CAST);
730 RECORD(EXPR_CXX_REINTERPRET_CAST);
731 RECORD(EXPR_CXX_CONST_CAST);
732 RECORD(EXPR_CXX_ADDRSPACE_CAST);
733 RECORD(EXPR_CXX_FUNCTIONAL_CAST);
734 RECORD(EXPR_USER_DEFINED_LITERAL);
735 RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
736 RECORD(EXPR_CXX_BOOL_LITERAL);
737 RECORD(EXPR_CXX_NULL_PTR_LITERAL);
738 RECORD(EXPR_CXX_TYPEID_EXPR);
739 RECORD(EXPR_CXX_TYPEID_TYPE);
740 RECORD(EXPR_CXX_THIS);
741 RECORD(EXPR_CXX_THROW);
742 RECORD(EXPR_CXX_DEFAULT_ARG);
743 RECORD(EXPR_CXX_DEFAULT_INIT);
744 RECORD(EXPR_CXX_BIND_TEMPORARY);
745 RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
746 RECORD(EXPR_CXX_NEW);
747 RECORD(EXPR_CXX_DELETE);
748 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
749 RECORD(EXPR_EXPR_WITH_CLEANUPS);
750 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
751 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
752 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
753 RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
754 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
755 RECORD(EXPR_CXX_EXPRESSION_TRAIT);
756 RECORD(EXPR_CXX_NOEXCEPT);
757 RECORD(EXPR_OPAQUE_VALUE);
758 RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR);
759 RECORD(EXPR_TYPE_TRAIT);
760 RECORD(EXPR_ARRAY_TYPE_TRAIT);
761 RECORD(EXPR_PACK_EXPANSION);
762 RECORD(EXPR_SIZEOF_PACK);
763 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM);
764 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
765 RECORD(EXPR_FUNCTION_PARM_PACK);
766 RECORD(EXPR_MATERIALIZE_TEMPORARY);
767 RECORD(EXPR_CUDA_KERNEL_CALL);
768 RECORD(EXPR_CXX_UUIDOF_EXPR);
769 RECORD(EXPR_CXX_UUIDOF_TYPE);
770 RECORD(EXPR_LAMBDA);
771 #undef RECORD
774 void ASTWriter::WriteBlockInfoBlock() {
775 RecordData Record;
776 Stream.EnterBlockInfoBlock();
778 #define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
779 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
781 // Control Block.
782 BLOCK(CONTROL_BLOCK);
783 RECORD(METADATA);
784 RECORD(MODULE_NAME);
785 RECORD(MODULE_DIRECTORY);
786 RECORD(MODULE_MAP_FILE);
787 RECORD(IMPORTS);
788 RECORD(ORIGINAL_FILE);
789 RECORD(ORIGINAL_FILE_ID);
790 RECORD(INPUT_FILE_OFFSETS);
792 BLOCK(OPTIONS_BLOCK);
793 RECORD(LANGUAGE_OPTIONS);
794 RECORD(TARGET_OPTIONS);
795 RECORD(FILE_SYSTEM_OPTIONS);
796 RECORD(HEADER_SEARCH_OPTIONS);
797 RECORD(PREPROCESSOR_OPTIONS);
799 BLOCK(INPUT_FILES_BLOCK);
800 RECORD(INPUT_FILE);
801 RECORD(INPUT_FILE_HASH);
803 // AST Top-Level Block.
804 BLOCK(AST_BLOCK);
805 RECORD(TYPE_OFFSET);
806 RECORD(DECL_OFFSET);
807 RECORD(IDENTIFIER_OFFSET);
808 RECORD(IDENTIFIER_TABLE);
809 RECORD(EAGERLY_DESERIALIZED_DECLS);
810 RECORD(MODULAR_CODEGEN_DECLS);
811 RECORD(SPECIAL_TYPES);
812 RECORD(STATISTICS);
813 RECORD(TENTATIVE_DEFINITIONS);
814 RECORD(SELECTOR_OFFSETS);
815 RECORD(METHOD_POOL);
816 RECORD(PP_COUNTER_VALUE);
817 RECORD(SOURCE_LOCATION_OFFSETS);
818 RECORD(SOURCE_LOCATION_PRELOADS);
819 RECORD(EXT_VECTOR_DECLS);
820 RECORD(UNUSED_FILESCOPED_DECLS);
821 RECORD(PPD_ENTITIES_OFFSETS);
822 RECORD(VTABLE_USES);
823 RECORD(PPD_SKIPPED_RANGES);
824 RECORD(REFERENCED_SELECTOR_POOL);
825 RECORD(TU_UPDATE_LEXICAL);
826 RECORD(SEMA_DECL_REFS);
827 RECORD(WEAK_UNDECLARED_IDENTIFIERS);
828 RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
829 RECORD(UPDATE_VISIBLE);
830 RECORD(DECL_UPDATE_OFFSETS);
831 RECORD(DECL_UPDATES);
832 RECORD(CUDA_SPECIAL_DECL_REFS);
833 RECORD(HEADER_SEARCH_TABLE);
834 RECORD(FP_PRAGMA_OPTIONS);
835 RECORD(OPENCL_EXTENSIONS);
836 RECORD(OPENCL_EXTENSION_TYPES);
837 RECORD(OPENCL_EXTENSION_DECLS);
838 RECORD(DELEGATING_CTORS);
839 RECORD(KNOWN_NAMESPACES);
840 RECORD(MODULE_OFFSET_MAP);
841 RECORD(SOURCE_MANAGER_LINE_TABLE);
842 RECORD(OBJC_CATEGORIES_MAP);
843 RECORD(FILE_SORTED_DECLS);
844 RECORD(IMPORTED_MODULES);
845 RECORD(OBJC_CATEGORIES);
846 RECORD(MACRO_OFFSET);
847 RECORD(INTERESTING_IDENTIFIERS);
848 RECORD(UNDEFINED_BUT_USED);
849 RECORD(LATE_PARSED_TEMPLATE);
850 RECORD(OPTIMIZE_PRAGMA_OPTIONS);
851 RECORD(MSSTRUCT_PRAGMA_OPTIONS);
852 RECORD(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS);
853 RECORD(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES);
854 RECORD(DELETE_EXPRS_TO_ANALYZE);
855 RECORD(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH);
856 RECORD(PP_CONDITIONAL_STACK);
857 RECORD(DECLS_TO_CHECK_FOR_DEFERRED_DIAGS);
858 RECORD(PP_INCLUDED_FILES);
859 RECORD(PP_ASSUME_NONNULL_LOC);
861 // SourceManager Block.
862 BLOCK(SOURCE_MANAGER_BLOCK);
863 RECORD(SM_SLOC_FILE_ENTRY);
864 RECORD(SM_SLOC_BUFFER_ENTRY);
865 RECORD(SM_SLOC_BUFFER_BLOB);
866 RECORD(SM_SLOC_BUFFER_BLOB_COMPRESSED);
867 RECORD(SM_SLOC_EXPANSION_ENTRY);
869 // Preprocessor Block.
870 BLOCK(PREPROCESSOR_BLOCK);
871 RECORD(PP_MACRO_DIRECTIVE_HISTORY);
872 RECORD(PP_MACRO_FUNCTION_LIKE);
873 RECORD(PP_MACRO_OBJECT_LIKE);
874 RECORD(PP_MODULE_MACRO);
875 RECORD(PP_TOKEN);
877 // Submodule Block.
878 BLOCK(SUBMODULE_BLOCK);
879 RECORD(SUBMODULE_METADATA);
880 RECORD(SUBMODULE_DEFINITION);
881 RECORD(SUBMODULE_UMBRELLA_HEADER);
882 RECORD(SUBMODULE_HEADER);
883 RECORD(SUBMODULE_TOPHEADER);
884 RECORD(SUBMODULE_UMBRELLA_DIR);
885 RECORD(SUBMODULE_IMPORTS);
886 RECORD(SUBMODULE_AFFECTING_MODULES);
887 RECORD(SUBMODULE_EXPORTS);
888 RECORD(SUBMODULE_REQUIRES);
889 RECORD(SUBMODULE_EXCLUDED_HEADER);
890 RECORD(SUBMODULE_LINK_LIBRARY);
891 RECORD(SUBMODULE_CONFIG_MACRO);
892 RECORD(SUBMODULE_CONFLICT);
893 RECORD(SUBMODULE_PRIVATE_HEADER);
894 RECORD(SUBMODULE_TEXTUAL_HEADER);
895 RECORD(SUBMODULE_PRIVATE_TEXTUAL_HEADER);
896 RECORD(SUBMODULE_INITIALIZERS);
897 RECORD(SUBMODULE_EXPORT_AS);
899 // Comments Block.
900 BLOCK(COMMENTS_BLOCK);
901 RECORD(COMMENTS_RAW_COMMENT);
903 // Decls and Types block.
904 BLOCK(DECLTYPES_BLOCK);
905 RECORD(TYPE_EXT_QUAL);
906 RECORD(TYPE_COMPLEX);
907 RECORD(TYPE_POINTER);
908 RECORD(TYPE_BLOCK_POINTER);
909 RECORD(TYPE_LVALUE_REFERENCE);
910 RECORD(TYPE_RVALUE_REFERENCE);
911 RECORD(TYPE_MEMBER_POINTER);
912 RECORD(TYPE_CONSTANT_ARRAY);
913 RECORD(TYPE_INCOMPLETE_ARRAY);
914 RECORD(TYPE_VARIABLE_ARRAY);
915 RECORD(TYPE_VECTOR);
916 RECORD(TYPE_EXT_VECTOR);
917 RECORD(TYPE_FUNCTION_NO_PROTO);
918 RECORD(TYPE_FUNCTION_PROTO);
919 RECORD(TYPE_TYPEDEF);
920 RECORD(TYPE_TYPEOF_EXPR);
921 RECORD(TYPE_TYPEOF);
922 RECORD(TYPE_RECORD);
923 RECORD(TYPE_ENUM);
924 RECORD(TYPE_OBJC_INTERFACE);
925 RECORD(TYPE_OBJC_OBJECT_POINTER);
926 RECORD(TYPE_DECLTYPE);
927 RECORD(TYPE_ELABORATED);
928 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
929 RECORD(TYPE_UNRESOLVED_USING);
930 RECORD(TYPE_INJECTED_CLASS_NAME);
931 RECORD(TYPE_OBJC_OBJECT);
932 RECORD(TYPE_TEMPLATE_TYPE_PARM);
933 RECORD(TYPE_TEMPLATE_SPECIALIZATION);
934 RECORD(TYPE_DEPENDENT_NAME);
935 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
936 RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
937 RECORD(TYPE_PAREN);
938 RECORD(TYPE_MACRO_QUALIFIED);
939 RECORD(TYPE_PACK_EXPANSION);
940 RECORD(TYPE_ATTRIBUTED);
941 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
942 RECORD(TYPE_AUTO);
943 RECORD(TYPE_UNARY_TRANSFORM);
944 RECORD(TYPE_ATOMIC);
945 RECORD(TYPE_DECAYED);
946 RECORD(TYPE_ADJUSTED);
947 RECORD(TYPE_OBJC_TYPE_PARAM);
948 RECORD(LOCAL_REDECLARATIONS);
949 RECORD(DECL_TYPEDEF);
950 RECORD(DECL_TYPEALIAS);
951 RECORD(DECL_ENUM);
952 RECORD(DECL_RECORD);
953 RECORD(DECL_ENUM_CONSTANT);
954 RECORD(DECL_FUNCTION);
955 RECORD(DECL_OBJC_METHOD);
956 RECORD(DECL_OBJC_INTERFACE);
957 RECORD(DECL_OBJC_PROTOCOL);
958 RECORD(DECL_OBJC_IVAR);
959 RECORD(DECL_OBJC_AT_DEFS_FIELD);
960 RECORD(DECL_OBJC_CATEGORY);
961 RECORD(DECL_OBJC_CATEGORY_IMPL);
962 RECORD(DECL_OBJC_IMPLEMENTATION);
963 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
964 RECORD(DECL_OBJC_PROPERTY);
965 RECORD(DECL_OBJC_PROPERTY_IMPL);
966 RECORD(DECL_FIELD);
967 RECORD(DECL_MS_PROPERTY);
968 RECORD(DECL_VAR);
969 RECORD(DECL_IMPLICIT_PARAM);
970 RECORD(DECL_PARM_VAR);
971 RECORD(DECL_FILE_SCOPE_ASM);
972 RECORD(DECL_BLOCK);
973 RECORD(DECL_CONTEXT_LEXICAL);
974 RECORD(DECL_CONTEXT_VISIBLE);
975 RECORD(DECL_NAMESPACE);
976 RECORD(DECL_NAMESPACE_ALIAS);
977 RECORD(DECL_USING);
978 RECORD(DECL_USING_SHADOW);
979 RECORD(DECL_USING_DIRECTIVE);
980 RECORD(DECL_UNRESOLVED_USING_VALUE);
981 RECORD(DECL_UNRESOLVED_USING_TYPENAME);
982 RECORD(DECL_LINKAGE_SPEC);
983 RECORD(DECL_CXX_RECORD);
984 RECORD(DECL_CXX_METHOD);
985 RECORD(DECL_CXX_CONSTRUCTOR);
986 RECORD(DECL_CXX_DESTRUCTOR);
987 RECORD(DECL_CXX_CONVERSION);
988 RECORD(DECL_ACCESS_SPEC);
989 RECORD(DECL_FRIEND);
990 RECORD(DECL_FRIEND_TEMPLATE);
991 RECORD(DECL_CLASS_TEMPLATE);
992 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
993 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
994 RECORD(DECL_VAR_TEMPLATE);
995 RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
996 RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
997 RECORD(DECL_FUNCTION_TEMPLATE);
998 RECORD(DECL_TEMPLATE_TYPE_PARM);
999 RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
1000 RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
1001 RECORD(DECL_CONCEPT);
1002 RECORD(DECL_REQUIRES_EXPR_BODY);
1003 RECORD(DECL_TYPE_ALIAS_TEMPLATE);
1004 RECORD(DECL_STATIC_ASSERT);
1005 RECORD(DECL_CXX_BASE_SPECIFIERS);
1006 RECORD(DECL_CXX_CTOR_INITIALIZERS);
1007 RECORD(DECL_INDIRECTFIELD);
1008 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
1009 RECORD(DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK);
1010 RECORD(DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION);
1011 RECORD(DECL_IMPORT);
1012 RECORD(DECL_OMP_THREADPRIVATE);
1013 RECORD(DECL_EMPTY);
1014 RECORD(DECL_OBJC_TYPE_PARAM);
1015 RECORD(DECL_OMP_CAPTUREDEXPR);
1016 RECORD(DECL_PRAGMA_COMMENT);
1017 RECORD(DECL_PRAGMA_DETECT_MISMATCH);
1018 RECORD(DECL_OMP_DECLARE_REDUCTION);
1019 RECORD(DECL_OMP_ALLOCATE);
1021 // Statements and Exprs can occur in the Decls and Types block.
1022 AddStmtsExprs(Stream, Record);
1024 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
1025 RECORD(PPD_MACRO_EXPANSION);
1026 RECORD(PPD_MACRO_DEFINITION);
1027 RECORD(PPD_INCLUSION_DIRECTIVE);
1029 // Decls and Types block.
1030 BLOCK(EXTENSION_BLOCK);
1031 RECORD(EXTENSION_METADATA);
1033 BLOCK(UNHASHED_CONTROL_BLOCK);
1034 RECORD(SIGNATURE);
1035 RECORD(AST_BLOCK_HASH);
1036 RECORD(DIAGNOSTIC_OPTIONS);
1037 RECORD(DIAG_PRAGMA_MAPPINGS);
1039 #undef RECORD
1040 #undef BLOCK
1041 Stream.ExitBlock();
1044 /// Prepares a path for being written to an AST file by converting it
1045 /// to an absolute path and removing nested './'s.
1047 /// \return \c true if the path was changed.
1048 static bool cleanPathForOutput(FileManager &FileMgr,
1049 SmallVectorImpl<char> &Path) {
1050 bool Changed = FileMgr.makeAbsolutePath(Path);
1051 return Changed | llvm::sys::path::remove_dots(Path);
1054 /// Adjusts the given filename to only write out the portion of the
1055 /// filename that is not part of the system root directory.
1057 /// \param Filename the file name to adjust.
1059 /// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
1060 /// the returned filename will be adjusted by this root directory.
1062 /// \returns either the original filename (if it needs no adjustment) or the
1063 /// adjusted filename (which points into the @p Filename parameter).
1064 static const char *
1065 adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
1066 assert(Filename && "No file name to adjust?");
1068 if (BaseDir.empty())
1069 return Filename;
1071 // Verify that the filename and the system root have the same prefix.
1072 unsigned Pos = 0;
1073 for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
1074 if (Filename[Pos] != BaseDir[Pos])
1075 return Filename; // Prefixes don't match.
1077 // We hit the end of the filename before we hit the end of the system root.
1078 if (!Filename[Pos])
1079 return Filename;
1081 // If there's not a path separator at the end of the base directory nor
1082 // immediately after it, then this isn't within the base directory.
1083 if (!llvm::sys::path::is_separator(Filename[Pos])) {
1084 if (!llvm::sys::path::is_separator(BaseDir.back()))
1085 return Filename;
1086 } else {
1087 // If the file name has a '/' at the current position, skip over the '/'.
1088 // We distinguish relative paths from absolute paths by the
1089 // absence of '/' at the beginning of relative paths.
1091 // FIXME: This is wrong. We distinguish them by asking if the path is
1092 // absolute, which isn't the same thing. And there might be multiple '/'s
1093 // in a row. Use a better mechanism to indicate whether we have emitted an
1094 // absolute or relative path.
1095 ++Pos;
1098 return Filename + Pos;
1101 std::pair<ASTFileSignature, ASTFileSignature>
1102 ASTWriter::createSignature(StringRef AllBytes, StringRef ASTBlockBytes) {
1103 llvm::SHA1 Hasher;
1104 Hasher.update(ASTBlockBytes);
1105 ASTFileSignature ASTBlockHash = ASTFileSignature::create(Hasher.result());
1107 // Add the remaining bytes (i.e. bytes before the unhashed control block that
1108 // are not part of the AST block).
1109 Hasher.update(
1110 AllBytes.take_front(ASTBlockBytes.bytes_end() - AllBytes.bytes_begin()));
1111 Hasher.update(
1112 AllBytes.take_back(AllBytes.bytes_end() - ASTBlockBytes.bytes_end()));
1113 ASTFileSignature Signature = ASTFileSignature::create(Hasher.result());
1115 return std::make_pair(ASTBlockHash, Signature);
1118 ASTFileSignature ASTWriter::writeUnhashedControlBlock(Preprocessor &PP,
1119 ASTContext &Context) {
1120 using namespace llvm;
1122 // Flush first to prepare the PCM hash (signature).
1123 Stream.FlushToWord();
1124 auto StartOfUnhashedControl = Stream.GetCurrentBitNo() >> 3;
1126 // Enter the block and prepare to write records.
1127 RecordData Record;
1128 Stream.EnterSubblock(UNHASHED_CONTROL_BLOCK_ID, 5);
1130 // For implicit modules, write the hash of the PCM as its signature.
1131 ASTFileSignature Signature;
1132 if (WritingModule &&
1133 PP.getHeaderSearchInfo().getHeaderSearchOpts().ModulesHashContent) {
1134 ASTFileSignature ASTBlockHash;
1135 auto ASTBlockStartByte = ASTBlockRange.first >> 3;
1136 auto ASTBlockByteLength = (ASTBlockRange.second >> 3) - ASTBlockStartByte;
1137 std::tie(ASTBlockHash, Signature) = createSignature(
1138 StringRef(Buffer.begin(), StartOfUnhashedControl),
1139 StringRef(Buffer.begin() + ASTBlockStartByte, ASTBlockByteLength));
1141 Record.append(ASTBlockHash.begin(), ASTBlockHash.end());
1142 Stream.EmitRecord(AST_BLOCK_HASH, Record);
1143 Record.clear();
1144 Record.append(Signature.begin(), Signature.end());
1145 Stream.EmitRecord(SIGNATURE, Record);
1146 Record.clear();
1149 // Diagnostic options.
1150 const auto &Diags = Context.getDiagnostics();
1151 const DiagnosticOptions &DiagOpts = Diags.getDiagnosticOptions();
1152 #define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1153 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1154 Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1155 #include "clang/Basic/DiagnosticOptions.def"
1156 Record.push_back(DiagOpts.Warnings.size());
1157 for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1158 AddString(DiagOpts.Warnings[I], Record);
1159 Record.push_back(DiagOpts.Remarks.size());
1160 for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1161 AddString(DiagOpts.Remarks[I], Record);
1162 // Note: we don't serialize the log or serialization file names, because they
1163 // are generally transient files and will almost always be overridden.
1164 Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1165 Record.clear();
1167 // Write out the diagnostic/pragma mappings.
1168 WritePragmaDiagnosticMappings(Diags, /* isModule = */ WritingModule);
1170 // Header search entry usage.
1171 auto HSEntryUsage = PP.getHeaderSearchInfo().computeUserEntryUsage();
1172 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1173 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_ENTRY_USAGE));
1174 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Number of bits.
1175 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Bit vector.
1176 unsigned HSUsageAbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1178 RecordData::value_type Record[] = {HEADER_SEARCH_ENTRY_USAGE,
1179 HSEntryUsage.size()};
1180 Stream.EmitRecordWithBlob(HSUsageAbbrevCode, Record, bytes(HSEntryUsage));
1183 // Leave the options block.
1184 Stream.ExitBlock();
1185 return Signature;
1188 /// Write the control block.
1189 void ASTWriter::WriteControlBlock(Preprocessor &PP, ASTContext &Context,
1190 StringRef isysroot) {
1191 using namespace llvm;
1193 Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
1194 RecordData Record;
1196 // Metadata
1197 auto MetadataAbbrev = std::make_shared<BitCodeAbbrev>();
1198 MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1199 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1200 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1201 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1202 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1203 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
1204 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
1205 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1206 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1207 unsigned MetadataAbbrevCode = Stream.EmitAbbrev(std::move(MetadataAbbrev));
1208 assert((!WritingModule || isysroot.empty()) &&
1209 "writing module as a relocatable PCH?");
1211 RecordData::value_type Record[] = {
1212 METADATA,
1213 VERSION_MAJOR,
1214 VERSION_MINOR,
1215 CLANG_VERSION_MAJOR,
1216 CLANG_VERSION_MINOR,
1217 !isysroot.empty(),
1218 IncludeTimestamps,
1219 ASTHasCompilerErrors};
1220 Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1221 getClangFullRepositoryVersion());
1224 if (WritingModule) {
1225 // Module name
1226 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1227 Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1228 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1229 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1230 RecordData::value_type Record[] = {MODULE_NAME};
1231 Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1234 if (WritingModule && WritingModule->Directory) {
1235 SmallString<128> BaseDir;
1236 if (PP.getHeaderSearchInfo().getHeaderSearchOpts().ModuleFileHomeIsCwd) {
1237 // Use the current working directory as the base path for all inputs.
1238 auto *CWD =
1239 Context.getSourceManager().getFileManager().getDirectory(".").get();
1240 BaseDir.assign(CWD->getName());
1241 } else {
1242 BaseDir.assign(WritingModule->Directory->getName());
1244 cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
1246 // If the home of the module is the current working directory, then we
1247 // want to pick up the cwd of the build process loading the module, not
1248 // our cwd, when we load this module.
1249 if (!(PP.getHeaderSearchInfo()
1250 .getHeaderSearchOpts()
1251 .ModuleMapFileHomeIsCwd ||
1252 PP.getHeaderSearchInfo().getHeaderSearchOpts().ModuleFileHomeIsCwd) ||
1253 WritingModule->Directory->getName() != StringRef(".")) {
1254 // Module directory.
1255 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1256 Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1257 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
1258 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1260 RecordData::value_type Record[] = {MODULE_DIRECTORY};
1261 Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
1264 // Write out all other paths relative to the base directory if possible.
1265 BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
1266 } else if (!isysroot.empty()) {
1267 // Write out paths relative to the sysroot if possible.
1268 BaseDirectory = std::string(isysroot);
1271 // Module map file
1272 if (WritingModule && WritingModule->Kind == Module::ModuleMapModule) {
1273 Record.clear();
1275 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
1276 AddPath(WritingModule->PresumedModuleMapFile.empty()
1277 ? Map.getModuleMapFileForUniquing(WritingModule)->getName()
1278 : StringRef(WritingModule->PresumedModuleMapFile),
1279 Record);
1281 // Additional module map files.
1282 if (auto *AdditionalModMaps =
1283 Map.getAdditionalModuleMapFiles(WritingModule)) {
1284 Record.push_back(AdditionalModMaps->size());
1285 SmallVector<const FileEntry *, 1> ModMaps(AdditionalModMaps->begin(),
1286 AdditionalModMaps->end());
1287 llvm::sort(ModMaps, [](const FileEntry *A, const FileEntry *B) {
1288 return A->getName() < B->getName();
1290 for (const FileEntry *F : ModMaps)
1291 AddPath(F->getName(), Record);
1292 } else {
1293 Record.push_back(0);
1296 Stream.EmitRecord(MODULE_MAP_FILE, Record);
1299 // Imports
1300 if (Chain) {
1301 serialization::ModuleManager &Mgr = Chain->getModuleManager();
1302 Record.clear();
1304 for (ModuleFile &M : Mgr) {
1305 // Skip modules that weren't directly imported.
1306 if (!M.isDirectlyImported())
1307 continue;
1309 Record.push_back((unsigned)M.Kind); // FIXME: Stable encoding
1310 AddSourceLocation(M.ImportLoc, Record);
1312 // If we have calculated signature, there is no need to store
1313 // the size or timestamp.
1314 Record.push_back(M.Signature ? 0 : M.File->getSize());
1315 Record.push_back(M.Signature ? 0 : getTimestampForOutput(M.File));
1317 llvm::append_range(Record, M.Signature);
1319 AddString(M.ModuleName, Record);
1320 AddPath(M.FileName, Record);
1322 Stream.EmitRecord(IMPORTS, Record);
1325 // Write the options block.
1326 Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
1328 // Language options.
1329 Record.clear();
1330 const LangOptions &LangOpts = Context.getLangOpts();
1331 #define LANGOPT(Name, Bits, Default, Description) \
1332 Record.push_back(LangOpts.Name);
1333 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1334 Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
1335 #include "clang/Basic/LangOptions.def"
1336 #define SANITIZER(NAME, ID) \
1337 Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
1338 #include "clang/Basic/Sanitizers.def"
1340 Record.push_back(LangOpts.ModuleFeatures.size());
1341 for (StringRef Feature : LangOpts.ModuleFeatures)
1342 AddString(Feature, Record);
1344 Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1345 AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
1347 AddString(LangOpts.CurrentModule, Record);
1349 // Comment options.
1350 Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
1351 for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
1352 AddString(I, Record);
1354 Record.push_back(LangOpts.CommentOpts.ParseAllComments);
1356 // OpenMP offloading options.
1357 Record.push_back(LangOpts.OMPTargetTriples.size());
1358 for (auto &T : LangOpts.OMPTargetTriples)
1359 AddString(T.getTriple(), Record);
1361 AddString(LangOpts.OMPHostIRFile, Record);
1363 Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1365 // Target options.
1366 Record.clear();
1367 const TargetInfo &Target = Context.getTargetInfo();
1368 const TargetOptions &TargetOpts = Target.getTargetOpts();
1369 AddString(TargetOpts.Triple, Record);
1370 AddString(TargetOpts.CPU, Record);
1371 AddString(TargetOpts.TuneCPU, Record);
1372 AddString(TargetOpts.ABI, Record);
1373 Record.push_back(TargetOpts.FeaturesAsWritten.size());
1374 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1375 AddString(TargetOpts.FeaturesAsWritten[I], Record);
1377 Record.push_back(TargetOpts.Features.size());
1378 for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1379 AddString(TargetOpts.Features[I], Record);
1381 Stream.EmitRecord(TARGET_OPTIONS, Record);
1383 // File system options.
1384 Record.clear();
1385 const FileSystemOptions &FSOpts =
1386 Context.getSourceManager().getFileManager().getFileSystemOpts();
1387 AddString(FSOpts.WorkingDir, Record);
1388 Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1390 // Header search options.
1391 Record.clear();
1392 const HeaderSearchOptions &HSOpts
1393 = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1394 AddString(HSOpts.Sysroot, Record);
1396 // Include entries.
1397 Record.push_back(HSOpts.UserEntries.size());
1398 for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1399 const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1400 AddString(Entry.Path, Record);
1401 Record.push_back(static_cast<unsigned>(Entry.Group));
1402 Record.push_back(Entry.IsFramework);
1403 Record.push_back(Entry.IgnoreSysRoot);
1406 // System header prefixes.
1407 Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1408 for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1409 AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1410 Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1413 AddString(HSOpts.ResourceDir, Record);
1414 AddString(HSOpts.ModuleCachePath, Record);
1415 AddString(HSOpts.ModuleUserBuildPath, Record);
1416 Record.push_back(HSOpts.DisableModuleHash);
1417 Record.push_back(HSOpts.ImplicitModuleMaps);
1418 Record.push_back(HSOpts.ModuleMapFileHomeIsCwd);
1419 Record.push_back(HSOpts.EnablePrebuiltImplicitModules);
1420 Record.push_back(HSOpts.UseBuiltinIncludes);
1421 Record.push_back(HSOpts.UseStandardSystemIncludes);
1422 Record.push_back(HSOpts.UseStandardCXXIncludes);
1423 Record.push_back(HSOpts.UseLibcxx);
1424 // Write out the specific module cache path that contains the module files.
1425 AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
1426 Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1428 // Preprocessor options.
1429 Record.clear();
1430 const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1432 // Macro definitions.
1433 Record.push_back(PPOpts.Macros.size());
1434 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1435 AddString(PPOpts.Macros[I].first, Record);
1436 Record.push_back(PPOpts.Macros[I].second);
1439 // Includes
1440 Record.push_back(PPOpts.Includes.size());
1441 for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1442 AddString(PPOpts.Includes[I], Record);
1444 // Macro includes
1445 Record.push_back(PPOpts.MacroIncludes.size());
1446 for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1447 AddString(PPOpts.MacroIncludes[I], Record);
1449 Record.push_back(PPOpts.UsePredefines);
1450 // Detailed record is important since it is used for the module cache hash.
1451 Record.push_back(PPOpts.DetailedRecord);
1452 AddString(PPOpts.ImplicitPCHInclude, Record);
1453 Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1454 Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1456 // Leave the options block.
1457 Stream.ExitBlock();
1459 // Original file name and file ID
1460 SourceManager &SM = Context.getSourceManager();
1461 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1462 auto FileAbbrev = std::make_shared<BitCodeAbbrev>();
1463 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1464 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
1465 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1466 unsigned FileAbbrevCode = Stream.EmitAbbrev(std::move(FileAbbrev));
1468 Record.clear();
1469 Record.push_back(ORIGINAL_FILE);
1470 Record.push_back(SM.getMainFileID().getOpaqueValue());
1471 EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
1474 Record.clear();
1475 Record.push_back(SM.getMainFileID().getOpaqueValue());
1476 Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1478 std::set<const FileEntry *> AffectingModuleMaps;
1479 if (WritingModule) {
1480 AffectingModuleMaps =
1481 GetAllModuleMaps(PP.getHeaderSearchInfo(), WritingModule);
1484 WriteInputFiles(Context.SourceMgr,
1485 PP.getHeaderSearchInfo().getHeaderSearchOpts(),
1486 AffectingModuleMaps);
1487 Stream.ExitBlock();
1490 namespace {
1492 /// An input file.
1493 struct InputFileEntry {
1494 const FileEntry *File;
1495 bool IsSystemFile;
1496 bool IsTransient;
1497 bool BufferOverridden;
1498 bool IsTopLevelModuleMap;
1499 uint32_t ContentHash[2];
1502 } // namespace
1504 void ASTWriter::WriteInputFiles(
1505 SourceManager &SourceMgr, HeaderSearchOptions &HSOpts,
1506 std::set<const FileEntry *> &AffectingModuleMaps) {
1507 using namespace llvm;
1509 Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
1511 // Create input-file abbreviation.
1512 auto IFAbbrev = std::make_shared<BitCodeAbbrev>();
1513 IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
1514 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
1515 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1516 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1517 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
1518 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
1519 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Module map
1520 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1521 unsigned IFAbbrevCode = Stream.EmitAbbrev(std::move(IFAbbrev));
1523 // Create input file hash abbreviation.
1524 auto IFHAbbrev = std::make_shared<BitCodeAbbrev>();
1525 IFHAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_HASH));
1526 IFHAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1527 IFHAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1528 unsigned IFHAbbrevCode = Stream.EmitAbbrev(std::move(IFHAbbrev));
1530 // Get all ContentCache objects for files, sorted by whether the file is a
1531 // system one or not. System files go at the back, users files at the front.
1532 std::deque<InputFileEntry> SortedFiles;
1533 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1534 // Get this source location entry.
1535 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1536 assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
1538 // We only care about file entries that were not overridden.
1539 if (!SLoc->isFile())
1540 continue;
1541 const SrcMgr::FileInfo &File = SLoc->getFile();
1542 const SrcMgr::ContentCache *Cache = &File.getContentCache();
1543 if (!Cache->OrigEntry)
1544 continue;
1546 if (isModuleMap(File.getFileCharacteristic()) &&
1547 !isSystem(File.getFileCharacteristic()) &&
1548 !AffectingModuleMaps.empty() &&
1549 AffectingModuleMaps.find(Cache->OrigEntry) ==
1550 AffectingModuleMaps.end()) {
1551 SkippedModuleMaps.insert(Cache->OrigEntry);
1552 // Do not emit modulemaps that do not affect current module.
1553 continue;
1556 InputFileEntry Entry;
1557 Entry.File = Cache->OrigEntry;
1558 Entry.IsSystemFile = isSystem(File.getFileCharacteristic());
1559 Entry.IsTransient = Cache->IsTransient;
1560 Entry.BufferOverridden = Cache->BufferOverridden;
1561 Entry.IsTopLevelModuleMap = isModuleMap(File.getFileCharacteristic()) &&
1562 File.getIncludeLoc().isInvalid();
1564 auto ContentHash = hash_code(-1);
1565 if (PP->getHeaderSearchInfo()
1566 .getHeaderSearchOpts()
1567 .ValidateASTInputFilesContent) {
1568 auto MemBuff = Cache->getBufferIfLoaded();
1569 if (MemBuff)
1570 ContentHash = hash_value(MemBuff->getBuffer());
1571 else
1572 // FIXME: The path should be taken from the FileEntryRef.
1573 PP->Diag(SourceLocation(), diag::err_module_unable_to_hash_content)
1574 << Entry.File->getName();
1576 auto CH = llvm::APInt(64, ContentHash);
1577 Entry.ContentHash[0] =
1578 static_cast<uint32_t>(CH.getLoBits(32).getZExtValue());
1579 Entry.ContentHash[1] =
1580 static_cast<uint32_t>(CH.getHiBits(32).getZExtValue());
1582 if (Entry.IsSystemFile)
1583 SortedFiles.push_back(Entry);
1584 else
1585 SortedFiles.push_front(Entry);
1588 unsigned UserFilesNum = 0;
1589 // Write out all of the input files.
1590 std::vector<uint64_t> InputFileOffsets;
1591 for (const auto &Entry : SortedFiles) {
1592 uint32_t &InputFileID = InputFileIDs[Entry.File];
1593 if (InputFileID != 0)
1594 continue; // already recorded this file.
1596 // Record this entry's offset.
1597 InputFileOffsets.push_back(Stream.GetCurrentBitNo());
1599 InputFileID = InputFileOffsets.size();
1601 if (!Entry.IsSystemFile)
1602 ++UserFilesNum;
1604 // Emit size/modification time for this file.
1605 // And whether this file was overridden.
1607 RecordData::value_type Record[] = {
1608 INPUT_FILE,
1609 InputFileOffsets.size(),
1610 (uint64_t)Entry.File->getSize(),
1611 (uint64_t)getTimestampForOutput(Entry.File),
1612 Entry.BufferOverridden,
1613 Entry.IsTransient,
1614 Entry.IsTopLevelModuleMap};
1616 // FIXME: The path should be taken from the FileEntryRef.
1617 EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName());
1620 // Emit content hash for this file.
1622 RecordData::value_type Record[] = {INPUT_FILE_HASH, Entry.ContentHash[0],
1623 Entry.ContentHash[1]};
1624 Stream.EmitRecordWithAbbrev(IFHAbbrevCode, Record);
1628 Stream.ExitBlock();
1630 // Create input file offsets abbreviation.
1631 auto OffsetsAbbrev = std::make_shared<BitCodeAbbrev>();
1632 OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1633 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
1634 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1635 // input files
1636 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
1637 unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(std::move(OffsetsAbbrev));
1639 // Write input file offsets.
1640 RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
1641 InputFileOffsets.size(), UserFilesNum};
1642 Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
1645 //===----------------------------------------------------------------------===//
1646 // Source Manager Serialization
1647 //===----------------------------------------------------------------------===//
1649 /// Create an abbreviation for the SLocEntry that refers to a
1650 /// file.
1651 static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1652 using namespace llvm;
1654 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1655 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1656 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1657 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1658 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
1659 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1660 // FileEntry fields.
1661 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
1662 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
1663 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1664 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
1665 return Stream.EmitAbbrev(std::move(Abbrev));
1668 /// Create an abbreviation for the SLocEntry that refers to a
1669 /// buffer.
1670 static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
1671 using namespace llvm;
1673 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1674 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
1675 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1676 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1677 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
1678 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1679 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
1680 return Stream.EmitAbbrev(std::move(Abbrev));
1683 /// Create an abbreviation for the SLocEntry that refers to a
1684 /// buffer's blob.
1685 static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
1686 bool Compressed) {
1687 using namespace llvm;
1689 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1690 Abbrev->Add(BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED
1691 : SM_SLOC_BUFFER_BLOB));
1692 if (Compressed)
1693 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
1694 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
1695 return Stream.EmitAbbrev(std::move(Abbrev));
1698 /// Create an abbreviation for the SLocEntry that refers to a macro
1699 /// expansion.
1700 static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
1701 using namespace llvm;
1703 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1704 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
1705 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1706 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1707 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Start location
1708 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // End location
1709 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Is token range
1710 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
1711 return Stream.EmitAbbrev(std::move(Abbrev));
1714 /// Emit key length and data length as ULEB-encoded data, and return them as a
1715 /// pair.
1716 static std::pair<unsigned, unsigned>
1717 emitULEBKeyDataLength(unsigned KeyLen, unsigned DataLen, raw_ostream &Out) {
1718 llvm::encodeULEB128(KeyLen, Out);
1719 llvm::encodeULEB128(DataLen, Out);
1720 return std::make_pair(KeyLen, DataLen);
1723 namespace {
1725 // Trait used for the on-disk hash table of header search information.
1726 class HeaderFileInfoTrait {
1727 ASTWriter &Writer;
1729 // Keep track of the framework names we've used during serialization.
1730 SmallString<128> FrameworkStringData;
1731 llvm::StringMap<unsigned> FrameworkNameOffset;
1733 public:
1734 HeaderFileInfoTrait(ASTWriter &Writer) : Writer(Writer) {}
1736 struct key_type {
1737 StringRef Filename;
1738 off_t Size;
1739 time_t ModTime;
1741 using key_type_ref = const key_type &;
1743 using UnresolvedModule =
1744 llvm::PointerIntPair<Module *, 2, ModuleMap::ModuleHeaderRole>;
1746 struct data_type {
1747 const HeaderFileInfo &HFI;
1748 ArrayRef<ModuleMap::KnownHeader> KnownHeaders;
1749 UnresolvedModule Unresolved;
1751 using data_type_ref = const data_type &;
1753 using hash_value_type = unsigned;
1754 using offset_type = unsigned;
1756 hash_value_type ComputeHash(key_type_ref key) {
1757 // The hash is based only on size/time of the file, so that the reader can
1758 // match even when symlinking or excess path elements ("foo/../", "../")
1759 // change the form of the name. However, complete path is still the key.
1760 return llvm::hash_combine(key.Size, key.ModTime);
1763 std::pair<unsigned, unsigned>
1764 EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
1765 unsigned KeyLen = key.Filename.size() + 1 + 8 + 8;
1766 unsigned DataLen = 1 + 4 + 4;
1767 for (auto ModInfo : Data.KnownHeaders)
1768 if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
1769 DataLen += 4;
1770 if (Data.Unresolved.getPointer())
1771 DataLen += 4;
1772 return emitULEBKeyDataLength(KeyLen, DataLen, Out);
1775 void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
1776 using namespace llvm::support;
1778 endian::Writer LE(Out, little);
1779 LE.write<uint64_t>(key.Size);
1780 KeyLen -= 8;
1781 LE.write<uint64_t>(key.ModTime);
1782 KeyLen -= 8;
1783 Out.write(key.Filename.data(), KeyLen);
1786 void EmitData(raw_ostream &Out, key_type_ref key,
1787 data_type_ref Data, unsigned DataLen) {
1788 using namespace llvm::support;
1790 endian::Writer LE(Out, little);
1791 uint64_t Start = Out.tell(); (void)Start;
1793 unsigned char Flags = (Data.HFI.isImport << 5)
1794 | (Data.HFI.isPragmaOnce << 4)
1795 | (Data.HFI.DirInfo << 1)
1796 | Data.HFI.IndexHeaderMapHeader;
1797 LE.write<uint8_t>(Flags);
1799 if (!Data.HFI.ControllingMacro)
1800 LE.write<uint32_t>(Data.HFI.ControllingMacroID);
1801 else
1802 LE.write<uint32_t>(Writer.getIdentifierRef(Data.HFI.ControllingMacro));
1804 unsigned Offset = 0;
1805 if (!Data.HFI.Framework.empty()) {
1806 // If this header refers into a framework, save the framework name.
1807 llvm::StringMap<unsigned>::iterator Pos
1808 = FrameworkNameOffset.find(Data.HFI.Framework);
1809 if (Pos == FrameworkNameOffset.end()) {
1810 Offset = FrameworkStringData.size() + 1;
1811 FrameworkStringData.append(Data.HFI.Framework);
1812 FrameworkStringData.push_back(0);
1814 FrameworkNameOffset[Data.HFI.Framework] = Offset;
1815 } else
1816 Offset = Pos->second;
1818 LE.write<uint32_t>(Offset);
1820 auto EmitModule = [&](Module *M, ModuleMap::ModuleHeaderRole Role) {
1821 if (uint32_t ModID = Writer.getLocalOrImportedSubmoduleID(M)) {
1822 uint32_t Value = (ModID << 2) | (unsigned)Role;
1823 assert((Value >> 2) == ModID && "overflow in header module info");
1824 LE.write<uint32_t>(Value);
1828 // FIXME: If the header is excluded, we should write out some
1829 // record of that fact.
1830 for (auto ModInfo : Data.KnownHeaders)
1831 EmitModule(ModInfo.getModule(), ModInfo.getRole());
1832 if (Data.Unresolved.getPointer())
1833 EmitModule(Data.Unresolved.getPointer(), Data.Unresolved.getInt());
1835 assert(Out.tell() - Start == DataLen && "Wrong data length");
1838 const char *strings_begin() const { return FrameworkStringData.begin(); }
1839 const char *strings_end() const { return FrameworkStringData.end(); }
1842 } // namespace
1844 /// Write the header search block for the list of files that
1846 /// \param HS The header search structure to save.
1847 void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
1848 HeaderFileInfoTrait GeneratorTrait(*this);
1849 llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
1850 SmallVector<const char *, 4> SavedStrings;
1851 unsigned NumHeaderSearchEntries = 0;
1853 // Find all unresolved headers for the current module. We generally will
1854 // have resolved them before we get here, but not necessarily: we might be
1855 // compiling a preprocessed module, where there is no requirement for the
1856 // original files to exist any more.
1857 const HeaderFileInfo Empty; // So we can take a reference.
1858 if (WritingModule) {
1859 llvm::SmallVector<Module *, 16> Worklist(1, WritingModule);
1860 while (!Worklist.empty()) {
1861 Module *M = Worklist.pop_back_val();
1862 // We don't care about headers in unimportable submodules.
1863 if (M->isUnimportable())
1864 continue;
1866 // Map to disk files where possible, to pick up any missing stat
1867 // information. This also means we don't need to check the unresolved
1868 // headers list when emitting resolved headers in the first loop below.
1869 // FIXME: It'd be preferable to avoid doing this if we were given
1870 // sufficient stat information in the module map.
1871 HS.getModuleMap().resolveHeaderDirectives(M, /*File=*/llvm::None);
1873 // If the file didn't exist, we can still create a module if we were given
1874 // enough information in the module map.
1875 for (auto U : M->MissingHeaders) {
1876 // Check that we were given enough information to build a module
1877 // without this file existing on disk.
1878 if (!U.Size || (!U.ModTime && IncludeTimestamps)) {
1879 PP->Diag(U.FileNameLoc, diag::err_module_no_size_mtime_for_header)
1880 << WritingModule->getFullModuleName() << U.Size.has_value()
1881 << U.FileName;
1882 continue;
1885 // Form the effective relative pathname for the file.
1886 SmallString<128> Filename(M->Directory->getName());
1887 llvm::sys::path::append(Filename, U.FileName);
1888 PreparePathForOutput(Filename);
1890 StringRef FilenameDup = strdup(Filename.c_str());
1891 SavedStrings.push_back(FilenameDup.data());
1893 HeaderFileInfoTrait::key_type Key = {
1894 FilenameDup, *U.Size, IncludeTimestamps ? *U.ModTime : 0
1896 HeaderFileInfoTrait::data_type Data = {
1897 Empty, {}, {M, ModuleMap::headerKindToRole(U.Kind)}
1899 // FIXME: Deal with cases where there are multiple unresolved header
1900 // directives in different submodules for the same header.
1901 Generator.insert(Key, Data, GeneratorTrait);
1902 ++NumHeaderSearchEntries;
1905 Worklist.append(M->submodule_begin(), M->submodule_end());
1909 SmallVector<const FileEntry *, 16> FilesByUID;
1910 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
1912 if (FilesByUID.size() > HS.header_file_size())
1913 FilesByUID.resize(HS.header_file_size());
1915 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1916 const FileEntry *File = FilesByUID[UID];
1917 if (!File)
1918 continue;
1920 // Get the file info. This will load info from the external source if
1921 // necessary. Skip emitting this file if we have no information on it
1922 // as a header file (in which case HFI will be null) or if it hasn't
1923 // changed since it was loaded. Also skip it if it's for a modular header
1924 // from a different module; in that case, we rely on the module(s)
1925 // containing the header to provide this information.
1926 const HeaderFileInfo *HFI =
1927 HS.getExistingFileInfo(File, /*WantExternal*/!Chain);
1928 if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
1929 continue;
1931 // Massage the file path into an appropriate form.
1932 StringRef Filename = File->getName();
1933 SmallString<128> FilenameTmp(Filename);
1934 if (PreparePathForOutput(FilenameTmp)) {
1935 // If we performed any translation on the file name at all, we need to
1936 // save this string, since the generator will refer to it later.
1937 Filename = StringRef(strdup(FilenameTmp.c_str()));
1938 SavedStrings.push_back(Filename.data());
1941 HeaderFileInfoTrait::key_type Key = {
1942 Filename, File->getSize(), getTimestampForOutput(File)
1944 HeaderFileInfoTrait::data_type Data = {
1945 *HFI, HS.getModuleMap().findResolvedModulesForHeader(File), {}
1947 Generator.insert(Key, Data, GeneratorTrait);
1948 ++NumHeaderSearchEntries;
1951 // Create the on-disk hash table in a buffer.
1952 SmallString<4096> TableData;
1953 uint32_t BucketOffset;
1955 using namespace llvm::support;
1957 llvm::raw_svector_ostream Out(TableData);
1958 // Make sure that no bucket is at offset 0
1959 endian::write<uint32_t>(Out, 0, little);
1960 BucketOffset = Generator.Emit(Out, GeneratorTrait);
1963 // Create a blob abbreviation
1964 using namespace llvm;
1966 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1967 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1968 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1969 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1970 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1971 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1972 unsigned TableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
1974 // Write the header search table
1975 RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
1976 NumHeaderSearchEntries, TableData.size()};
1977 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
1978 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
1980 // Free all of the strings we had to duplicate.
1981 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
1982 free(const_cast<char *>(SavedStrings[I]));
1985 static void emitBlob(llvm::BitstreamWriter &Stream, StringRef Blob,
1986 unsigned SLocBufferBlobCompressedAbbrv,
1987 unsigned SLocBufferBlobAbbrv) {
1988 using RecordDataType = ASTWriter::RecordData::value_type;
1990 // Compress the buffer if possible. We expect that almost all PCM
1991 // consumers will not want its contents.
1992 SmallVector<uint8_t, 0> CompressedBuffer;
1993 if (llvm::compression::zlib::isAvailable()) {
1994 llvm::compression::zlib::compress(
1995 llvm::arrayRefFromStringRef(Blob.drop_back(1)), CompressedBuffer);
1996 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED, Blob.size() - 1};
1997 Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
1998 llvm::toStringRef(CompressedBuffer));
1999 return;
2002 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB};
2003 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob);
2006 /// Writes the block containing the serialized form of the
2007 /// source manager.
2009 /// TODO: We should probably use an on-disk hash table (stored in a
2010 /// blob), indexed based on the file name, so that we only create
2011 /// entries for files that we actually need. In the common case (no
2012 /// errors), we probably won't have to create file entries for any of
2013 /// the files in the AST.
2014 void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
2015 const Preprocessor &PP) {
2016 RecordData Record;
2018 // Enter the source manager block.
2019 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4);
2020 const uint64_t SourceManagerBlockOffset = Stream.GetCurrentBitNo();
2022 // Abbreviations for the various kinds of source-location entries.
2023 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
2024 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
2025 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false);
2026 unsigned SLocBufferBlobCompressedAbbrv =
2027 CreateSLocBufferBlobAbbrev(Stream, true);
2028 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
2030 // Write out the source location entry table. We skip the first
2031 // entry, which is always the same dummy entry.
2032 std::vector<uint32_t> SLocEntryOffsets;
2033 uint64_t SLocEntryOffsetsBase = Stream.GetCurrentBitNo();
2034 RecordData PreloadSLocs;
2035 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
2036 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
2037 I != N; ++I) {
2038 // Get this source location entry.
2039 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
2040 FileID FID = FileID::get(I);
2041 assert(&SourceMgr.getSLocEntry(FID) == SLoc);
2043 // Record the offset of this source-location entry.
2044 uint64_t Offset = Stream.GetCurrentBitNo() - SLocEntryOffsetsBase;
2045 assert((Offset >> 32) == 0 && "SLocEntry offset too large");
2046 SLocEntryOffsets.push_back(Offset);
2048 // Figure out which record code to use.
2049 unsigned Code;
2050 if (SLoc->isFile()) {
2051 const SrcMgr::ContentCache *Cache = &SLoc->getFile().getContentCache();
2052 if (Cache->OrigEntry) {
2053 Code = SM_SLOC_FILE_ENTRY;
2054 } else
2055 Code = SM_SLOC_BUFFER_ENTRY;
2056 } else
2057 Code = SM_SLOC_EXPANSION_ENTRY;
2058 Record.clear();
2059 Record.push_back(Code);
2061 // Starting offset of this entry within this module, so skip the dummy.
2062 Record.push_back(SLoc->getOffset() - 2);
2063 if (SLoc->isFile()) {
2064 const SrcMgr::FileInfo &File = SLoc->getFile();
2065 const SrcMgr::ContentCache *Content = &File.getContentCache();
2066 if (Content->OrigEntry && !SkippedModuleMaps.empty() &&
2067 SkippedModuleMaps.find(Content->OrigEntry) !=
2068 SkippedModuleMaps.end()) {
2069 // Do not emit files that were not listed as inputs.
2070 continue;
2072 AddSourceLocation(File.getIncludeLoc(), Record);
2073 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
2074 Record.push_back(File.hasLineDirectives());
2076 bool EmitBlob = false;
2077 if (Content->OrigEntry) {
2078 assert(Content->OrigEntry == Content->ContentsEntry &&
2079 "Writing to AST an overridden file is not supported");
2081 // The source location entry is a file. Emit input file ID.
2082 assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
2083 Record.push_back(InputFileIDs[Content->OrigEntry]);
2085 Record.push_back(File.NumCreatedFIDs);
2087 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
2088 if (FDI != FileDeclIDs.end()) {
2089 Record.push_back(FDI->second->FirstDeclIndex);
2090 Record.push_back(FDI->second->DeclIDs.size());
2091 } else {
2092 Record.push_back(0);
2093 Record.push_back(0);
2096 Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
2098 if (Content->BufferOverridden || Content->IsTransient)
2099 EmitBlob = true;
2100 } else {
2101 // The source location entry is a buffer. The blob associated
2102 // with this entry contains the contents of the buffer.
2104 // We add one to the size so that we capture the trailing NULL
2105 // that is required by llvm::MemoryBuffer::getMemBuffer (on
2106 // the reader side).
2107 llvm::Optional<llvm::MemoryBufferRef> Buffer =
2108 Content->getBufferOrNone(PP.getDiagnostics(), PP.getFileManager());
2109 StringRef Name = Buffer ? Buffer->getBufferIdentifier() : "";
2110 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
2111 StringRef(Name.data(), Name.size() + 1));
2112 EmitBlob = true;
2114 if (Name == "<built-in>")
2115 PreloadSLocs.push_back(SLocEntryOffsets.size());
2118 if (EmitBlob) {
2119 // Include the implicit terminating null character in the on-disk buffer
2120 // if we're writing it uncompressed.
2121 llvm::Optional<llvm::MemoryBufferRef> Buffer =
2122 Content->getBufferOrNone(PP.getDiagnostics(), PP.getFileManager());
2123 if (!Buffer)
2124 Buffer = llvm::MemoryBufferRef("<<<INVALID BUFFER>>>", "");
2125 StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
2126 emitBlob(Stream, Blob, SLocBufferBlobCompressedAbbrv,
2127 SLocBufferBlobAbbrv);
2129 } else {
2130 // The source location entry is a macro expansion.
2131 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
2132 LocSeq::State Seq;
2133 AddSourceLocation(Expansion.getSpellingLoc(), Record, Seq);
2134 AddSourceLocation(Expansion.getExpansionLocStart(), Record, Seq);
2135 AddSourceLocation(Expansion.isMacroArgExpansion()
2136 ? SourceLocation()
2137 : Expansion.getExpansionLocEnd(),
2138 Record, Seq);
2139 Record.push_back(Expansion.isExpansionTokenRange());
2141 // Compute the token length for this macro expansion.
2142 SourceLocation::UIntTy NextOffset = SourceMgr.getNextLocalOffset();
2143 if (I + 1 != N)
2144 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
2145 Record.push_back(NextOffset - SLoc->getOffset() - 1);
2146 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
2150 Stream.ExitBlock();
2152 if (SLocEntryOffsets.empty())
2153 return;
2155 // Write the source-location offsets table into the AST block. This
2156 // table is used for lazily loading source-location information.
2157 using namespace llvm;
2159 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2160 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
2161 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
2162 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
2163 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // base offset
2164 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
2165 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2167 RecordData::value_type Record[] = {
2168 SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
2169 SourceMgr.getNextLocalOffset() - 1 /* skip dummy */,
2170 SLocEntryOffsetsBase - SourceManagerBlockOffset};
2171 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
2172 bytes(SLocEntryOffsets));
2174 // Write the source location entry preloads array, telling the AST
2175 // reader which source locations entries it should load eagerly.
2176 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
2178 // Write the line table. It depends on remapping working, so it must come
2179 // after the source location offsets.
2180 if (SourceMgr.hasLineTable()) {
2181 LineTableInfo &LineTable = SourceMgr.getLineTable();
2183 Record.clear();
2185 // Emit the needed file names.
2186 llvm::DenseMap<int, int> FilenameMap;
2187 FilenameMap[-1] = -1; // For unspecified filenames.
2188 for (const auto &L : LineTable) {
2189 if (L.first.ID < 0)
2190 continue;
2191 for (auto &LE : L.second) {
2192 if (FilenameMap.insert(std::make_pair(LE.FilenameID,
2193 FilenameMap.size() - 1)).second)
2194 AddPath(LineTable.getFilename(LE.FilenameID), Record);
2197 Record.push_back(0);
2199 // Emit the line entries
2200 for (const auto &L : LineTable) {
2201 // Only emit entries for local files.
2202 if (L.first.ID < 0)
2203 continue;
2205 // Emit the file ID
2206 Record.push_back(L.first.ID);
2208 // Emit the line entries
2209 Record.push_back(L.second.size());
2210 for (const auto &LE : L.second) {
2211 Record.push_back(LE.FileOffset);
2212 Record.push_back(LE.LineNo);
2213 Record.push_back(FilenameMap[LE.FilenameID]);
2214 Record.push_back((unsigned)LE.FileKind);
2215 Record.push_back(LE.IncludeOffset);
2219 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
2223 //===----------------------------------------------------------------------===//
2224 // Preprocessor Serialization
2225 //===----------------------------------------------------------------------===//
2227 static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
2228 const Preprocessor &PP) {
2229 if (MacroInfo *MI = MD->getMacroInfo())
2230 if (MI->isBuiltinMacro())
2231 return true;
2233 if (IsModule) {
2234 SourceLocation Loc = MD->getLocation();
2235 if (Loc.isInvalid())
2236 return true;
2237 if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
2238 return true;
2241 return false;
2244 void ASTWriter::writeIncludedFiles(raw_ostream &Out, const Preprocessor &PP) {
2245 using namespace llvm::support;
2247 const Preprocessor::IncludedFilesSet &IncludedFiles = PP.getIncludedFiles();
2249 std::vector<uint32_t> IncludedInputFileIDs;
2250 IncludedInputFileIDs.reserve(IncludedFiles.size());
2252 for (const FileEntry *File : IncludedFiles) {
2253 auto InputFileIt = InputFileIDs.find(File);
2254 if (InputFileIt == InputFileIDs.end())
2255 continue;
2256 IncludedInputFileIDs.push_back(InputFileIt->second);
2259 llvm::sort(IncludedInputFileIDs);
2261 endian::Writer LE(Out, little);
2262 LE.write<uint32_t>(IncludedInputFileIDs.size());
2263 for (uint32_t ID : IncludedInputFileIDs)
2264 LE.write<uint32_t>(ID);
2267 /// Writes the block containing the serialized form of the
2268 /// preprocessor.
2269 void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
2270 uint64_t MacroOffsetsBase = Stream.GetCurrentBitNo();
2272 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
2273 if (PPRec)
2274 WritePreprocessorDetail(*PPRec, MacroOffsetsBase);
2276 RecordData Record;
2277 RecordData ModuleMacroRecord;
2279 // If the preprocessor __COUNTER__ value has been bumped, remember it.
2280 if (PP.getCounterValue() != 0) {
2281 RecordData::value_type Record[] = {PP.getCounterValue()};
2282 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
2285 // If we have a recorded #pragma assume_nonnull, remember it so it can be
2286 // replayed when the preamble terminates into the main file.
2287 SourceLocation AssumeNonNullLoc =
2288 PP.getPreambleRecordedPragmaAssumeNonNullLoc();
2289 if (AssumeNonNullLoc.isValid()) {
2290 assert(PP.isRecordingPreamble());
2291 AddSourceLocation(AssumeNonNullLoc, Record);
2292 Stream.EmitRecord(PP_ASSUME_NONNULL_LOC, Record);
2293 Record.clear();
2296 if (PP.isRecordingPreamble() && PP.hasRecordedPreamble()) {
2297 assert(!IsModule);
2298 auto SkipInfo = PP.getPreambleSkipInfo();
2299 if (SkipInfo) {
2300 Record.push_back(true);
2301 AddSourceLocation(SkipInfo->HashTokenLoc, Record);
2302 AddSourceLocation(SkipInfo->IfTokenLoc, Record);
2303 Record.push_back(SkipInfo->FoundNonSkipPortion);
2304 Record.push_back(SkipInfo->FoundElse);
2305 AddSourceLocation(SkipInfo->ElseLoc, Record);
2306 } else {
2307 Record.push_back(false);
2309 for (const auto &Cond : PP.getPreambleConditionalStack()) {
2310 AddSourceLocation(Cond.IfLoc, Record);
2311 Record.push_back(Cond.WasSkipping);
2312 Record.push_back(Cond.FoundNonSkip);
2313 Record.push_back(Cond.FoundElse);
2315 Stream.EmitRecord(PP_CONDITIONAL_STACK, Record);
2316 Record.clear();
2319 // Enter the preprocessor block.
2320 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
2322 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
2323 // FIXME: Include a location for the use, and say which one was used.
2324 if (PP.SawDateOrTime())
2325 PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
2327 // Loop over all the macro directives that are live at the end of the file,
2328 // emitting each to the PP section.
2330 // Construct the list of identifiers with macro directives that need to be
2331 // serialized.
2332 SmallVector<const IdentifierInfo *, 128> MacroIdentifiers;
2333 for (auto &Id : PP.getIdentifierTable())
2334 if (Id.second->hadMacroDefinition() &&
2335 (!Id.second->isFromAST() ||
2336 Id.second->hasChangedSinceDeserialization()))
2337 MacroIdentifiers.push_back(Id.second);
2338 // Sort the set of macro definitions that need to be serialized by the
2339 // name of the macro, to provide a stable ordering.
2340 llvm::sort(MacroIdentifiers, llvm::deref<std::less<>>());
2342 // Emit the macro directives as a list and associate the offset with the
2343 // identifier they belong to.
2344 for (const IdentifierInfo *Name : MacroIdentifiers) {
2345 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name);
2346 uint64_t StartOffset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2347 assert((StartOffset >> 32) == 0 && "Macro identifiers offset too large");
2349 // Write out any exported module macros.
2350 bool EmittedModuleMacros = false;
2351 // C+=20 Header Units are compiled module interfaces, but they preserve
2352 // macros that are live (i.e. have a defined value) at the end of the
2353 // compilation. So when writing a header unit, we preserve only the final
2354 // value of each macro (and discard any that are undefined). Header units
2355 // do not have sub-modules (although they might import other header units).
2356 // PCH files, conversely, retain the history of each macro's define/undef
2357 // and of leaf macros in sub modules.
2358 if (IsModule && WritingModule->isHeaderUnit()) {
2359 // This is for the main TU when it is a C++20 header unit.
2360 // We preserve the final state of defined macros, and we do not emit ones
2361 // that are undefined.
2362 if (!MD || shouldIgnoreMacro(MD, IsModule, PP) ||
2363 MD->getKind() == MacroDirective::MD_Undefine)
2364 continue;
2365 AddSourceLocation(MD->getLocation(), Record);
2366 Record.push_back(MD->getKind());
2367 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
2368 Record.push_back(getMacroRef(DefMD->getInfo(), Name));
2369 } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
2370 Record.push_back(VisMD->isPublic());
2372 ModuleMacroRecord.push_back(getSubmoduleID(WritingModule));
2373 ModuleMacroRecord.push_back(getMacroRef(MD->getMacroInfo(), Name));
2374 Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2375 ModuleMacroRecord.clear();
2376 EmittedModuleMacros = true;
2377 } else {
2378 // Emit the macro directives in reverse source order.
2379 for (; MD; MD = MD->getPrevious()) {
2380 // Once we hit an ignored macro, we're done: the rest of the chain
2381 // will all be ignored macros.
2382 if (shouldIgnoreMacro(MD, IsModule, PP))
2383 break;
2384 AddSourceLocation(MD->getLocation(), Record);
2385 Record.push_back(MD->getKind());
2386 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
2387 Record.push_back(getMacroRef(DefMD->getInfo(), Name));
2388 } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
2389 Record.push_back(VisMD->isPublic());
2393 // We write out exported module macros for PCH as well.
2394 auto Leafs = PP.getLeafModuleMacros(Name);
2395 SmallVector<ModuleMacro *, 8> Worklist(Leafs.begin(), Leafs.end());
2396 llvm::DenseMap<ModuleMacro *, unsigned> Visits;
2397 while (!Worklist.empty()) {
2398 auto *Macro = Worklist.pop_back_val();
2400 // Emit a record indicating this submodule exports this macro.
2401 ModuleMacroRecord.push_back(getSubmoduleID(Macro->getOwningModule()));
2402 ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
2403 for (auto *M : Macro->overrides())
2404 ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
2406 Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2407 ModuleMacroRecord.clear();
2409 // Enqueue overridden macros once we've visited all their ancestors.
2410 for (auto *M : Macro->overrides())
2411 if (++Visits[M] == M->getNumOverridingMacros())
2412 Worklist.push_back(M);
2414 EmittedModuleMacros = true;
2417 if (Record.empty() && !EmittedModuleMacros)
2418 continue;
2420 IdentMacroDirectivesOffsetMap[Name] = StartOffset;
2421 Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2422 Record.clear();
2425 /// Offsets of each of the macros into the bitstream, indexed by
2426 /// the local macro ID
2428 /// For each identifier that is associated with a macro, this map
2429 /// provides the offset into the bitstream where that macro is
2430 /// defined.
2431 std::vector<uint32_t> MacroOffsets;
2433 for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2434 const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2435 MacroInfo *MI = MacroInfosToEmit[I].MI;
2436 MacroID ID = MacroInfosToEmit[I].ID;
2438 if (ID < FirstMacroID) {
2439 assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2440 continue;
2443 // Record the local offset of this macro.
2444 unsigned Index = ID - FirstMacroID;
2445 if (Index >= MacroOffsets.size())
2446 MacroOffsets.resize(Index + 1);
2448 uint64_t Offset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2449 assert((Offset >> 32) == 0 && "Macro offset too large");
2450 MacroOffsets[Index] = Offset;
2452 AddIdentifierRef(Name, Record);
2453 AddSourceLocation(MI->getDefinitionLoc(), Record);
2454 AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2455 Record.push_back(MI->isUsed());
2456 Record.push_back(MI->isUsedForHeaderGuard());
2457 Record.push_back(MI->getNumTokens());
2458 unsigned Code;
2459 if (MI->isObjectLike()) {
2460 Code = PP_MACRO_OBJECT_LIKE;
2461 } else {
2462 Code = PP_MACRO_FUNCTION_LIKE;
2464 Record.push_back(MI->isC99Varargs());
2465 Record.push_back(MI->isGNUVarargs());
2466 Record.push_back(MI->hasCommaPasting());
2467 Record.push_back(MI->getNumParams());
2468 for (const IdentifierInfo *Param : MI->params())
2469 AddIdentifierRef(Param, Record);
2472 // If we have a detailed preprocessing record, record the macro definition
2473 // ID that corresponds to this macro.
2474 if (PPRec)
2475 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2477 Stream.EmitRecord(Code, Record);
2478 Record.clear();
2480 // Emit the tokens array.
2481 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2482 // Note that we know that the preprocessor does not have any annotation
2483 // tokens in it because they are created by the parser, and thus can't
2484 // be in a macro definition.
2485 const Token &Tok = MI->getReplacementToken(TokNo);
2486 AddToken(Tok, Record);
2487 Stream.EmitRecord(PP_TOKEN, Record);
2488 Record.clear();
2490 ++NumMacros;
2493 Stream.ExitBlock();
2495 // Write the offsets table for macro IDs.
2496 using namespace llvm;
2498 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2499 Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2500 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2501 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2502 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // base offset
2503 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2505 unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2507 RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
2508 FirstMacroID - NUM_PREDEF_MACRO_IDS,
2509 MacroOffsetsBase - ASTBlockStartOffset};
2510 Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
2514 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2515 Abbrev->Add(BitCodeAbbrevOp(PP_INCLUDED_FILES));
2516 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2517 unsigned IncludedFilesAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2519 SmallString<2048> Buffer;
2520 raw_svector_ostream Out(Buffer);
2521 writeIncludedFiles(Out, PP);
2522 RecordData::value_type Record[] = {PP_INCLUDED_FILES};
2523 Stream.EmitRecordWithBlob(IncludedFilesAbbrev, Record, Buffer.data(),
2524 Buffer.size());
2528 void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec,
2529 uint64_t MacroOffsetsBase) {
2530 if (PPRec.local_begin() == PPRec.local_end())
2531 return;
2533 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
2535 // Enter the preprocessor block.
2536 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
2538 // If the preprocessor has a preprocessing record, emit it.
2539 unsigned NumPreprocessingRecords = 0;
2540 using namespace llvm;
2542 // Set up the abbreviation for
2543 unsigned InclusionAbbrev = 0;
2545 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2546 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
2547 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2548 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2549 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
2550 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
2551 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2552 InclusionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2555 unsigned FirstPreprocessorEntityID
2556 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
2557 + NUM_PREDEF_PP_ENTITY_IDS;
2558 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
2559 RecordData Record;
2560 for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2561 EEnd = PPRec.local_end();
2562 E != EEnd;
2563 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
2564 Record.clear();
2566 uint64_t Offset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2567 assert((Offset >> 32) == 0 && "Preprocessed entity offset too large");
2568 PreprocessedEntityOffsets.push_back(
2569 PPEntityOffset((*E)->getSourceRange(), Offset));
2571 if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
2572 // Record this macro definition's ID.
2573 MacroDefinitions[MD] = NextPreprocessorEntityID;
2575 AddIdentifierRef(MD->getName(), Record);
2576 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2577 continue;
2580 if (auto *ME = dyn_cast<MacroExpansion>(*E)) {
2581 Record.push_back(ME->isBuiltinMacro());
2582 if (ME->isBuiltinMacro())
2583 AddIdentifierRef(ME->getName(), Record);
2584 else
2585 Record.push_back(MacroDefinitions[ME->getDefinition()]);
2586 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
2587 continue;
2590 if (auto *ID = dyn_cast<InclusionDirective>(*E)) {
2591 Record.push_back(PPD_INCLUSION_DIRECTIVE);
2592 Record.push_back(ID->getFileName().size());
2593 Record.push_back(ID->wasInQuotes());
2594 Record.push_back(static_cast<unsigned>(ID->getKind()));
2595 Record.push_back(ID->importedModule());
2596 SmallString<64> Buffer;
2597 Buffer += ID->getFileName();
2598 // Check that the FileEntry is not null because it was not resolved and
2599 // we create a PCH even with compiler errors.
2600 if (ID->getFile())
2601 Buffer += ID->getFile()->getName();
2602 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
2603 continue;
2606 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2608 Stream.ExitBlock();
2610 // Write the offsets table for the preprocessing record.
2611 if (NumPreprocessingRecords > 0) {
2612 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2614 // Write the offsets table for identifier IDs.
2615 using namespace llvm;
2617 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2618 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
2619 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
2620 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2621 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2623 RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS,
2624 FirstPreprocessorEntityID -
2625 NUM_PREDEF_PP_ENTITY_IDS};
2626 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
2627 bytes(PreprocessedEntityOffsets));
2630 // Write the skipped region table for the preprocessing record.
2631 ArrayRef<SourceRange> SkippedRanges = PPRec.getSkippedRanges();
2632 if (SkippedRanges.size() > 0) {
2633 std::vector<PPSkippedRange> SerializedSkippedRanges;
2634 SerializedSkippedRanges.reserve(SkippedRanges.size());
2635 for (auto const& Range : SkippedRanges)
2636 SerializedSkippedRanges.emplace_back(Range);
2638 using namespace llvm;
2639 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2640 Abbrev->Add(BitCodeAbbrevOp(PPD_SKIPPED_RANGES));
2641 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2642 unsigned PPESkippedRangeAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2644 Record.clear();
2645 Record.push_back(PPD_SKIPPED_RANGES);
2646 Stream.EmitRecordWithBlob(PPESkippedRangeAbbrev, Record,
2647 bytes(SerializedSkippedRanges));
2651 unsigned ASTWriter::getLocalOrImportedSubmoduleID(const Module *Mod) {
2652 if (!Mod)
2653 return 0;
2655 auto Known = SubmoduleIDs.find(Mod);
2656 if (Known != SubmoduleIDs.end())
2657 return Known->second;
2659 auto *Top = Mod->getTopLevelModule();
2660 if (Top != WritingModule &&
2661 (getLangOpts().CompilingPCH ||
2662 !Top->fullModuleNameIs(StringRef(getLangOpts().CurrentModule))))
2663 return 0;
2665 return SubmoduleIDs[Mod] = NextSubmoduleID++;
2668 unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2669 // FIXME: This can easily happen, if we have a reference to a submodule that
2670 // did not result in us loading a module file for that submodule. For
2671 // instance, a cross-top-level-module 'conflict' declaration will hit this.
2672 unsigned ID = getLocalOrImportedSubmoduleID(Mod);
2673 assert((ID || !Mod) &&
2674 "asked for module ID for non-local, non-imported module");
2675 return ID;
2678 /// Compute the number of modules within the given tree (including the
2679 /// given module).
2680 static unsigned getNumberOfModules(Module *Mod) {
2681 unsigned ChildModules = 0;
2682 for (auto Sub = Mod->submodule_begin(), SubEnd = Mod->submodule_end();
2683 Sub != SubEnd; ++Sub)
2684 ChildModules += getNumberOfModules(*Sub);
2686 return ChildModules + 1;
2689 void ASTWriter::WriteSubmodules(Module *WritingModule) {
2690 // Enter the submodule description block.
2691 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
2693 // Write the abbreviations needed for the submodules block.
2694 using namespace llvm;
2696 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2697 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
2698 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
2699 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
2700 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Kind
2701 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2702 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
2703 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2704 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
2705 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
2706 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
2707 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
2708 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
2709 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ModuleMapIsPriv...
2710 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2711 unsigned DefinitionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2713 Abbrev = std::make_shared<BitCodeAbbrev>();
2714 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
2715 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2716 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2718 Abbrev = std::make_shared<BitCodeAbbrev>();
2719 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2720 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2721 unsigned HeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2723 Abbrev = std::make_shared<BitCodeAbbrev>();
2724 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2725 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2726 unsigned TopHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2728 Abbrev = std::make_shared<BitCodeAbbrev>();
2729 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2730 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2731 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2733 Abbrev = std::make_shared<BitCodeAbbrev>();
2734 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
2735 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
2736 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
2737 unsigned RequiresAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2739 Abbrev = std::make_shared<BitCodeAbbrev>();
2740 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2741 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2742 unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2744 Abbrev = std::make_shared<BitCodeAbbrev>();
2745 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
2746 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2747 unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2749 Abbrev = std::make_shared<BitCodeAbbrev>();
2750 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
2751 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2752 unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2754 Abbrev = std::make_shared<BitCodeAbbrev>();
2755 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
2756 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2757 unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2759 Abbrev = std::make_shared<BitCodeAbbrev>();
2760 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2761 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2762 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2763 unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2765 Abbrev = std::make_shared<BitCodeAbbrev>();
2766 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2767 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2768 unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2770 Abbrev = std::make_shared<BitCodeAbbrev>();
2771 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2772 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module
2773 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message
2774 unsigned ConflictAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2776 Abbrev = std::make_shared<BitCodeAbbrev>();
2777 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXPORT_AS));
2778 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2779 unsigned ExportAsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2781 // Write the submodule metadata block.
2782 RecordData::value_type Record[] = {
2783 getNumberOfModules(WritingModule),
2784 FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS};
2785 Stream.EmitRecord(SUBMODULE_METADATA, Record);
2787 // Write all of the submodules.
2788 std::queue<Module *> Q;
2789 Q.push(WritingModule);
2790 while (!Q.empty()) {
2791 Module *Mod = Q.front();
2792 Q.pop();
2793 unsigned ID = getSubmoduleID(Mod);
2795 uint64_t ParentID = 0;
2796 if (Mod->Parent) {
2797 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
2798 ParentID = SubmoduleIDs[Mod->Parent];
2801 // Emit the definition of the block.
2803 RecordData::value_type Record[] = {SUBMODULE_DEFINITION,
2805 ParentID,
2806 (RecordData::value_type)Mod->Kind,
2807 Mod->IsFramework,
2808 Mod->IsExplicit,
2809 Mod->IsSystem,
2810 Mod->IsExternC,
2811 Mod->InferSubmodules,
2812 Mod->InferExplicitSubmodules,
2813 Mod->InferExportWildcard,
2814 Mod->ConfigMacrosExhaustive,
2815 Mod->ModuleMapIsPrivate};
2816 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2819 // Emit the requirements.
2820 for (const auto &R : Mod->Requirements) {
2821 RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.second};
2822 Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.first);
2825 // Emit the umbrella header, if there is one.
2826 if (auto UmbrellaHeader = Mod->getUmbrellaHeader()) {
2827 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
2828 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2829 UmbrellaHeader.NameAsWritten);
2830 } else if (auto UmbrellaDir = Mod->getUmbrellaDir()) {
2831 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
2832 Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
2833 UmbrellaDir.NameAsWritten);
2836 // Emit the headers.
2837 struct {
2838 unsigned RecordKind;
2839 unsigned Abbrev;
2840 Module::HeaderKind HeaderKind;
2841 } HeaderLists[] = {
2842 {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
2843 {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
2844 {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
2845 {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
2846 Module::HK_PrivateTextual},
2847 {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
2849 for (auto &HL : HeaderLists) {
2850 RecordData::value_type Record[] = {HL.RecordKind};
2851 for (auto &H : Mod->Headers[HL.HeaderKind])
2852 Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
2855 // Emit the top headers.
2857 auto TopHeaders = Mod->getTopHeaders(PP->getFileManager());
2858 RecordData::value_type Record[] = {SUBMODULE_TOPHEADER};
2859 for (auto *H : TopHeaders) {
2860 SmallString<128> HeaderName(H->getName());
2861 PreparePathForOutput(HeaderName);
2862 Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, HeaderName);
2866 // Emit the imports.
2867 if (!Mod->Imports.empty()) {
2868 RecordData Record;
2869 for (auto *I : Mod->Imports)
2870 Record.push_back(getSubmoduleID(I));
2871 Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2874 // Emit the modules affecting compilation that were not imported.
2875 if (!Mod->AffectingModules.empty()) {
2876 RecordData Record;
2877 for (auto *I : Mod->AffectingModules)
2878 Record.push_back(getSubmoduleID(I));
2879 Stream.EmitRecord(SUBMODULE_AFFECTING_MODULES, Record);
2882 // Emit the exports.
2883 if (!Mod->Exports.empty()) {
2884 RecordData Record;
2885 for (const auto &E : Mod->Exports) {
2886 // FIXME: This may fail; we don't require that all exported modules
2887 // are local or imported.
2888 Record.push_back(getSubmoduleID(E.getPointer()));
2889 Record.push_back(E.getInt());
2891 Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
2894 //FIXME: How do we emit the 'use'd modules? They may not be submodules.
2895 // Might be unnecessary as use declarations are only used to build the
2896 // module itself.
2898 // TODO: Consider serializing undeclared uses of modules.
2900 // Emit the link libraries.
2901 for (const auto &LL : Mod->LinkLibraries) {
2902 RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY,
2903 LL.IsFramework};
2904 Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library);
2907 // Emit the conflicts.
2908 for (const auto &C : Mod->Conflicts) {
2909 // FIXME: This may fail; we don't require that all conflicting modules
2910 // are local or imported.
2911 RecordData::value_type Record[] = {SUBMODULE_CONFLICT,
2912 getSubmoduleID(C.Other)};
2913 Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message);
2916 // Emit the configuration macros.
2917 for (const auto &CM : Mod->ConfigMacros) {
2918 RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO};
2919 Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM);
2922 // Emit the initializers, if any.
2923 RecordData Inits;
2924 for (Decl *D : Context->getModuleInitializers(Mod))
2925 Inits.push_back(GetDeclRef(D));
2926 if (!Inits.empty())
2927 Stream.EmitRecord(SUBMODULE_INITIALIZERS, Inits);
2929 // Emit the name of the re-exported module, if any.
2930 if (!Mod->ExportAsModule.empty()) {
2931 RecordData::value_type Record[] = {SUBMODULE_EXPORT_AS};
2932 Stream.EmitRecordWithBlob(ExportAsAbbrev, Record, Mod->ExportAsModule);
2935 // Queue up the submodules of this module.
2936 for (auto *M : Mod->submodules())
2937 Q.push(M);
2940 Stream.ExitBlock();
2942 assert((NextSubmoduleID - FirstSubmoduleID ==
2943 getNumberOfModules(WritingModule)) &&
2944 "Wrong # of submodules; found a reference to a non-local, "
2945 "non-imported submodule?");
2948 void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
2949 bool isModule) {
2950 llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
2951 DiagStateIDMap;
2952 unsigned CurrID = 0;
2953 RecordData Record;
2955 auto EncodeDiagStateFlags =
2956 [](const DiagnosticsEngine::DiagState *DS) -> unsigned {
2957 unsigned Result = (unsigned)DS->ExtBehavior;
2958 for (unsigned Val :
2959 {(unsigned)DS->IgnoreAllWarnings, (unsigned)DS->EnableAllWarnings,
2960 (unsigned)DS->WarningsAsErrors, (unsigned)DS->ErrorsAsFatal,
2961 (unsigned)DS->SuppressSystemWarnings})
2962 Result = (Result << 1) | Val;
2963 return Result;
2966 unsigned Flags = EncodeDiagStateFlags(Diag.DiagStatesByLoc.FirstDiagState);
2967 Record.push_back(Flags);
2969 auto AddDiagState = [&](const DiagnosticsEngine::DiagState *State,
2970 bool IncludeNonPragmaStates) {
2971 // Ensure that the diagnostic state wasn't modified since it was created.
2972 // We will not correctly round-trip this information otherwise.
2973 assert(Flags == EncodeDiagStateFlags(State) &&
2974 "diag state flags vary in single AST file");
2976 unsigned &DiagStateID = DiagStateIDMap[State];
2977 Record.push_back(DiagStateID);
2979 if (DiagStateID == 0) {
2980 DiagStateID = ++CurrID;
2982 // Add a placeholder for the number of mappings.
2983 auto SizeIdx = Record.size();
2984 Record.emplace_back();
2985 for (const auto &I : *State) {
2986 if (I.second.isPragma() || IncludeNonPragmaStates) {
2987 Record.push_back(I.first);
2988 Record.push_back(I.second.serialize());
2991 // Update the placeholder.
2992 Record[SizeIdx] = (Record.size() - SizeIdx) / 2;
2996 AddDiagState(Diag.DiagStatesByLoc.FirstDiagState, isModule);
2998 // Reserve a spot for the number of locations with state transitions.
2999 auto NumLocationsIdx = Record.size();
3000 Record.emplace_back();
3002 // Emit the state transitions.
3003 unsigned NumLocations = 0;
3004 for (auto &FileIDAndFile : Diag.DiagStatesByLoc.Files) {
3005 if (!FileIDAndFile.first.isValid() ||
3006 !FileIDAndFile.second.HasLocalTransitions)
3007 continue;
3008 ++NumLocations;
3010 SourceLocation Loc = Diag.SourceMgr->getComposedLoc(FileIDAndFile.first, 0);
3011 assert(!Loc.isInvalid() && "start loc for valid FileID is invalid");
3012 AddSourceLocation(Loc, Record);
3014 Record.push_back(FileIDAndFile.second.StateTransitions.size());
3015 for (auto &StatePoint : FileIDAndFile.second.StateTransitions) {
3016 Record.push_back(StatePoint.Offset);
3017 AddDiagState(StatePoint.State, false);
3021 // Backpatch the number of locations.
3022 Record[NumLocationsIdx] = NumLocations;
3024 // Emit CurDiagStateLoc. Do it last in order to match source order.
3026 // This also protects against a hypothetical corner case with simulating
3027 // -Werror settings for implicit modules in the ASTReader, where reading
3028 // CurDiagState out of context could change whether warning pragmas are
3029 // treated as errors.
3030 AddSourceLocation(Diag.DiagStatesByLoc.CurDiagStateLoc, Record);
3031 AddDiagState(Diag.DiagStatesByLoc.CurDiagState, false);
3033 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
3036 //===----------------------------------------------------------------------===//
3037 // Type Serialization
3038 //===----------------------------------------------------------------------===//
3040 /// Write the representation of a type to the AST stream.
3041 void ASTWriter::WriteType(QualType T) {
3042 TypeIdx &IdxRef = TypeIdxs[T];
3043 if (IdxRef.getIndex() == 0) // we haven't seen this type before.
3044 IdxRef = TypeIdx(NextTypeID++);
3045 TypeIdx Idx = IdxRef;
3047 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
3049 // Emit the type's representation.
3050 uint64_t Offset = ASTTypeWriter(*this).write(T) - DeclTypesBlockStartOffset;
3052 // Record the offset for this type.
3053 unsigned Index = Idx.getIndex() - FirstTypeID;
3054 if (TypeOffsets.size() == Index)
3055 TypeOffsets.emplace_back(Offset);
3056 else if (TypeOffsets.size() < Index) {
3057 TypeOffsets.resize(Index + 1);
3058 TypeOffsets[Index].setBitOffset(Offset);
3059 } else {
3060 llvm_unreachable("Types emitted in wrong order");
3064 //===----------------------------------------------------------------------===//
3065 // Declaration Serialization
3066 //===----------------------------------------------------------------------===//
3068 /// Write the block containing all of the declaration IDs
3069 /// lexically declared within the given DeclContext.
3071 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
3072 /// bitstream, or 0 if no block was written.
3073 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
3074 DeclContext *DC) {
3075 if (DC->decls_empty())
3076 return 0;
3078 uint64_t Offset = Stream.GetCurrentBitNo();
3079 SmallVector<uint32_t, 128> KindDeclPairs;
3080 for (const auto *D : DC->decls()) {
3081 KindDeclPairs.push_back(D->getKind());
3082 KindDeclPairs.push_back(GetDeclRef(D));
3085 ++NumLexicalDeclContexts;
3086 RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
3087 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
3088 bytes(KindDeclPairs));
3089 return Offset;
3092 void ASTWriter::WriteTypeDeclOffsets() {
3093 using namespace llvm;
3095 // Write the type offsets array
3096 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3097 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
3098 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
3099 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
3100 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
3101 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3103 RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(),
3104 FirstTypeID - NUM_PREDEF_TYPE_IDS};
3105 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
3108 // Write the declaration offsets array
3109 Abbrev = std::make_shared<BitCodeAbbrev>();
3110 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
3111 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
3112 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
3113 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
3114 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3116 RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(),
3117 FirstDeclID - NUM_PREDEF_DECL_IDS};
3118 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
3122 void ASTWriter::WriteFileDeclIDsMap() {
3123 using namespace llvm;
3125 SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs;
3126 SortedFileDeclIDs.reserve(FileDeclIDs.size());
3127 for (const auto &P : FileDeclIDs)
3128 SortedFileDeclIDs.push_back(std::make_pair(P.first, P.second.get()));
3129 llvm::sort(SortedFileDeclIDs, llvm::less_first());
3131 // Join the vectors of DeclIDs from all files.
3132 SmallVector<DeclID, 256> FileGroupedDeclIDs;
3133 for (auto &FileDeclEntry : SortedFileDeclIDs) {
3134 DeclIDInFileInfo &Info = *FileDeclEntry.second;
3135 Info.FirstDeclIndex = FileGroupedDeclIDs.size();
3136 llvm::stable_sort(Info.DeclIDs);
3137 for (auto &LocDeclEntry : Info.DeclIDs)
3138 FileGroupedDeclIDs.push_back(LocDeclEntry.second);
3141 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3142 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
3143 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3144 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3145 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
3146 RecordData::value_type Record[] = {FILE_SORTED_DECLS,
3147 FileGroupedDeclIDs.size()};
3148 Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
3151 void ASTWriter::WriteComments() {
3152 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
3153 auto _ = llvm::make_scope_exit([this] { Stream.ExitBlock(); });
3154 if (!PP->getPreprocessorOpts().WriteCommentListToPCH)
3155 return;
3156 RecordData Record;
3157 for (const auto &FO : Context->Comments.OrderedComments) {
3158 for (const auto &OC : FO.second) {
3159 const RawComment *I = OC.second;
3160 Record.clear();
3161 AddSourceRange(I->getSourceRange(), Record);
3162 Record.push_back(I->getKind());
3163 Record.push_back(I->isTrailingComment());
3164 Record.push_back(I->isAlmostTrailingComment());
3165 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
3170 //===----------------------------------------------------------------------===//
3171 // Global Method Pool and Selector Serialization
3172 //===----------------------------------------------------------------------===//
3174 namespace {
3176 // Trait used for the on-disk hash table used in the method pool.
3177 class ASTMethodPoolTrait {
3178 ASTWriter &Writer;
3180 public:
3181 using key_type = Selector;
3182 using key_type_ref = key_type;
3184 struct data_type {
3185 SelectorID ID;
3186 ObjCMethodList Instance, Factory;
3188 using data_type_ref = const data_type &;
3190 using hash_value_type = unsigned;
3191 using offset_type = unsigned;
3193 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) {}
3195 static hash_value_type ComputeHash(Selector Sel) {
3196 return serialization::ComputeHash(Sel);
3199 std::pair<unsigned, unsigned>
3200 EmitKeyDataLength(raw_ostream& Out, Selector Sel,
3201 data_type_ref Methods) {
3202 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
3203 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
3204 for (const ObjCMethodList *Method = &Methods.Instance; Method;
3205 Method = Method->getNext())
3206 if (ShouldWriteMethodListNode(Method))
3207 DataLen += 4;
3208 for (const ObjCMethodList *Method = &Methods.Factory; Method;
3209 Method = Method->getNext())
3210 if (ShouldWriteMethodListNode(Method))
3211 DataLen += 4;
3212 return emitULEBKeyDataLength(KeyLen, DataLen, Out);
3215 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
3216 using namespace llvm::support;
3218 endian::Writer LE(Out, little);
3219 uint64_t Start = Out.tell();
3220 assert((Start >> 32) == 0 && "Selector key offset too large");
3221 Writer.SetSelectorOffset(Sel, Start);
3222 unsigned N = Sel.getNumArgs();
3223 LE.write<uint16_t>(N);
3224 if (N == 0)
3225 N = 1;
3226 for (unsigned I = 0; I != N; ++I)
3227 LE.write<uint32_t>(
3228 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
3231 void EmitData(raw_ostream& Out, key_type_ref,
3232 data_type_ref Methods, unsigned DataLen) {
3233 using namespace llvm::support;
3235 endian::Writer LE(Out, little);
3236 uint64_t Start = Out.tell(); (void)Start;
3237 LE.write<uint32_t>(Methods.ID);
3238 unsigned NumInstanceMethods = 0;
3239 for (const ObjCMethodList *Method = &Methods.Instance; Method;
3240 Method = Method->getNext())
3241 if (ShouldWriteMethodListNode(Method))
3242 ++NumInstanceMethods;
3244 unsigned NumFactoryMethods = 0;
3245 for (const ObjCMethodList *Method = &Methods.Factory; Method;
3246 Method = Method->getNext())
3247 if (ShouldWriteMethodListNode(Method))
3248 ++NumFactoryMethods;
3250 unsigned InstanceBits = Methods.Instance.getBits();
3251 assert(InstanceBits < 4);
3252 unsigned InstanceHasMoreThanOneDeclBit =
3253 Methods.Instance.hasMoreThanOneDecl();
3254 unsigned FullInstanceBits = (NumInstanceMethods << 3) |
3255 (InstanceHasMoreThanOneDeclBit << 2) |
3256 InstanceBits;
3257 unsigned FactoryBits = Methods.Factory.getBits();
3258 assert(FactoryBits < 4);
3259 unsigned FactoryHasMoreThanOneDeclBit =
3260 Methods.Factory.hasMoreThanOneDecl();
3261 unsigned FullFactoryBits = (NumFactoryMethods << 3) |
3262 (FactoryHasMoreThanOneDeclBit << 2) |
3263 FactoryBits;
3264 LE.write<uint16_t>(FullInstanceBits);
3265 LE.write<uint16_t>(FullFactoryBits);
3266 for (const ObjCMethodList *Method = &Methods.Instance; Method;
3267 Method = Method->getNext())
3268 if (ShouldWriteMethodListNode(Method))
3269 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
3270 for (const ObjCMethodList *Method = &Methods.Factory; Method;
3271 Method = Method->getNext())
3272 if (ShouldWriteMethodListNode(Method))
3273 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
3275 assert(Out.tell() - Start == DataLen && "Data length is wrong");
3278 private:
3279 static bool ShouldWriteMethodListNode(const ObjCMethodList *Node) {
3280 return (Node->getMethod() && !Node->getMethod()->isFromASTFile());
3284 } // namespace
3286 /// Write ObjC data: selectors and the method pool.
3288 /// The method pool contains both instance and factory methods, stored
3289 /// in an on-disk hash table indexed by the selector. The hash table also
3290 /// contains an empty entry for every other selector known to Sema.
3291 void ASTWriter::WriteSelectors(Sema &SemaRef) {
3292 using namespace llvm;
3294 // Do we have to do anything at all?
3295 if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
3296 return;
3297 unsigned NumTableEntries = 0;
3298 // Create and write out the blob that contains selectors and the method pool.
3300 llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
3301 ASTMethodPoolTrait Trait(*this);
3303 // Create the on-disk hash table representation. We walk through every
3304 // selector we've seen and look it up in the method pool.
3305 SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
3306 for (auto &SelectorAndID : SelectorIDs) {
3307 Selector S = SelectorAndID.first;
3308 SelectorID ID = SelectorAndID.second;
3309 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
3310 ASTMethodPoolTrait::data_type Data = {
3312 ObjCMethodList(),
3313 ObjCMethodList()
3315 if (F != SemaRef.MethodPool.end()) {
3316 Data.Instance = F->second.first;
3317 Data.Factory = F->second.second;
3319 // Only write this selector if it's not in an existing AST or something
3320 // changed.
3321 if (Chain && ID < FirstSelectorID) {
3322 // Selector already exists. Did it change?
3323 bool changed = false;
3324 for (ObjCMethodList *M = &Data.Instance; M && M->getMethod();
3325 M = M->getNext()) {
3326 if (!M->getMethod()->isFromASTFile()) {
3327 changed = true;
3328 Data.Instance = *M;
3329 break;
3332 for (ObjCMethodList *M = &Data.Factory; M && M->getMethod();
3333 M = M->getNext()) {
3334 if (!M->getMethod()->isFromASTFile()) {
3335 changed = true;
3336 Data.Factory = *M;
3337 break;
3340 if (!changed)
3341 continue;
3342 } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
3343 // A new method pool entry.
3344 ++NumTableEntries;
3346 Generator.insert(S, Data, Trait);
3349 // Create the on-disk hash table in a buffer.
3350 SmallString<4096> MethodPool;
3351 uint32_t BucketOffset;
3353 using namespace llvm::support;
3355 ASTMethodPoolTrait Trait(*this);
3356 llvm::raw_svector_ostream Out(MethodPool);
3357 // Make sure that no bucket is at offset 0
3358 endian::write<uint32_t>(Out, 0, little);
3359 BucketOffset = Generator.Emit(Out, Trait);
3362 // Create a blob abbreviation
3363 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3364 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
3365 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3366 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3367 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3368 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3370 // Write the method pool
3372 RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
3373 NumTableEntries};
3374 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
3377 // Create a blob abbreviation for the selector table offsets.
3378 Abbrev = std::make_shared<BitCodeAbbrev>();
3379 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
3380 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
3381 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3382 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3383 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3385 // Write the selector offsets table.
3387 RecordData::value_type Record[] = {
3388 SELECTOR_OFFSETS, SelectorOffsets.size(),
3389 FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
3390 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3391 bytes(SelectorOffsets));
3396 /// Write the selectors referenced in @selector expression into AST file.
3397 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
3398 using namespace llvm;
3400 if (SemaRef.ReferencedSelectors.empty())
3401 return;
3403 RecordData Record;
3404 ASTRecordWriter Writer(*this, Record);
3406 // Note: this writes out all references even for a dependent AST. But it is
3407 // very tricky to fix, and given that @selector shouldn't really appear in
3408 // headers, probably not worth it. It's not a correctness issue.
3409 for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
3410 Selector Sel = SelectorAndLocation.first;
3411 SourceLocation Loc = SelectorAndLocation.second;
3412 Writer.AddSelectorRef(Sel);
3413 Writer.AddSourceLocation(Loc);
3415 Writer.Emit(REFERENCED_SELECTOR_POOL);
3418 //===----------------------------------------------------------------------===//
3419 // Identifier Table Serialization
3420 //===----------------------------------------------------------------------===//
3422 /// Determine the declaration that should be put into the name lookup table to
3423 /// represent the given declaration in this module. This is usually D itself,
3424 /// but if D was imported and merged into a local declaration, we want the most
3425 /// recent local declaration instead. The chosen declaration will be the most
3426 /// recent declaration in any module that imports this one.
3427 static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
3428 NamedDecl *D) {
3429 if (!LangOpts.Modules || !D->isFromASTFile())
3430 return D;
3432 if (Decl *Redecl = D->getPreviousDecl()) {
3433 // For Redeclarable decls, a prior declaration might be local.
3434 for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
3435 // If we find a local decl, we're done.
3436 if (!Redecl->isFromASTFile()) {
3437 // Exception: in very rare cases (for injected-class-names), not all
3438 // redeclarations are in the same semantic context. Skip ones in a
3439 // different context. They don't go in this lookup table at all.
3440 if (!Redecl->getDeclContext()->getRedeclContext()->Equals(
3441 D->getDeclContext()->getRedeclContext()))
3442 continue;
3443 return cast<NamedDecl>(Redecl);
3446 // If we find a decl from a (chained-)PCH stop since we won't find a
3447 // local one.
3448 if (Redecl->getOwningModuleID() == 0)
3449 break;
3451 } else if (Decl *First = D->getCanonicalDecl()) {
3452 // For Mergeable decls, the first decl might be local.
3453 if (!First->isFromASTFile())
3454 return cast<NamedDecl>(First);
3457 // All declarations are imported. Our most recent declaration will also be
3458 // the most recent one in anyone who imports us.
3459 return D;
3462 namespace {
3464 class ASTIdentifierTableTrait {
3465 ASTWriter &Writer;
3466 Preprocessor &PP;
3467 IdentifierResolver &IdResolver;
3468 bool IsModule;
3469 bool NeedDecls;
3470 ASTWriter::RecordData *InterestingIdentifierOffsets;
3472 /// Determines whether this is an "interesting" identifier that needs a
3473 /// full IdentifierInfo structure written into the hash table. Notably, this
3474 /// doesn't check whether the name has macros defined; use PublicMacroIterator
3475 /// to check that.
3476 bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
3477 if (MacroOffset || II->isPoisoned() ||
3478 (!IsModule && II->getObjCOrBuiltinID()) ||
3479 II->hasRevertedTokenIDToIdentifier() ||
3480 (NeedDecls && II->getFETokenInfo()))
3481 return true;
3483 return false;
3486 public:
3487 using key_type = IdentifierInfo *;
3488 using key_type_ref = key_type;
3490 using data_type = IdentID;
3491 using data_type_ref = data_type;
3493 using hash_value_type = unsigned;
3494 using offset_type = unsigned;
3496 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
3497 IdentifierResolver &IdResolver, bool IsModule,
3498 ASTWriter::RecordData *InterestingIdentifierOffsets)
3499 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
3500 NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
3501 InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
3503 bool needDecls() const { return NeedDecls; }
3505 static hash_value_type ComputeHash(const IdentifierInfo* II) {
3506 return llvm::djbHash(II->getName());
3509 bool isInterestingIdentifier(const IdentifierInfo *II) {
3510 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3511 return isInterestingIdentifier(II, MacroOffset);
3514 bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) {
3515 return isInterestingIdentifier(II, 0);
3518 std::pair<unsigned, unsigned>
3519 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
3520 // Record the location of the identifier data. This is used when generating
3521 // the mapping from persistent IDs to strings.
3522 Writer.SetIdentifierOffset(II, Out.tell());
3524 // Emit the offset of the key/data length information to the interesting
3525 // identifiers table if necessary.
3526 if (InterestingIdentifierOffsets && isInterestingIdentifier(II))
3527 InterestingIdentifierOffsets->push_back(Out.tell());
3529 unsigned KeyLen = II->getLength() + 1;
3530 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
3531 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3532 if (isInterestingIdentifier(II, MacroOffset)) {
3533 DataLen += 2; // 2 bytes for builtin ID
3534 DataLen += 2; // 2 bytes for flags
3535 if (MacroOffset)
3536 DataLen += 4; // MacroDirectives offset.
3538 if (NeedDecls) {
3539 for (IdentifierResolver::iterator D = IdResolver.begin(II),
3540 DEnd = IdResolver.end();
3541 D != DEnd; ++D)
3542 DataLen += 4;
3545 return emitULEBKeyDataLength(KeyLen, DataLen, Out);
3548 void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
3549 unsigned KeyLen) {
3550 Out.write(II->getNameStart(), KeyLen);
3553 void EmitData(raw_ostream& Out, IdentifierInfo* II,
3554 IdentID ID, unsigned) {
3555 using namespace llvm::support;
3557 endian::Writer LE(Out, little);
3559 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3560 if (!isInterestingIdentifier(II, MacroOffset)) {
3561 LE.write<uint32_t>(ID << 1);
3562 return;
3565 LE.write<uint32_t>((ID << 1) | 0x01);
3566 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3567 assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
3568 LE.write<uint16_t>(Bits);
3569 Bits = 0;
3570 bool HadMacroDefinition = MacroOffset != 0;
3571 Bits = (Bits << 1) | unsigned(HadMacroDefinition);
3572 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3573 Bits = (Bits << 1) | unsigned(II->isPoisoned());
3574 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
3575 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
3576 LE.write<uint16_t>(Bits);
3578 if (HadMacroDefinition)
3579 LE.write<uint32_t>(MacroOffset);
3581 if (NeedDecls) {
3582 // Emit the declaration IDs in reverse order, because the
3583 // IdentifierResolver provides the declarations as they would be
3584 // visible (e.g., the function "stat" would come before the struct
3585 // "stat"), but the ASTReader adds declarations to the end of the list
3586 // (so we need to see the struct "stat" before the function "stat").
3587 // Only emit declarations that aren't from a chained PCH, though.
3588 SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II),
3589 IdResolver.end());
3590 for (NamedDecl *D : llvm::reverse(Decls))
3591 LE.write<uint32_t>(
3592 Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), D)));
3597 } // namespace
3599 /// Write the identifier table into the AST file.
3601 /// The identifier table consists of a blob containing string data
3602 /// (the actual identifiers themselves) and a separate "offsets" index
3603 /// that maps identifier IDs to locations within the blob.
3604 void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
3605 IdentifierResolver &IdResolver,
3606 bool IsModule) {
3607 using namespace llvm;
3609 RecordData InterestingIdents;
3611 // Create and write out the blob that contains the identifier
3612 // strings.
3614 llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
3615 ASTIdentifierTableTrait Trait(
3616 *this, PP, IdResolver, IsModule,
3617 (getLangOpts().CPlusPlus && IsModule) ? &InterestingIdents : nullptr);
3619 // Look for any identifiers that were named while processing the
3620 // headers, but are otherwise not needed. We add these to the hash
3621 // table to enable checking of the predefines buffer in the case
3622 // where the user adds new macro definitions when building the AST
3623 // file.
3624 SmallVector<const IdentifierInfo *, 128> IIs;
3625 for (const auto &ID : PP.getIdentifierTable())
3626 IIs.push_back(ID.second);
3627 // Sort the identifiers lexicographically before getting them references so
3628 // that their order is stable.
3629 llvm::sort(IIs, llvm::deref<std::less<>>());
3630 for (const IdentifierInfo *II : IIs)
3631 if (Trait.isInterestingNonMacroIdentifier(II))
3632 getIdentifierRef(II);
3634 // Create the on-disk hash table representation. We only store offsets
3635 // for identifiers that appear here for the first time.
3636 IdentifierOffsets.resize(NextIdentID - FirstIdentID);
3637 for (auto IdentIDPair : IdentifierIDs) {
3638 auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
3639 IdentID ID = IdentIDPair.second;
3640 assert(II && "NULL identifier in identifier table");
3641 // Write out identifiers if either the ID is local or the identifier has
3642 // changed since it was loaded.
3643 if (ID >= FirstIdentID || !Chain || !II->isFromAST()
3644 || II->hasChangedSinceDeserialization() ||
3645 (Trait.needDecls() &&
3646 II->hasFETokenInfoChangedSinceDeserialization()))
3647 Generator.insert(II, ID, Trait);
3650 // Create the on-disk hash table in a buffer.
3651 SmallString<4096> IdentifierTable;
3652 uint32_t BucketOffset;
3654 using namespace llvm::support;
3656 llvm::raw_svector_ostream Out(IdentifierTable);
3657 // Make sure that no bucket is at offset 0
3658 endian::write<uint32_t>(Out, 0, little);
3659 BucketOffset = Generator.Emit(Out, Trait);
3662 // Create a blob abbreviation
3663 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3664 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
3665 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3666 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3667 unsigned IDTableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3669 // Write the identifier table
3670 RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
3671 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
3674 // Write the offsets table for identifier IDs.
3675 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3676 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
3677 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
3678 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3679 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3680 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3682 #ifndef NDEBUG
3683 for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3684 assert(IdentifierOffsets[I] && "Missing identifier offset?");
3685 #endif
3687 RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
3688 IdentifierOffsets.size(),
3689 FirstIdentID - NUM_PREDEF_IDENT_IDS};
3690 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
3691 bytes(IdentifierOffsets));
3693 // In C++, write the list of interesting identifiers (those that are
3694 // defined as macros, poisoned, or similar unusual things).
3695 if (!InterestingIdents.empty())
3696 Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
3699 //===----------------------------------------------------------------------===//
3700 // DeclContext's Name Lookup Table Serialization
3701 //===----------------------------------------------------------------------===//
3703 namespace {
3705 // Trait used for the on-disk hash table used in the method pool.
3706 class ASTDeclContextNameLookupTrait {
3707 ASTWriter &Writer;
3708 llvm::SmallVector<DeclID, 64> DeclIDs;
3710 public:
3711 using key_type = DeclarationNameKey;
3712 using key_type_ref = key_type;
3714 /// A start and end index into DeclIDs, representing a sequence of decls.
3715 using data_type = std::pair<unsigned, unsigned>;
3716 using data_type_ref = const data_type &;
3718 using hash_value_type = unsigned;
3719 using offset_type = unsigned;
3721 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) {}
3723 template<typename Coll>
3724 data_type getData(const Coll &Decls) {
3725 unsigned Start = DeclIDs.size();
3726 for (NamedDecl *D : Decls) {
3727 DeclIDs.push_back(
3728 Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
3730 return std::make_pair(Start, DeclIDs.size());
3733 data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
3734 unsigned Start = DeclIDs.size();
3735 llvm::append_range(DeclIDs, FromReader);
3736 return std::make_pair(Start, DeclIDs.size());
3739 static bool EqualKey(key_type_ref a, key_type_ref b) {
3740 return a == b;
3743 hash_value_type ComputeHash(DeclarationNameKey Name) {
3744 return Name.getHash();
3747 void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
3748 assert(Writer.hasChain() &&
3749 "have reference to loaded module file but no chain?");
3751 using namespace llvm::support;
3753 endian::write<uint32_t>(Out, Writer.getChain()->getModuleFileID(F), little);
3756 std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
3757 DeclarationNameKey Name,
3758 data_type_ref Lookup) {
3759 unsigned KeyLen = 1;
3760 switch (Name.getKind()) {
3761 case DeclarationName::Identifier:
3762 case DeclarationName::ObjCZeroArgSelector:
3763 case DeclarationName::ObjCOneArgSelector:
3764 case DeclarationName::ObjCMultiArgSelector:
3765 case DeclarationName::CXXLiteralOperatorName:
3766 case DeclarationName::CXXDeductionGuideName:
3767 KeyLen += 4;
3768 break;
3769 case DeclarationName::CXXOperatorName:
3770 KeyLen += 1;
3771 break;
3772 case DeclarationName::CXXConstructorName:
3773 case DeclarationName::CXXDestructorName:
3774 case DeclarationName::CXXConversionFunctionName:
3775 case DeclarationName::CXXUsingDirective:
3776 break;
3779 // 4 bytes for each DeclID.
3780 unsigned DataLen = 4 * (Lookup.second - Lookup.first);
3782 return emitULEBKeyDataLength(KeyLen, DataLen, Out);
3785 void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
3786 using namespace llvm::support;
3788 endian::Writer LE(Out, little);
3789 LE.write<uint8_t>(Name.getKind());
3790 switch (Name.getKind()) {
3791 case DeclarationName::Identifier:
3792 case DeclarationName::CXXLiteralOperatorName:
3793 case DeclarationName::CXXDeductionGuideName:
3794 LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier()));
3795 return;
3796 case DeclarationName::ObjCZeroArgSelector:
3797 case DeclarationName::ObjCOneArgSelector:
3798 case DeclarationName::ObjCMultiArgSelector:
3799 LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
3800 return;
3801 case DeclarationName::CXXOperatorName:
3802 assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&
3803 "Invalid operator?");
3804 LE.write<uint8_t>(Name.getOperatorKind());
3805 return;
3806 case DeclarationName::CXXConstructorName:
3807 case DeclarationName::CXXDestructorName:
3808 case DeclarationName::CXXConversionFunctionName:
3809 case DeclarationName::CXXUsingDirective:
3810 return;
3813 llvm_unreachable("Invalid name kind?");
3816 void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
3817 unsigned DataLen) {
3818 using namespace llvm::support;
3820 endian::Writer LE(Out, little);
3821 uint64_t Start = Out.tell(); (void)Start;
3822 for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I)
3823 LE.write<uint32_t>(DeclIDs[I]);
3824 assert(Out.tell() - Start == DataLen && "Data length is wrong");
3828 } // namespace
3830 bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
3831 DeclContext *DC) {
3832 return Result.hasExternalDecls() &&
3833 DC->hasNeedToReconcileExternalVisibleStorage();
3836 bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
3837 DeclContext *DC) {
3838 for (auto *D : Result.getLookupResult())
3839 if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
3840 return false;
3842 return true;
3845 void
3846 ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
3847 llvm::SmallVectorImpl<char> &LookupTable) {
3848 assert(!ConstDC->hasLazyLocalLexicalLookups() &&
3849 !ConstDC->hasLazyExternalLexicalLookups() &&
3850 "must call buildLookups first");
3852 // FIXME: We need to build the lookups table, which is logically const.
3853 auto *DC = const_cast<DeclContext*>(ConstDC);
3854 assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
3856 // Create the on-disk hash table representation.
3857 MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait,
3858 ASTDeclContextNameLookupTrait> Generator;
3859 ASTDeclContextNameLookupTrait Trait(*this);
3861 // The first step is to collect the declaration names which we need to
3862 // serialize into the name lookup table, and to collect them in a stable
3863 // order.
3864 SmallVector<DeclarationName, 16> Names;
3866 // We also build up small sets of the constructor and conversion function
3867 // names which are visible.
3868 llvm::SmallPtrSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
3870 for (auto &Lookup : *DC->buildLookup()) {
3871 auto &Name = Lookup.first;
3872 auto &Result = Lookup.second;
3874 // If there are no local declarations in our lookup result, we
3875 // don't need to write an entry for the name at all. If we can't
3876 // write out a lookup set without performing more deserialization,
3877 // just skip this entry.
3878 if (isLookupResultExternal(Result, DC) &&
3879 isLookupResultEntirelyExternal(Result, DC))
3880 continue;
3882 // We also skip empty results. If any of the results could be external and
3883 // the currently available results are empty, then all of the results are
3884 // external and we skip it above. So the only way we get here with an empty
3885 // results is when no results could have been external *and* we have
3886 // external results.
3888 // FIXME: While we might want to start emitting on-disk entries for negative
3889 // lookups into a decl context as an optimization, today we *have* to skip
3890 // them because there are names with empty lookup results in decl contexts
3891 // which we can't emit in any stable ordering: we lookup constructors and
3892 // conversion functions in the enclosing namespace scope creating empty
3893 // results for them. This in almost certainly a bug in Clang's name lookup,
3894 // but that is likely to be hard or impossible to fix and so we tolerate it
3895 // here by omitting lookups with empty results.
3896 if (Lookup.second.getLookupResult().empty())
3897 continue;
3899 switch (Lookup.first.getNameKind()) {
3900 default:
3901 Names.push_back(Lookup.first);
3902 break;
3904 case DeclarationName::CXXConstructorName:
3905 assert(isa<CXXRecordDecl>(DC) &&
3906 "Cannot have a constructor name outside of a class!");
3907 ConstructorNameSet.insert(Name);
3908 break;
3910 case DeclarationName::CXXConversionFunctionName:
3911 assert(isa<CXXRecordDecl>(DC) &&
3912 "Cannot have a conversion function name outside of a class!");
3913 ConversionNameSet.insert(Name);
3914 break;
3918 // Sort the names into a stable order.
3919 llvm::sort(Names);
3921 if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
3922 // We need to establish an ordering of constructor and conversion function
3923 // names, and they don't have an intrinsic ordering.
3925 // First we try the easy case by forming the current context's constructor
3926 // name and adding that name first. This is a very useful optimization to
3927 // avoid walking the lexical declarations in many cases, and it also
3928 // handles the only case where a constructor name can come from some other
3929 // lexical context -- when that name is an implicit constructor merged from
3930 // another declaration in the redecl chain. Any non-implicit constructor or
3931 // conversion function which doesn't occur in all the lexical contexts
3932 // would be an ODR violation.
3933 auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
3934 Context->getCanonicalType(Context->getRecordType(D)));
3935 if (ConstructorNameSet.erase(ImplicitCtorName))
3936 Names.push_back(ImplicitCtorName);
3938 // If we still have constructors or conversion functions, we walk all the
3939 // names in the decl and add the constructors and conversion functions
3940 // which are visible in the order they lexically occur within the context.
3941 if (!ConstructorNameSet.empty() || !ConversionNameSet.empty())
3942 for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
3943 if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
3944 auto Name = ChildND->getDeclName();
3945 switch (Name.getNameKind()) {
3946 default:
3947 continue;
3949 case DeclarationName::CXXConstructorName:
3950 if (ConstructorNameSet.erase(Name))
3951 Names.push_back(Name);
3952 break;
3954 case DeclarationName::CXXConversionFunctionName:
3955 if (ConversionNameSet.erase(Name))
3956 Names.push_back(Name);
3957 break;
3960 if (ConstructorNameSet.empty() && ConversionNameSet.empty())
3961 break;
3964 assert(ConstructorNameSet.empty() && "Failed to find all of the visible "
3965 "constructors by walking all the "
3966 "lexical members of the context.");
3967 assert(ConversionNameSet.empty() && "Failed to find all of the visible "
3968 "conversion functions by walking all "
3969 "the lexical members of the context.");
3972 // Next we need to do a lookup with each name into this decl context to fully
3973 // populate any results from external sources. We don't actually use the
3974 // results of these lookups because we only want to use the results after all
3975 // results have been loaded and the pointers into them will be stable.
3976 for (auto &Name : Names)
3977 DC->lookup(Name);
3979 // Now we need to insert the results for each name into the hash table. For
3980 // constructor names and conversion function names, we actually need to merge
3981 // all of the results for them into one list of results each and insert
3982 // those.
3983 SmallVector<NamedDecl *, 8> ConstructorDecls;
3984 SmallVector<NamedDecl *, 8> ConversionDecls;
3986 // Now loop over the names, either inserting them or appending for the two
3987 // special cases.
3988 for (auto &Name : Names) {
3989 DeclContext::lookup_result Result = DC->noload_lookup(Name);
3991 switch (Name.getNameKind()) {
3992 default:
3993 Generator.insert(Name, Trait.getData(Result), Trait);
3994 break;
3996 case DeclarationName::CXXConstructorName:
3997 ConstructorDecls.append(Result.begin(), Result.end());
3998 break;
4000 case DeclarationName::CXXConversionFunctionName:
4001 ConversionDecls.append(Result.begin(), Result.end());
4002 break;
4006 // Handle our two special cases if we ended up having any. We arbitrarily use
4007 // the first declaration's name here because the name itself isn't part of
4008 // the key, only the kind of name is used.
4009 if (!ConstructorDecls.empty())
4010 Generator.insert(ConstructorDecls.front()->getDeclName(),
4011 Trait.getData(ConstructorDecls), Trait);
4012 if (!ConversionDecls.empty())
4013 Generator.insert(ConversionDecls.front()->getDeclName(),
4014 Trait.getData(ConversionDecls), Trait);
4016 // Create the on-disk hash table. Also emit the existing imported and
4017 // merged table if there is one.
4018 auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr;
4019 Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr);
4022 /// Write the block containing all of the declaration IDs
4023 /// visible from the given DeclContext.
4025 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
4026 /// bitstream, or 0 if no block was written.
4027 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
4028 DeclContext *DC) {
4029 // If we imported a key declaration of this namespace, write the visible
4030 // lookup results as an update record for it rather than including them
4031 // on this declaration. We will only look at key declarations on reload.
4032 if (isa<NamespaceDecl>(DC) && Chain &&
4033 Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) {
4034 // Only do this once, for the first local declaration of the namespace.
4035 for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
4036 Prev = Prev->getPreviousDecl())
4037 if (!Prev->isFromASTFile())
4038 return 0;
4040 // Note that we need to emit an update record for the primary context.
4041 UpdatedDeclContexts.insert(DC->getPrimaryContext());
4043 // Make sure all visible decls are written. They will be recorded later. We
4044 // do this using a side data structure so we can sort the names into
4045 // a deterministic order.
4046 StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup();
4047 SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16>
4048 LookupResults;
4049 if (Map) {
4050 LookupResults.reserve(Map->size());
4051 for (auto &Entry : *Map)
4052 LookupResults.push_back(
4053 std::make_pair(Entry.first, Entry.second.getLookupResult()));
4056 llvm::sort(LookupResults, llvm::less_first());
4057 for (auto &NameAndResult : LookupResults) {
4058 DeclarationName Name = NameAndResult.first;
4059 DeclContext::lookup_result Result = NameAndResult.second;
4060 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
4061 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
4062 // We have to work around a name lookup bug here where negative lookup
4063 // results for these names get cached in namespace lookup tables (these
4064 // names should never be looked up in a namespace).
4065 assert(Result.empty() && "Cannot have a constructor or conversion "
4066 "function name in a namespace!");
4067 continue;
4070 for (NamedDecl *ND : Result)
4071 if (!ND->isFromASTFile())
4072 GetDeclRef(ND);
4075 return 0;
4078 if (DC->getPrimaryContext() != DC)
4079 return 0;
4081 // Skip contexts which don't support name lookup.
4082 if (!DC->isLookupContext())
4083 return 0;
4085 // If not in C++, we perform name lookup for the translation unit via the
4086 // IdentifierInfo chains, don't bother to build a visible-declarations table.
4087 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
4088 return 0;
4090 // Serialize the contents of the mapping used for lookup. Note that,
4091 // although we have two very different code paths, the serialized
4092 // representation is the same for both cases: a declaration name,
4093 // followed by a size, followed by references to the visible
4094 // declarations that have that name.
4095 uint64_t Offset = Stream.GetCurrentBitNo();
4096 StoredDeclsMap *Map = DC->buildLookup();
4097 if (!Map || Map->empty())
4098 return 0;
4100 // Create the on-disk hash table in a buffer.
4101 SmallString<4096> LookupTable;
4102 GenerateNameLookupTable(DC, LookupTable);
4104 // Write the lookup table
4105 RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
4106 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
4107 LookupTable);
4108 ++NumVisibleDeclContexts;
4109 return Offset;
4112 /// Write an UPDATE_VISIBLE block for the given context.
4114 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
4115 /// DeclContext in a dependent AST file. As such, they only exist for the TU
4116 /// (in C++), for namespaces, and for classes with forward-declared unscoped
4117 /// enumeration members (in C++11).
4118 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
4119 StoredDeclsMap *Map = DC->getLookupPtr();
4120 if (!Map || Map->empty())
4121 return;
4123 // Create the on-disk hash table in a buffer.
4124 SmallString<4096> LookupTable;
4125 GenerateNameLookupTable(DC, LookupTable);
4127 // If we're updating a namespace, select a key declaration as the key for the
4128 // update record; those are the only ones that will be checked on reload.
4129 if (isa<NamespaceDecl>(DC))
4130 DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
4132 // Write the lookup table
4133 RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))};
4134 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
4137 /// Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
4138 void ASTWriter::WriteFPPragmaOptions(const FPOptionsOverride &Opts) {
4139 RecordData::value_type Record[] = {Opts.getAsOpaqueInt()};
4140 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
4143 /// Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
4144 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
4145 if (!SemaRef.Context.getLangOpts().OpenCL)
4146 return;
4148 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
4149 RecordData Record;
4150 for (const auto &I:Opts.OptMap) {
4151 AddString(I.getKey(), Record);
4152 auto V = I.getValue();
4153 Record.push_back(V.Supported ? 1 : 0);
4154 Record.push_back(V.Enabled ? 1 : 0);
4155 Record.push_back(V.WithPragma ? 1 : 0);
4156 Record.push_back(V.Avail);
4157 Record.push_back(V.Core);
4158 Record.push_back(V.Opt);
4160 Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
4162 void ASTWriter::WriteCUDAPragmas(Sema &SemaRef) {
4163 if (SemaRef.ForceCUDAHostDeviceDepth > 0) {
4164 RecordData::value_type Record[] = {SemaRef.ForceCUDAHostDeviceDepth};
4165 Stream.EmitRecord(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH, Record);
4169 void ASTWriter::WriteObjCCategories() {
4170 SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
4171 RecordData Categories;
4173 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
4174 unsigned Size = 0;
4175 unsigned StartIndex = Categories.size();
4177 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
4179 // Allocate space for the size.
4180 Categories.push_back(0);
4182 // Add the categories.
4183 for (ObjCInterfaceDecl::known_categories_iterator
4184 Cat = Class->known_categories_begin(),
4185 CatEnd = Class->known_categories_end();
4186 Cat != CatEnd; ++Cat, ++Size) {
4187 assert(getDeclID(*Cat) != 0 && "Bogus category");
4188 AddDeclRef(*Cat, Categories);
4191 // Update the size.
4192 Categories[StartIndex] = Size;
4194 // Record this interface -> category map.
4195 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
4196 CategoriesMap.push_back(CatInfo);
4199 // Sort the categories map by the definition ID, since the reader will be
4200 // performing binary searches on this information.
4201 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
4203 // Emit the categories map.
4204 using namespace llvm;
4206 auto Abbrev = std::make_shared<BitCodeAbbrev>();
4207 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
4208 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
4209 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4210 unsigned AbbrevID = Stream.EmitAbbrev(std::move(Abbrev));
4212 RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
4213 Stream.EmitRecordWithBlob(AbbrevID, Record,
4214 reinterpret_cast<char *>(CategoriesMap.data()),
4215 CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
4217 // Emit the category lists.
4218 Stream.EmitRecord(OBJC_CATEGORIES, Categories);
4221 void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
4222 Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
4224 if (LPTMap.empty())
4225 return;
4227 RecordData Record;
4228 for (auto &LPTMapEntry : LPTMap) {
4229 const FunctionDecl *FD = LPTMapEntry.first;
4230 LateParsedTemplate &LPT = *LPTMapEntry.second;
4231 AddDeclRef(FD, Record);
4232 AddDeclRef(LPT.D, Record);
4233 Record.push_back(LPT.Toks.size());
4235 for (const auto &Tok : LPT.Toks) {
4236 AddToken(Tok, Record);
4239 Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
4242 /// Write the state of 'pragma clang optimize' at the end of the module.
4243 void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
4244 RecordData Record;
4245 SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
4246 AddSourceLocation(PragmaLoc, Record);
4247 Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
4250 /// Write the state of 'pragma ms_struct' at the end of the module.
4251 void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
4252 RecordData Record;
4253 Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF);
4254 Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
4257 /// Write the state of 'pragma pointers_to_members' at the end of the
4258 //module.
4259 void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
4260 RecordData Record;
4261 Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod);
4262 AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record);
4263 Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record);
4266 /// Write the state of 'pragma align/pack' at the end of the module.
4267 void ASTWriter::WritePackPragmaOptions(Sema &SemaRef) {
4268 // Don't serialize pragma align/pack state for modules, since it should only
4269 // take effect on a per-submodule basis.
4270 if (WritingModule)
4271 return;
4273 RecordData Record;
4274 AddAlignPackInfo(SemaRef.AlignPackStack.CurrentValue, Record);
4275 AddSourceLocation(SemaRef.AlignPackStack.CurrentPragmaLocation, Record);
4276 Record.push_back(SemaRef.AlignPackStack.Stack.size());
4277 for (const auto &StackEntry : SemaRef.AlignPackStack.Stack) {
4278 AddAlignPackInfo(StackEntry.Value, Record);
4279 AddSourceLocation(StackEntry.PragmaLocation, Record);
4280 AddSourceLocation(StackEntry.PragmaPushLocation, Record);
4281 AddString(StackEntry.StackSlotLabel, Record);
4283 Stream.EmitRecord(ALIGN_PACK_PRAGMA_OPTIONS, Record);
4286 /// Write the state of 'pragma float_control' at the end of the module.
4287 void ASTWriter::WriteFloatControlPragmaOptions(Sema &SemaRef) {
4288 // Don't serialize pragma float_control state for modules,
4289 // since it should only take effect on a per-submodule basis.
4290 if (WritingModule)
4291 return;
4293 RecordData Record;
4294 Record.push_back(SemaRef.FpPragmaStack.CurrentValue.getAsOpaqueInt());
4295 AddSourceLocation(SemaRef.FpPragmaStack.CurrentPragmaLocation, Record);
4296 Record.push_back(SemaRef.FpPragmaStack.Stack.size());
4297 for (const auto &StackEntry : SemaRef.FpPragmaStack.Stack) {
4298 Record.push_back(StackEntry.Value.getAsOpaqueInt());
4299 AddSourceLocation(StackEntry.PragmaLocation, Record);
4300 AddSourceLocation(StackEntry.PragmaPushLocation, Record);
4301 AddString(StackEntry.StackSlotLabel, Record);
4303 Stream.EmitRecord(FLOAT_CONTROL_PRAGMA_OPTIONS, Record);
4306 void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
4307 ModuleFileExtensionWriter &Writer) {
4308 // Enter the extension block.
4309 Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
4311 // Emit the metadata record abbreviation.
4312 auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
4313 Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
4314 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4315 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4316 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4317 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4318 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4319 unsigned Abbrev = Stream.EmitAbbrev(std::move(Abv));
4321 // Emit the metadata record.
4322 RecordData Record;
4323 auto Metadata = Writer.getExtension()->getExtensionMetadata();
4324 Record.push_back(EXTENSION_METADATA);
4325 Record.push_back(Metadata.MajorVersion);
4326 Record.push_back(Metadata.MinorVersion);
4327 Record.push_back(Metadata.BlockName.size());
4328 Record.push_back(Metadata.UserInfo.size());
4329 SmallString<64> Buffer;
4330 Buffer += Metadata.BlockName;
4331 Buffer += Metadata.UserInfo;
4332 Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
4334 // Emit the contents of the extension block.
4335 Writer.writeExtensionContents(SemaRef, Stream);
4337 // Exit the extension block.
4338 Stream.ExitBlock();
4341 //===----------------------------------------------------------------------===//
4342 // General Serialization Routines
4343 //===----------------------------------------------------------------------===//
4345 void ASTRecordWriter::AddAttr(const Attr *A) {
4346 auto &Record = *this;
4347 // FIXME: Clang can't handle the serialization/deserialization of
4348 // preferred_name properly now. See
4349 // https://github.com/llvm/llvm-project/issues/56490 for example.
4350 if (!A || (isa<PreferredNameAttr>(A) && Writer->isWritingNamedModules()))
4351 return Record.push_back(0);
4353 Record.push_back(A->getKind() + 1); // FIXME: stable encoding, target attrs
4355 Record.AddIdentifierRef(A->getAttrName());
4356 Record.AddIdentifierRef(A->getScopeName());
4357 Record.AddSourceRange(A->getRange());
4358 Record.AddSourceLocation(A->getScopeLoc());
4359 Record.push_back(A->getParsedKind());
4360 Record.push_back(A->getSyntax());
4361 Record.push_back(A->getAttributeSpellingListIndexRaw());
4363 #include "clang/Serialization/AttrPCHWrite.inc"
4366 /// Emit the list of attributes to the specified record.
4367 void ASTRecordWriter::AddAttributes(ArrayRef<const Attr *> Attrs) {
4368 push_back(Attrs.size());
4369 for (const auto *A : Attrs)
4370 AddAttr(A);
4373 void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
4374 AddSourceLocation(Tok.getLocation(), Record);
4375 Record.push_back(Tok.getLength());
4377 // FIXME: When reading literal tokens, reconstruct the literal pointer
4378 // if it is needed.
4379 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
4380 // FIXME: Should translate token kind to a stable encoding.
4381 Record.push_back(Tok.getKind());
4382 // FIXME: Should translate token flags to a stable encoding.
4383 Record.push_back(Tok.getFlags());
4386 void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
4387 Record.push_back(Str.size());
4388 Record.insert(Record.end(), Str.begin(), Str.end());
4391 bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
4392 assert(Context && "should have context when outputting path");
4394 bool Changed =
4395 cleanPathForOutput(Context->getSourceManager().getFileManager(), Path);
4397 // Remove a prefix to make the path relative, if relevant.
4398 const char *PathBegin = Path.data();
4399 const char *PathPtr =
4400 adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
4401 if (PathPtr != PathBegin) {
4402 Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
4403 Changed = true;
4406 return Changed;
4409 void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
4410 SmallString<128> FilePath(Path);
4411 PreparePathForOutput(FilePath);
4412 AddString(FilePath, Record);
4415 void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
4416 StringRef Path) {
4417 SmallString<128> FilePath(Path);
4418 PreparePathForOutput(FilePath);
4419 Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
4422 void ASTWriter::AddVersionTuple(const VersionTuple &Version,
4423 RecordDataImpl &Record) {
4424 Record.push_back(Version.getMajor());
4425 if (Optional<unsigned> Minor = Version.getMinor())
4426 Record.push_back(*Minor + 1);
4427 else
4428 Record.push_back(0);
4429 if (Optional<unsigned> Subminor = Version.getSubminor())
4430 Record.push_back(*Subminor + 1);
4431 else
4432 Record.push_back(0);
4435 /// Note that the identifier II occurs at the given offset
4436 /// within the identifier table.
4437 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
4438 IdentID ID = IdentifierIDs[II];
4439 // Only store offsets new to this AST file. Other identifier names are looked
4440 // up earlier in the chain and thus don't need an offset.
4441 if (ID >= FirstIdentID)
4442 IdentifierOffsets[ID - FirstIdentID] = Offset;
4445 /// Note that the selector Sel occurs at the given offset
4446 /// within the method pool/selector table.
4447 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
4448 unsigned ID = SelectorIDs[Sel];
4449 assert(ID && "Unknown selector");
4450 // Don't record offsets for selectors that are also available in a different
4451 // file.
4452 if (ID < FirstSelectorID)
4453 return;
4454 SelectorOffsets[ID - FirstSelectorID] = Offset;
4457 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream,
4458 SmallVectorImpl<char> &Buffer,
4459 InMemoryModuleCache &ModuleCache,
4460 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
4461 bool IncludeTimestamps)
4462 : Stream(Stream), Buffer(Buffer), ModuleCache(ModuleCache),
4463 IncludeTimestamps(IncludeTimestamps) {
4464 for (const auto &Ext : Extensions) {
4465 if (auto Writer = Ext->createExtensionWriter(*this))
4466 ModuleFileExtensionWriters.push_back(std::move(Writer));
4470 ASTWriter::~ASTWriter() = default;
4472 const LangOptions &ASTWriter::getLangOpts() const {
4473 assert(WritingAST && "can't determine lang opts when not writing AST");
4474 return Context->getLangOpts();
4477 time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const {
4478 return IncludeTimestamps ? E->getModificationTime() : 0;
4481 ASTFileSignature ASTWriter::WriteAST(Sema &SemaRef, StringRef OutputFile,
4482 Module *WritingModule, StringRef isysroot,
4483 bool hasErrors,
4484 bool ShouldCacheASTInMemory) {
4485 WritingAST = true;
4487 ASTHasCompilerErrors = hasErrors;
4489 // Emit the file header.
4490 Stream.Emit((unsigned)'C', 8);
4491 Stream.Emit((unsigned)'P', 8);
4492 Stream.Emit((unsigned)'C', 8);
4493 Stream.Emit((unsigned)'H', 8);
4495 WriteBlockInfoBlock();
4497 Context = &SemaRef.Context;
4498 PP = &SemaRef.PP;
4499 this->WritingModule = WritingModule;
4500 ASTFileSignature Signature = WriteASTCore(SemaRef, isysroot, WritingModule);
4501 Context = nullptr;
4502 PP = nullptr;
4503 this->WritingModule = nullptr;
4504 this->BaseDirectory.clear();
4506 WritingAST = false;
4507 if (ShouldCacheASTInMemory) {
4508 // Construct MemoryBuffer and update buffer manager.
4509 ModuleCache.addBuiltPCM(OutputFile,
4510 llvm::MemoryBuffer::getMemBufferCopy(
4511 StringRef(Buffer.begin(), Buffer.size())));
4513 return Signature;
4516 template<typename Vector>
4517 static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4518 ASTWriter::RecordData &Record) {
4519 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4520 I != E; ++I) {
4521 Writer.AddDeclRef(*I, Record);
4525 ASTFileSignature ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
4526 Module *WritingModule) {
4527 using namespace llvm;
4529 bool isModule = WritingModule != nullptr;
4531 // Make sure that the AST reader knows to finalize itself.
4532 if (Chain)
4533 Chain->finalizeForWriting();
4535 ASTContext &Context = SemaRef.Context;
4536 Preprocessor &PP = SemaRef.PP;
4538 // Set up predefined declaration IDs.
4539 auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
4540 if (D) {
4541 assert(D->isCanonicalDecl() && "predefined decl is not canonical");
4542 DeclIDs[D] = ID;
4545 RegisterPredefDecl(Context.getTranslationUnitDecl(),
4546 PREDEF_DECL_TRANSLATION_UNIT_ID);
4547 RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
4548 RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
4549 RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
4550 RegisterPredefDecl(Context.ObjCProtocolClassDecl,
4551 PREDEF_DECL_OBJC_PROTOCOL_ID);
4552 RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
4553 RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
4554 RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
4555 PREDEF_DECL_OBJC_INSTANCETYPE_ID);
4556 RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
4557 RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
4558 RegisterPredefDecl(Context.BuiltinMSVaListDecl,
4559 PREDEF_DECL_BUILTIN_MS_VA_LIST_ID);
4560 RegisterPredefDecl(Context.MSGuidTagDecl,
4561 PREDEF_DECL_BUILTIN_MS_GUID_ID);
4562 RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
4563 RegisterPredefDecl(Context.MakeIntegerSeqDecl,
4564 PREDEF_DECL_MAKE_INTEGER_SEQ_ID);
4565 RegisterPredefDecl(Context.CFConstantStringTypeDecl,
4566 PREDEF_DECL_CF_CONSTANT_STRING_ID);
4567 RegisterPredefDecl(Context.CFConstantStringTagDecl,
4568 PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID);
4569 RegisterPredefDecl(Context.TypePackElementDecl,
4570 PREDEF_DECL_TYPE_PACK_ELEMENT_ID);
4572 // Build a record containing all of the tentative definitions in this file, in
4573 // TentativeDefinitions order. Generally, this record will be empty for
4574 // headers.
4575 RecordData TentativeDefinitions;
4576 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
4578 // Build a record containing all of the file scoped decls in this file.
4579 RecordData UnusedFileScopedDecls;
4580 if (!isModule)
4581 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
4582 UnusedFileScopedDecls);
4584 // Build a record containing all of the delegating constructors we still need
4585 // to resolve.
4586 RecordData DelegatingCtorDecls;
4587 if (!isModule)
4588 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
4590 // Write the set of weak, undeclared identifiers. We always write the
4591 // entire table, since later PCH files in a PCH chain are only interested in
4592 // the results at the end of the chain.
4593 RecordData WeakUndeclaredIdentifiers;
4594 for (const auto &WeakUndeclaredIdentifierList :
4595 SemaRef.WeakUndeclaredIdentifiers) {
4596 const IdentifierInfo *const II = WeakUndeclaredIdentifierList.first;
4597 for (const auto &WI : WeakUndeclaredIdentifierList.second) {
4598 AddIdentifierRef(II, WeakUndeclaredIdentifiers);
4599 AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
4600 AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
4604 // Build a record containing all of the ext_vector declarations.
4605 RecordData ExtVectorDecls;
4606 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
4608 // Build a record containing all of the VTable uses information.
4609 RecordData VTableUses;
4610 if (!SemaRef.VTableUses.empty()) {
4611 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
4612 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4613 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4614 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4618 // Build a record containing all of the UnusedLocalTypedefNameCandidates.
4619 RecordData UnusedLocalTypedefNameCandidates;
4620 for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
4621 AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
4623 // Build a record containing all of pending implicit instantiations.
4624 RecordData PendingInstantiations;
4625 for (const auto &I : SemaRef.PendingInstantiations) {
4626 AddDeclRef(I.first, PendingInstantiations);
4627 AddSourceLocation(I.second, PendingInstantiations);
4629 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4630 "There are local ones at end of translation unit!");
4632 // Build a record containing some declaration references.
4633 RecordData SemaDeclRefs;
4634 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) {
4635 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4636 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
4637 AddDeclRef(SemaRef.getStdAlignValT(), SemaDeclRefs);
4640 RecordData CUDASpecialDeclRefs;
4641 if (Context.getcudaConfigureCallDecl()) {
4642 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4645 // Build a record containing all of the known namespaces.
4646 RecordData KnownNamespaces;
4647 for (const auto &I : SemaRef.KnownNamespaces) {
4648 if (!I.second)
4649 AddDeclRef(I.first, KnownNamespaces);
4652 // Build a record of all used, undefined objects that require definitions.
4653 RecordData UndefinedButUsed;
4655 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
4656 SemaRef.getUndefinedButUsed(Undefined);
4657 for (const auto &I : Undefined) {
4658 AddDeclRef(I.first, UndefinedButUsed);
4659 AddSourceLocation(I.second, UndefinedButUsed);
4662 // Build a record containing all delete-expressions that we would like to
4663 // analyze later in AST.
4664 RecordData DeleteExprsToAnalyze;
4666 if (!isModule) {
4667 for (const auto &DeleteExprsInfo :
4668 SemaRef.getMismatchingDeleteExpressions()) {
4669 AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
4670 DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
4671 for (const auto &DeleteLoc : DeleteExprsInfo.second) {
4672 AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
4673 DeleteExprsToAnalyze.push_back(DeleteLoc.second);
4678 // Write the control block
4679 WriteControlBlock(PP, Context, isysroot);
4681 // Write the remaining AST contents.
4682 Stream.FlushToWord();
4683 ASTBlockRange.first = Stream.GetCurrentBitNo();
4684 Stream.EnterSubblock(AST_BLOCK_ID, 5);
4685 ASTBlockStartOffset = Stream.GetCurrentBitNo();
4687 // This is so that older clang versions, before the introduction
4688 // of the control block, can read and reject the newer PCH format.
4690 RecordData Record = {VERSION_MAJOR};
4691 Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4694 // Create a lexical update block containing all of the declarations in the
4695 // translation unit that do not come from other AST files.
4696 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
4697 SmallVector<uint32_t, 128> NewGlobalKindDeclPairs;
4698 for (const auto *D : TU->noload_decls()) {
4699 if (!D->isFromASTFile()) {
4700 NewGlobalKindDeclPairs.push_back(D->getKind());
4701 NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
4705 auto Abv = std::make_shared<BitCodeAbbrev>();
4706 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4707 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4708 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv));
4710 RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
4711 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4712 bytes(NewGlobalKindDeclPairs));
4715 // And a visible updates block for the translation unit.
4716 Abv = std::make_shared<BitCodeAbbrev>();
4717 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4718 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4719 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4720 UpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv));
4721 WriteDeclContextVisibleUpdate(TU);
4723 // If we have any extern "C" names, write out a visible update for them.
4724 if (Context.ExternCContext)
4725 WriteDeclContextVisibleUpdate(Context.ExternCContext);
4727 // If the translation unit has an anonymous namespace, and we don't already
4728 // have an update block for it, write it as an update block.
4729 // FIXME: Why do we not do this if there's already an update block?
4730 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4731 ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
4732 if (Record.empty())
4733 Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
4736 // Add update records for all mangling numbers and static local numbers.
4737 // These aren't really update records, but this is a convenient way of
4738 // tagging this rare extra data onto the declarations.
4739 for (const auto &Number : Context.MangleNumbers)
4740 if (!Number.first->isFromASTFile())
4741 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4742 Number.second));
4743 for (const auto &Number : Context.StaticLocalNumbers)
4744 if (!Number.first->isFromASTFile())
4745 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4746 Number.second));
4748 // Make sure visible decls, added to DeclContexts previously loaded from
4749 // an AST file, are registered for serialization. Likewise for template
4750 // specializations added to imported templates.
4751 for (const auto *I : DeclsToEmitEvenIfUnreferenced) {
4752 GetDeclRef(I);
4755 // Make sure all decls associated with an identifier are registered for
4756 // serialization, if we're storing decls with identifiers.
4757 if (!WritingModule || !getLangOpts().CPlusPlus) {
4758 llvm::SmallVector<const IdentifierInfo*, 256> IIs;
4759 for (const auto &ID : PP.getIdentifierTable()) {
4760 const IdentifierInfo *II = ID.second;
4761 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
4762 IIs.push_back(II);
4764 // Sort the identifiers to visit based on their name.
4765 llvm::sort(IIs, llvm::deref<std::less<>>());
4766 for (const IdentifierInfo *II : IIs) {
4767 for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4768 DEnd = SemaRef.IdResolver.end();
4769 D != DEnd; ++D) {
4770 GetDeclRef(*D);
4775 // For method pool in the module, if it contains an entry for a selector,
4776 // the entry should be complete, containing everything introduced by that
4777 // module and all modules it imports. It's possible that the entry is out of
4778 // date, so we need to pull in the new content here.
4780 // It's possible that updateOutOfDateSelector can update SelectorIDs. To be
4781 // safe, we copy all selectors out.
4782 llvm::SmallVector<Selector, 256> AllSelectors;
4783 for (auto &SelectorAndID : SelectorIDs)
4784 AllSelectors.push_back(SelectorAndID.first);
4785 for (auto &Selector : AllSelectors)
4786 SemaRef.updateOutOfDateSelector(Selector);
4788 // Form the record of special types.
4789 RecordData SpecialTypes;
4790 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
4791 AddTypeRef(Context.getFILEType(), SpecialTypes);
4792 AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4793 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4794 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4795 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
4796 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
4797 AddTypeRef(Context.getucontext_tType(), SpecialTypes);
4799 if (Chain) {
4800 // Write the mapping information describing our module dependencies and how
4801 // each of those modules were mapped into our own offset/ID space, so that
4802 // the reader can build the appropriate mapping to its own offset/ID space.
4803 // The map consists solely of a blob with the following format:
4804 // *(module-kind:i8
4805 // module-name-len:i16 module-name:len*i8
4806 // source-location-offset:i32
4807 // identifier-id:i32
4808 // preprocessed-entity-id:i32
4809 // macro-definition-id:i32
4810 // submodule-id:i32
4811 // selector-id:i32
4812 // declaration-id:i32
4813 // c++-base-specifiers-id:i32
4814 // type-id:i32)
4816 // module-kind is the ModuleKind enum value. If it is MK_PrebuiltModule,
4817 // MK_ExplicitModule or MK_ImplicitModule, then the module-name is the
4818 // module name. Otherwise, it is the module file name.
4819 auto Abbrev = std::make_shared<BitCodeAbbrev>();
4820 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4821 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4822 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
4823 SmallString<2048> Buffer;
4825 llvm::raw_svector_ostream Out(Buffer);
4826 for (ModuleFile &M : Chain->ModuleMgr) {
4827 using namespace llvm::support;
4829 endian::Writer LE(Out, little);
4830 LE.write<uint8_t>(static_cast<uint8_t>(M.Kind));
4831 StringRef Name = M.isModule() ? M.ModuleName : M.FileName;
4832 LE.write<uint16_t>(Name.size());
4833 Out.write(Name.data(), Name.size());
4835 // Note: if a base ID was uint max, it would not be possible to load
4836 // another module after it or have more than one entity inside it.
4837 uint32_t None = std::numeric_limits<uint32_t>::max();
4839 auto writeBaseIDOrNone = [&](auto BaseID, bool ShouldWrite) {
4840 assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
4841 if (ShouldWrite)
4842 LE.write<uint32_t>(BaseID);
4843 else
4844 LE.write<uint32_t>(None);
4847 // These values should be unique within a chain, since they will be read
4848 // as keys into ContinuousRangeMaps.
4849 writeBaseIDOrNone(M.SLocEntryBaseOffset, M.LocalNumSLocEntries);
4850 writeBaseIDOrNone(M.BaseIdentifierID, M.LocalNumIdentifiers);
4851 writeBaseIDOrNone(M.BaseMacroID, M.LocalNumMacros);
4852 writeBaseIDOrNone(M.BasePreprocessedEntityID,
4853 M.NumPreprocessedEntities);
4854 writeBaseIDOrNone(M.BaseSubmoduleID, M.LocalNumSubmodules);
4855 writeBaseIDOrNone(M.BaseSelectorID, M.LocalNumSelectors);
4856 writeBaseIDOrNone(M.BaseDeclID, M.LocalNumDecls);
4857 writeBaseIDOrNone(M.BaseTypeIndex, M.LocalNumTypes);
4860 RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
4861 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4862 Buffer.data(), Buffer.size());
4865 // Build a record containing all of the DeclsToCheckForDeferredDiags.
4866 SmallVector<serialization::DeclID, 64> DeclsToCheckForDeferredDiags;
4867 for (auto *D : SemaRef.DeclsToCheckForDeferredDiags)
4868 DeclsToCheckForDeferredDiags.push_back(GetDeclRef(D));
4870 RecordData DeclUpdatesOffsetsRecord;
4872 // Keep writing types, declarations, and declaration update records
4873 // until we've emitted all of them.
4874 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
4875 DeclTypesBlockStartOffset = Stream.GetCurrentBitNo();
4876 WriteTypeAbbrevs();
4877 WriteDeclAbbrevs();
4878 do {
4879 WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
4880 while (!DeclTypesToEmit.empty()) {
4881 DeclOrType DOT = DeclTypesToEmit.front();
4882 DeclTypesToEmit.pop();
4883 if (DOT.isType())
4884 WriteType(DOT.getType());
4885 else
4886 WriteDecl(Context, DOT.getDecl());
4888 } while (!DeclUpdates.empty());
4889 Stream.ExitBlock();
4891 DoneWritingDeclsAndTypes = true;
4893 // These things can only be done once we've written out decls and types.
4894 WriteTypeDeclOffsets();
4895 if (!DeclUpdatesOffsetsRecord.empty())
4896 Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
4897 WriteFileDeclIDsMap();
4898 WriteSourceManagerBlock(Context.getSourceManager(), PP);
4899 WriteComments();
4900 WritePreprocessor(PP, isModule);
4901 WriteHeaderSearch(PP.getHeaderSearchInfo());
4902 WriteSelectors(SemaRef);
4903 WriteReferencedSelectorsPool(SemaRef);
4904 WriteLateParsedTemplates(SemaRef);
4905 WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
4906 WriteFPPragmaOptions(SemaRef.CurFPFeatureOverrides());
4907 WriteOpenCLExtensions(SemaRef);
4908 WriteCUDAPragmas(SemaRef);
4910 // If we're emitting a module, write out the submodule information.
4911 if (WritingModule)
4912 WriteSubmodules(WritingModule);
4914 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
4916 // Write the record containing external, unnamed definitions.
4917 if (!EagerlyDeserializedDecls.empty())
4918 Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
4920 if (!ModularCodegenDecls.empty())
4921 Stream.EmitRecord(MODULAR_CODEGEN_DECLS, ModularCodegenDecls);
4923 // Write the record containing tentative definitions.
4924 if (!TentativeDefinitions.empty())
4925 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
4927 // Write the record containing unused file scoped decls.
4928 if (!UnusedFileScopedDecls.empty())
4929 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
4931 // Write the record containing weak undeclared identifiers.
4932 if (!WeakUndeclaredIdentifiers.empty())
4933 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
4934 WeakUndeclaredIdentifiers);
4936 // Write the record containing ext_vector type names.
4937 if (!ExtVectorDecls.empty())
4938 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
4940 // Write the record containing VTable uses information.
4941 if (!VTableUses.empty())
4942 Stream.EmitRecord(VTABLE_USES, VTableUses);
4944 // Write the record containing potentially unused local typedefs.
4945 if (!UnusedLocalTypedefNameCandidates.empty())
4946 Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
4947 UnusedLocalTypedefNameCandidates);
4949 // Write the record containing pending implicit instantiations.
4950 if (!PendingInstantiations.empty())
4951 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
4953 // Write the record containing declaration references of Sema.
4954 if (!SemaDeclRefs.empty())
4955 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
4957 // Write the record containing decls to be checked for deferred diags.
4958 if (!DeclsToCheckForDeferredDiags.empty())
4959 Stream.EmitRecord(DECLS_TO_CHECK_FOR_DEFERRED_DIAGS,
4960 DeclsToCheckForDeferredDiags);
4962 // Write the record containing CUDA-specific declaration references.
4963 if (!CUDASpecialDeclRefs.empty())
4964 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
4966 // Write the delegating constructors.
4967 if (!DelegatingCtorDecls.empty())
4968 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
4970 // Write the known namespaces.
4971 if (!KnownNamespaces.empty())
4972 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
4974 // Write the undefined internal functions and variables, and inline functions.
4975 if (!UndefinedButUsed.empty())
4976 Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
4978 if (!DeleteExprsToAnalyze.empty())
4979 Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
4981 // Write the visible updates to DeclContexts.
4982 for (auto *DC : UpdatedDeclContexts)
4983 WriteDeclContextVisibleUpdate(DC);
4985 if (!WritingModule) {
4986 // Write the submodules that were imported, if any.
4987 struct ModuleInfo {
4988 uint64_t ID;
4989 Module *M;
4990 ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
4992 llvm::SmallVector<ModuleInfo, 64> Imports;
4993 for (const auto *I : Context.local_imports()) {
4994 assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
4995 Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
4996 I->getImportedModule()));
4999 if (!Imports.empty()) {
5000 auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
5001 return A.ID < B.ID;
5003 auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
5004 return A.ID == B.ID;
5007 // Sort and deduplicate module IDs.
5008 llvm::sort(Imports, Cmp);
5009 Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
5010 Imports.end());
5012 RecordData ImportedModules;
5013 for (const auto &Import : Imports) {
5014 ImportedModules.push_back(Import.ID);
5015 // FIXME: If the module has macros imported then later has declarations
5016 // imported, this location won't be the right one as a location for the
5017 // declaration imports.
5018 AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules);
5021 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
5025 WriteObjCCategories();
5026 if(!WritingModule) {
5027 WriteOptimizePragmaOptions(SemaRef);
5028 WriteMSStructPragmaOptions(SemaRef);
5029 WriteMSPointersToMembersPragmaOptions(SemaRef);
5031 WritePackPragmaOptions(SemaRef);
5032 WriteFloatControlPragmaOptions(SemaRef);
5034 // Some simple statistics
5035 RecordData::value_type Record[] = {
5036 NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts};
5037 Stream.EmitRecord(STATISTICS, Record);
5038 Stream.ExitBlock();
5039 Stream.FlushToWord();
5040 ASTBlockRange.second = Stream.GetCurrentBitNo();
5042 // Write the module file extension blocks.
5043 for (const auto &ExtWriter : ModuleFileExtensionWriters)
5044 WriteModuleFileExtension(SemaRef, *ExtWriter);
5046 return writeUnhashedControlBlock(PP, Context);
5049 void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
5050 if (DeclUpdates.empty())
5051 return;
5053 DeclUpdateMap LocalUpdates;
5054 LocalUpdates.swap(DeclUpdates);
5056 for (auto &DeclUpdate : LocalUpdates) {
5057 const Decl *D = DeclUpdate.first;
5059 bool HasUpdatedBody = false;
5060 RecordData RecordData;
5061 ASTRecordWriter Record(*this, RecordData);
5062 for (auto &Update : DeclUpdate.second) {
5063 DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
5065 // An updated body is emitted last, so that the reader doesn't need
5066 // to skip over the lazy body to reach statements for other records.
5067 if (Kind == UPD_CXX_ADDED_FUNCTION_DEFINITION)
5068 HasUpdatedBody = true;
5069 else
5070 Record.push_back(Kind);
5072 switch (Kind) {
5073 case UPD_CXX_ADDED_IMPLICIT_MEMBER:
5074 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
5075 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
5076 assert(Update.getDecl() && "no decl to add?");
5077 Record.push_back(GetDeclRef(Update.getDecl()));
5078 break;
5080 case UPD_CXX_ADDED_FUNCTION_DEFINITION:
5081 break;
5083 case UPD_CXX_POINT_OF_INSTANTIATION:
5084 // FIXME: Do we need to also save the template specialization kind here?
5085 Record.AddSourceLocation(Update.getLoc());
5086 break;
5088 case UPD_CXX_ADDED_VAR_DEFINITION: {
5089 const VarDecl *VD = cast<VarDecl>(D);
5090 Record.push_back(VD->isInline());
5091 Record.push_back(VD->isInlineSpecified());
5092 Record.AddVarDeclInit(VD);
5093 break;
5096 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT:
5097 Record.AddStmt(const_cast<Expr *>(
5098 cast<ParmVarDecl>(Update.getDecl())->getDefaultArg()));
5099 break;
5101 case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER:
5102 Record.AddStmt(
5103 cast<FieldDecl>(Update.getDecl())->getInClassInitializer());
5104 break;
5106 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
5107 auto *RD = cast<CXXRecordDecl>(D);
5108 UpdatedDeclContexts.insert(RD->getPrimaryContext());
5109 Record.push_back(RD->isParamDestroyedInCallee());
5110 Record.push_back(RD->getArgPassingRestrictions());
5111 Record.AddCXXDefinitionData(RD);
5112 Record.AddOffset(WriteDeclContextLexicalBlock(
5113 *Context, const_cast<CXXRecordDecl *>(RD)));
5115 // This state is sometimes updated by template instantiation, when we
5116 // switch from the specialization referring to the template declaration
5117 // to it referring to the template definition.
5118 if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
5119 Record.push_back(MSInfo->getTemplateSpecializationKind());
5120 Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
5121 } else {
5122 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
5123 Record.push_back(Spec->getTemplateSpecializationKind());
5124 Record.AddSourceLocation(Spec->getPointOfInstantiation());
5126 // The instantiation might have been resolved to a partial
5127 // specialization. If so, record which one.
5128 auto From = Spec->getInstantiatedFrom();
5129 if (auto PartialSpec =
5130 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
5131 Record.push_back(true);
5132 Record.AddDeclRef(PartialSpec);
5133 Record.AddTemplateArgumentList(
5134 &Spec->getTemplateInstantiationArgs());
5135 } else {
5136 Record.push_back(false);
5139 Record.push_back(RD->getTagKind());
5140 Record.AddSourceLocation(RD->getLocation());
5141 Record.AddSourceLocation(RD->getBeginLoc());
5142 Record.AddSourceRange(RD->getBraceRange());
5144 // Instantiation may change attributes; write them all out afresh.
5145 Record.push_back(D->hasAttrs());
5146 if (D->hasAttrs())
5147 Record.AddAttributes(D->getAttrs());
5149 // FIXME: Ensure we don't get here for explicit instantiations.
5150 break;
5153 case UPD_CXX_RESOLVED_DTOR_DELETE:
5154 Record.AddDeclRef(Update.getDecl());
5155 Record.AddStmt(cast<CXXDestructorDecl>(D)->getOperatorDeleteThisArg());
5156 break;
5158 case UPD_CXX_RESOLVED_EXCEPTION_SPEC: {
5159 auto prototype =
5160 cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>();
5161 Record.writeExceptionSpecInfo(prototype->getExceptionSpecInfo());
5162 break;
5165 case UPD_CXX_DEDUCED_RETURN_TYPE:
5166 Record.push_back(GetOrCreateTypeID(Update.getType()));
5167 break;
5169 case UPD_DECL_MARKED_USED:
5170 break;
5172 case UPD_MANGLING_NUMBER:
5173 case UPD_STATIC_LOCAL_NUMBER:
5174 Record.push_back(Update.getNumber());
5175 break;
5177 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
5178 Record.AddSourceRange(
5179 D->getAttr<OMPThreadPrivateDeclAttr>()->getRange());
5180 break;
5182 case UPD_DECL_MARKED_OPENMP_ALLOCATE: {
5183 auto *A = D->getAttr<OMPAllocateDeclAttr>();
5184 Record.push_back(A->getAllocatorType());
5185 Record.AddStmt(A->getAllocator());
5186 Record.AddStmt(A->getAlignment());
5187 Record.AddSourceRange(A->getRange());
5188 break;
5191 case UPD_DECL_MARKED_OPENMP_DECLARETARGET:
5192 Record.push_back(D->getAttr<OMPDeclareTargetDeclAttr>()->getMapType());
5193 Record.AddSourceRange(
5194 D->getAttr<OMPDeclareTargetDeclAttr>()->getRange());
5195 break;
5197 case UPD_DECL_EXPORTED:
5198 Record.push_back(getSubmoduleID(Update.getModule()));
5199 break;
5201 case UPD_ADDED_ATTR_TO_RECORD:
5202 Record.AddAttributes(llvm::makeArrayRef(Update.getAttr()));
5203 break;
5207 if (HasUpdatedBody) {
5208 const auto *Def = cast<FunctionDecl>(D);
5209 Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
5210 Record.push_back(Def->isInlined());
5211 Record.AddSourceLocation(Def->getInnerLocStart());
5212 Record.AddFunctionDefinition(Def);
5215 OffsetsRecord.push_back(GetDeclRef(D));
5216 OffsetsRecord.push_back(Record.Emit(DECL_UPDATES));
5220 void ASTWriter::AddAlignPackInfo(const Sema::AlignPackInfo &Info,
5221 RecordDataImpl &Record) {
5222 uint32_t Raw = Sema::AlignPackInfo::getRawEncoding(Info);
5223 Record.push_back(Raw);
5226 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record,
5227 SourceLocationSequence *Seq) {
5228 Record.push_back(SourceLocationEncoding::encode(Loc, Seq));
5231 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record,
5232 SourceLocationSequence *Seq) {
5233 AddSourceLocation(Range.getBegin(), Record, Seq);
5234 AddSourceLocation(Range.getEnd(), Record, Seq);
5237 void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) {
5238 AddAPInt(Value.bitcastToAPInt());
5241 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
5242 Record.push_back(getIdentifierRef(II));
5245 IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
5246 if (!II)
5247 return 0;
5249 IdentID &ID = IdentifierIDs[II];
5250 if (ID == 0)
5251 ID = NextIdentID++;
5252 return ID;
5255 MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
5256 // Don't emit builtin macros like __LINE__ to the AST file unless they
5257 // have been redefined by the header (in which case they are not
5258 // isBuiltinMacro).
5259 if (!MI || MI->isBuiltinMacro())
5260 return 0;
5262 MacroID &ID = MacroIDs[MI];
5263 if (ID == 0) {
5264 ID = NextMacroID++;
5265 MacroInfoToEmitData Info = { Name, MI, ID };
5266 MacroInfosToEmit.push_back(Info);
5268 return ID;
5271 MacroID ASTWriter::getMacroID(MacroInfo *MI) {
5272 if (!MI || MI->isBuiltinMacro())
5273 return 0;
5275 assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
5276 return MacroIDs[MI];
5279 uint32_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
5280 return IdentMacroDirectivesOffsetMap.lookup(Name);
5283 void ASTRecordWriter::AddSelectorRef(const Selector SelRef) {
5284 Record->push_back(Writer->getSelectorRef(SelRef));
5287 SelectorID ASTWriter::getSelectorRef(Selector Sel) {
5288 if (Sel.getAsOpaquePtr() == nullptr) {
5289 return 0;
5292 SelectorID SID = SelectorIDs[Sel];
5293 if (SID == 0 && Chain) {
5294 // This might trigger a ReadSelector callback, which will set the ID for
5295 // this selector.
5296 Chain->LoadSelector(Sel);
5297 SID = SelectorIDs[Sel];
5299 if (SID == 0) {
5300 SID = NextSelectorID++;
5301 SelectorIDs[Sel] = SID;
5303 return SID;
5306 void ASTRecordWriter::AddCXXTemporary(const CXXTemporary *Temp) {
5307 AddDeclRef(Temp->getDestructor());
5310 void ASTRecordWriter::AddTemplateArgumentLocInfo(
5311 TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg) {
5312 switch (Kind) {
5313 case TemplateArgument::Expression:
5314 AddStmt(Arg.getAsExpr());
5315 break;
5316 case TemplateArgument::Type:
5317 AddTypeSourceInfo(Arg.getAsTypeSourceInfo());
5318 break;
5319 case TemplateArgument::Template:
5320 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5321 AddSourceLocation(Arg.getTemplateNameLoc());
5322 break;
5323 case TemplateArgument::TemplateExpansion:
5324 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5325 AddSourceLocation(Arg.getTemplateNameLoc());
5326 AddSourceLocation(Arg.getTemplateEllipsisLoc());
5327 break;
5328 case TemplateArgument::Null:
5329 case TemplateArgument::Integral:
5330 case TemplateArgument::Declaration:
5331 case TemplateArgument::NullPtr:
5332 case TemplateArgument::Pack:
5333 // FIXME: Is this right?
5334 break;
5338 void ASTRecordWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg) {
5339 AddTemplateArgument(Arg.getArgument());
5341 if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
5342 bool InfoHasSameExpr
5343 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
5344 Record->push_back(InfoHasSameExpr);
5345 if (InfoHasSameExpr)
5346 return; // Avoid storing the same expr twice.
5348 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo());
5351 void ASTRecordWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo) {
5352 if (!TInfo) {
5353 AddTypeRef(QualType());
5354 return;
5357 AddTypeRef(TInfo->getType());
5358 AddTypeLoc(TInfo->getTypeLoc());
5361 void ASTRecordWriter::AddTypeLoc(TypeLoc TL, LocSeq *OuterSeq) {
5362 LocSeq::State Seq(OuterSeq);
5363 TypeLocWriter TLW(*this, Seq);
5364 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
5365 TLW.Visit(TL);
5368 void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
5369 Record.push_back(GetOrCreateTypeID(T));
5372 TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
5373 assert(Context);
5374 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5375 if (T.isNull())
5376 return TypeIdx();
5377 assert(!T.getLocalFastQualifiers());
5379 TypeIdx &Idx = TypeIdxs[T];
5380 if (Idx.getIndex() == 0) {
5381 if (DoneWritingDeclsAndTypes) {
5382 assert(0 && "New type seen after serializing all the types to emit!");
5383 return TypeIdx();
5386 // We haven't seen this type before. Assign it a new ID and put it
5387 // into the queue of types to emit.
5388 Idx = TypeIdx(NextTypeID++);
5389 DeclTypesToEmit.push(T);
5391 return Idx;
5395 TypeID ASTWriter::getTypeID(QualType T) const {
5396 assert(Context);
5397 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5398 if (T.isNull())
5399 return TypeIdx();
5400 assert(!T.getLocalFastQualifiers());
5402 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
5403 assert(I != TypeIdxs.end() && "Type not emitted!");
5404 return I->second;
5408 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
5409 Record.push_back(GetDeclRef(D));
5412 DeclID ASTWriter::GetDeclRef(const Decl *D) {
5413 assert(WritingAST && "Cannot request a declaration ID before AST writing");
5415 if (!D) {
5416 return 0;
5419 // If D comes from an AST file, its declaration ID is already known and
5420 // fixed.
5421 if (D->isFromASTFile())
5422 return D->getGlobalID();
5424 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
5425 DeclID &ID = DeclIDs[D];
5426 if (ID == 0) {
5427 if (DoneWritingDeclsAndTypes) {
5428 assert(0 && "New decl seen after serializing all the decls to emit!");
5429 return 0;
5432 // We haven't seen this declaration before. Give it a new ID and
5433 // enqueue it in the list of declarations to emit.
5434 ID = NextDeclID++;
5435 DeclTypesToEmit.push(const_cast<Decl *>(D));
5438 return ID;
5441 DeclID ASTWriter::getDeclID(const Decl *D) {
5442 if (!D)
5443 return 0;
5445 // If D comes from an AST file, its declaration ID is already known and
5446 // fixed.
5447 if (D->isFromASTFile())
5448 return D->getGlobalID();
5450 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
5451 return DeclIDs[D];
5454 void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
5455 assert(ID);
5456 assert(D);
5458 SourceLocation Loc = D->getLocation();
5459 if (Loc.isInvalid())
5460 return;
5462 // We only keep track of the file-level declarations of each file.
5463 if (!D->getLexicalDeclContext()->isFileContext())
5464 return;
5465 // FIXME: ParmVarDecls that are part of a function type of a parameter of
5466 // a function/objc method, should not have TU as lexical context.
5467 // TemplateTemplateParmDecls that are part of an alias template, should not
5468 // have TU as lexical context.
5469 if (isa<ParmVarDecl>(D) || isa<TemplateTemplateParmDecl>(D))
5470 return;
5472 SourceManager &SM = Context->getSourceManager();
5473 SourceLocation FileLoc = SM.getFileLoc(Loc);
5474 assert(SM.isLocalSourceLocation(FileLoc));
5475 FileID FID;
5476 unsigned Offset;
5477 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
5478 if (FID.isInvalid())
5479 return;
5480 assert(SM.getSLocEntry(FID).isFile());
5482 std::unique_ptr<DeclIDInFileInfo> &Info = FileDeclIDs[FID];
5483 if (!Info)
5484 Info = std::make_unique<DeclIDInFileInfo>();
5486 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
5487 LocDeclIDsTy &Decls = Info->DeclIDs;
5488 Decls.push_back(LocDecl);
5491 unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {
5492 assert(needsAnonymousDeclarationNumber(D) &&
5493 "expected an anonymous declaration");
5495 // Number the anonymous declarations within this context, if we've not
5496 // already done so.
5497 auto It = AnonymousDeclarationNumbers.find(D);
5498 if (It == AnonymousDeclarationNumbers.end()) {
5499 auto *DC = D->getLexicalDeclContext();
5500 numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
5501 AnonymousDeclarationNumbers[ND] = Number;
5504 It = AnonymousDeclarationNumbers.find(D);
5505 assert(It != AnonymousDeclarationNumbers.end() &&
5506 "declaration not found within its lexical context");
5509 return It->second;
5512 void ASTRecordWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
5513 DeclarationName Name) {
5514 switch (Name.getNameKind()) {
5515 case DeclarationName::CXXConstructorName:
5516 case DeclarationName::CXXDestructorName:
5517 case DeclarationName::CXXConversionFunctionName:
5518 AddTypeSourceInfo(DNLoc.getNamedTypeInfo());
5519 break;
5521 case DeclarationName::CXXOperatorName:
5522 AddSourceRange(DNLoc.getCXXOperatorNameRange());
5523 break;
5525 case DeclarationName::CXXLiteralOperatorName:
5526 AddSourceLocation(DNLoc.getCXXLiteralOperatorNameLoc());
5527 break;
5529 case DeclarationName::Identifier:
5530 case DeclarationName::ObjCZeroArgSelector:
5531 case DeclarationName::ObjCOneArgSelector:
5532 case DeclarationName::ObjCMultiArgSelector:
5533 case DeclarationName::CXXUsingDirective:
5534 case DeclarationName::CXXDeductionGuideName:
5535 break;
5539 void ASTRecordWriter::AddDeclarationNameInfo(
5540 const DeclarationNameInfo &NameInfo) {
5541 AddDeclarationName(NameInfo.getName());
5542 AddSourceLocation(NameInfo.getLoc());
5543 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName());
5546 void ASTRecordWriter::AddQualifierInfo(const QualifierInfo &Info) {
5547 AddNestedNameSpecifierLoc(Info.QualifierLoc);
5548 Record->push_back(Info.NumTemplParamLists);
5549 for (unsigned i = 0, e = Info.NumTemplParamLists; i != e; ++i)
5550 AddTemplateParameterList(Info.TemplParamLists[i]);
5553 void ASTRecordWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
5554 // Nested name specifiers usually aren't too long. I think that 8 would
5555 // typically accommodate the vast majority.
5556 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
5558 // Push each of the nested-name-specifiers's onto a stack for
5559 // serialization in reverse order.
5560 while (NNS) {
5561 NestedNames.push_back(NNS);
5562 NNS = NNS.getPrefix();
5565 Record->push_back(NestedNames.size());
5566 while(!NestedNames.empty()) {
5567 NNS = NestedNames.pop_back_val();
5568 NestedNameSpecifier::SpecifierKind Kind
5569 = NNS.getNestedNameSpecifier()->getKind();
5570 Record->push_back(Kind);
5571 switch (Kind) {
5572 case NestedNameSpecifier::Identifier:
5573 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier());
5574 AddSourceRange(NNS.getLocalSourceRange());
5575 break;
5577 case NestedNameSpecifier::Namespace:
5578 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace());
5579 AddSourceRange(NNS.getLocalSourceRange());
5580 break;
5582 case NestedNameSpecifier::NamespaceAlias:
5583 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias());
5584 AddSourceRange(NNS.getLocalSourceRange());
5585 break;
5587 case NestedNameSpecifier::TypeSpec:
5588 case NestedNameSpecifier::TypeSpecWithTemplate:
5589 Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5590 AddTypeRef(NNS.getTypeLoc().getType());
5591 AddTypeLoc(NNS.getTypeLoc());
5592 AddSourceLocation(NNS.getLocalSourceRange().getEnd());
5593 break;
5595 case NestedNameSpecifier::Global:
5596 AddSourceLocation(NNS.getLocalSourceRange().getEnd());
5597 break;
5599 case NestedNameSpecifier::Super:
5600 AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl());
5601 AddSourceRange(NNS.getLocalSourceRange());
5602 break;
5607 void ASTRecordWriter::AddTemplateParameterList(
5608 const TemplateParameterList *TemplateParams) {
5609 assert(TemplateParams && "No TemplateParams!");
5610 AddSourceLocation(TemplateParams->getTemplateLoc());
5611 AddSourceLocation(TemplateParams->getLAngleLoc());
5612 AddSourceLocation(TemplateParams->getRAngleLoc());
5614 Record->push_back(TemplateParams->size());
5615 for (const auto &P : *TemplateParams)
5616 AddDeclRef(P);
5617 if (const Expr *RequiresClause = TemplateParams->getRequiresClause()) {
5618 Record->push_back(true);
5619 AddStmt(const_cast<Expr*>(RequiresClause));
5620 } else {
5621 Record->push_back(false);
5625 /// Emit a template argument list.
5626 void ASTRecordWriter::AddTemplateArgumentList(
5627 const TemplateArgumentList *TemplateArgs) {
5628 assert(TemplateArgs && "No TemplateArgs!");
5629 Record->push_back(TemplateArgs->size());
5630 for (int i = 0, e = TemplateArgs->size(); i != e; ++i)
5631 AddTemplateArgument(TemplateArgs->get(i));
5634 void ASTRecordWriter::AddASTTemplateArgumentListInfo(
5635 const ASTTemplateArgumentListInfo *ASTTemplArgList) {
5636 assert(ASTTemplArgList && "No ASTTemplArgList!");
5637 AddSourceLocation(ASTTemplArgList->LAngleLoc);
5638 AddSourceLocation(ASTTemplArgList->RAngleLoc);
5639 Record->push_back(ASTTemplArgList->NumTemplateArgs);
5640 const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
5641 for (int i = 0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
5642 AddTemplateArgumentLoc(TemplArgs[i]);
5645 void ASTRecordWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set) {
5646 Record->push_back(Set.size());
5647 for (ASTUnresolvedSet::const_iterator
5648 I = Set.begin(), E = Set.end(); I != E; ++I) {
5649 AddDeclRef(I.getDecl());
5650 Record->push_back(I.getAccess());
5654 // FIXME: Move this out of the main ASTRecordWriter interface.
5655 void ASTRecordWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
5656 Record->push_back(Base.isVirtual());
5657 Record->push_back(Base.isBaseOfClass());
5658 Record->push_back(Base.getAccessSpecifierAsWritten());
5659 Record->push_back(Base.getInheritConstructors());
5660 AddTypeSourceInfo(Base.getTypeSourceInfo());
5661 AddSourceRange(Base.getSourceRange());
5662 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
5663 : SourceLocation());
5666 static uint64_t EmitCXXBaseSpecifiers(ASTWriter &W,
5667 ArrayRef<CXXBaseSpecifier> Bases) {
5668 ASTWriter::RecordData Record;
5669 ASTRecordWriter Writer(W, Record);
5670 Writer.push_back(Bases.size());
5672 for (auto &Base : Bases)
5673 Writer.AddCXXBaseSpecifier(Base);
5675 return Writer.Emit(serialization::DECL_CXX_BASE_SPECIFIERS);
5678 // FIXME: Move this out of the main ASTRecordWriter interface.
5679 void ASTRecordWriter::AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases) {
5680 AddOffset(EmitCXXBaseSpecifiers(*Writer, Bases));
5683 static uint64_t
5684 EmitCXXCtorInitializers(ASTWriter &W,
5685 ArrayRef<CXXCtorInitializer *> CtorInits) {
5686 ASTWriter::RecordData Record;
5687 ASTRecordWriter Writer(W, Record);
5688 Writer.push_back(CtorInits.size());
5690 for (auto *Init : CtorInits) {
5691 if (Init->isBaseInitializer()) {
5692 Writer.push_back(CTOR_INITIALIZER_BASE);
5693 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
5694 Writer.push_back(Init->isBaseVirtual());
5695 } else if (Init->isDelegatingInitializer()) {
5696 Writer.push_back(CTOR_INITIALIZER_DELEGATING);
5697 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
5698 } else if (Init->isMemberInitializer()){
5699 Writer.push_back(CTOR_INITIALIZER_MEMBER);
5700 Writer.AddDeclRef(Init->getMember());
5701 } else {
5702 Writer.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
5703 Writer.AddDeclRef(Init->getIndirectMember());
5706 Writer.AddSourceLocation(Init->getMemberLocation());
5707 Writer.AddStmt(Init->getInit());
5708 Writer.AddSourceLocation(Init->getLParenLoc());
5709 Writer.AddSourceLocation(Init->getRParenLoc());
5710 Writer.push_back(Init->isWritten());
5711 if (Init->isWritten())
5712 Writer.push_back(Init->getSourceOrder());
5715 return Writer.Emit(serialization::DECL_CXX_CTOR_INITIALIZERS);
5718 // FIXME: Move this out of the main ASTRecordWriter interface.
5719 void ASTRecordWriter::AddCXXCtorInitializers(
5720 ArrayRef<CXXCtorInitializer *> CtorInits) {
5721 AddOffset(EmitCXXCtorInitializers(*Writer, CtorInits));
5724 void ASTRecordWriter::AddCXXDefinitionData(const CXXRecordDecl *D) {
5725 auto &Data = D->data();
5726 Record->push_back(Data.IsLambda);
5728 #define FIELD(Name, Width, Merge) \
5729 Record->push_back(Data.Name);
5730 #include "clang/AST/CXXRecordDeclDefinitionBits.def"
5732 // getODRHash will compute the ODRHash if it has not been previously computed.
5733 Record->push_back(D->getODRHash());
5734 bool ModulesDebugInfo =
5735 Writer->Context->getLangOpts().ModulesDebugInfo && !D->isDependentType();
5736 Record->push_back(ModulesDebugInfo);
5737 if (ModulesDebugInfo)
5738 Writer->ModularCodegenDecls.push_back(Writer->GetDeclRef(D));
5740 // IsLambda bit is already saved.
5742 Record->push_back(Data.NumBases);
5743 if (Data.NumBases > 0)
5744 AddCXXBaseSpecifiers(Data.bases());
5746 // FIXME: Make VBases lazily computed when needed to avoid storing them.
5747 Record->push_back(Data.NumVBases);
5748 if (Data.NumVBases > 0)
5749 AddCXXBaseSpecifiers(Data.vbases());
5751 AddUnresolvedSet(Data.Conversions.get(*Writer->Context));
5752 Record->push_back(Data.ComputedVisibleConversions);
5753 if (Data.ComputedVisibleConversions)
5754 AddUnresolvedSet(Data.VisibleConversions.get(*Writer->Context));
5755 // Data.Definition is the owning decl, no need to write it.
5756 AddDeclRef(D->getFirstFriend());
5758 // Add lambda-specific data.
5759 if (Data.IsLambda) {
5760 auto &Lambda = D->getLambdaData();
5761 Record->push_back(Lambda.DependencyKind);
5762 Record->push_back(Lambda.IsGenericLambda);
5763 Record->push_back(Lambda.CaptureDefault);
5764 Record->push_back(Lambda.NumCaptures);
5765 Record->push_back(Lambda.NumExplicitCaptures);
5766 Record->push_back(Lambda.HasKnownInternalLinkage);
5767 Record->push_back(Lambda.ManglingNumber);
5768 Record->push_back(D->getDeviceLambdaManglingNumber());
5769 AddDeclRef(D->getLambdaContextDecl());
5770 AddTypeSourceInfo(Lambda.MethodTyInfo);
5771 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
5772 const LambdaCapture &Capture = Lambda.Captures[I];
5773 AddSourceLocation(Capture.getLocation());
5774 Record->push_back(Capture.isImplicit());
5775 Record->push_back(Capture.getCaptureKind());
5776 switch (Capture.getCaptureKind()) {
5777 case LCK_StarThis:
5778 case LCK_This:
5779 case LCK_VLAType:
5780 break;
5781 case LCK_ByCopy:
5782 case LCK_ByRef:
5783 ValueDecl *Var =
5784 Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
5785 AddDeclRef(Var);
5786 AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
5787 : SourceLocation());
5788 break;
5794 void ASTRecordWriter::AddVarDeclInit(const VarDecl *VD) {
5795 const Expr *Init = VD->getInit();
5796 if (!Init) {
5797 push_back(0);
5798 return;
5801 unsigned Val = 1;
5802 if (EvaluatedStmt *ES = VD->getEvaluatedStmt()) {
5803 Val |= (ES->HasConstantInitialization ? 2 : 0);
5804 Val |= (ES->HasConstantDestruction ? 4 : 0);
5805 // FIXME: Also emit the constant initializer value.
5807 push_back(Val);
5808 writeStmtRef(Init);
5811 void ASTWriter::ReaderInitialized(ASTReader *Reader) {
5812 assert(Reader && "Cannot remove chain");
5813 assert((!Chain || Chain == Reader) && "Cannot replace chain");
5814 assert(FirstDeclID == NextDeclID &&
5815 FirstTypeID == NextTypeID &&
5816 FirstIdentID == NextIdentID &&
5817 FirstMacroID == NextMacroID &&
5818 FirstSubmoduleID == NextSubmoduleID &&
5819 FirstSelectorID == NextSelectorID &&
5820 "Setting chain after writing has started.");
5822 Chain = Reader;
5824 // Note, this will get called multiple times, once one the reader starts up
5825 // and again each time it's done reading a PCH or module.
5826 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
5827 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
5828 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
5829 FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
5830 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
5831 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
5832 NextDeclID = FirstDeclID;
5833 NextTypeID = FirstTypeID;
5834 NextIdentID = FirstIdentID;
5835 NextMacroID = FirstMacroID;
5836 NextSelectorID = FirstSelectorID;
5837 NextSubmoduleID = FirstSubmoduleID;
5840 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
5841 // Always keep the highest ID. See \p TypeRead() for more information.
5842 IdentID &StoredID = IdentifierIDs[II];
5843 if (ID > StoredID)
5844 StoredID = ID;
5847 void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
5848 // Always keep the highest ID. See \p TypeRead() for more information.
5849 MacroID &StoredID = MacroIDs[MI];
5850 if (ID > StoredID)
5851 StoredID = ID;
5854 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
5855 // Always take the highest-numbered type index. This copes with an interesting
5856 // case for chained AST writing where we schedule writing the type and then,
5857 // later, deserialize the type from another AST. In this case, we want to
5858 // keep the higher-numbered entry so that we can properly write it out to
5859 // the AST file.
5860 TypeIdx &StoredIdx = TypeIdxs[T];
5861 if (Idx.getIndex() >= StoredIdx.getIndex())
5862 StoredIdx = Idx;
5865 void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
5866 // Always keep the highest ID. See \p TypeRead() for more information.
5867 SelectorID &StoredID = SelectorIDs[S];
5868 if (ID > StoredID)
5869 StoredID = ID;
5872 void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
5873 MacroDefinitionRecord *MD) {
5874 assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
5875 MacroDefinitions[MD] = ID;
5878 void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
5879 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
5880 SubmoduleIDs[Mod] = ID;
5883 void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
5884 if (Chain && Chain->isProcessingUpdateRecords()) return;
5885 assert(D->isCompleteDefinition());
5886 assert(!WritingAST && "Already writing the AST!");
5887 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
5888 // We are interested when a PCH decl is modified.
5889 if (RD->isFromASTFile()) {
5890 // A forward reference was mutated into a definition. Rewrite it.
5891 // FIXME: This happens during template instantiation, should we
5892 // have created a new definition decl instead ?
5893 assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
5894 "completed a tag from another module but not by instantiation?");
5895 DeclUpdates[RD].push_back(
5896 DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION));
5901 static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) {
5902 if (D->isFromASTFile())
5903 return true;
5905 // The predefined __va_list_tag struct is imported if we imported any decls.
5906 // FIXME: This is a gross hack.
5907 return D == D->getASTContext().getVaListTagDecl();
5910 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
5911 if (Chain && Chain->isProcessingUpdateRecords()) return;
5912 assert(DC->isLookupContext() &&
5913 "Should not add lookup results to non-lookup contexts!");
5915 // TU is handled elsewhere.
5916 if (isa<TranslationUnitDecl>(DC))
5917 return;
5919 // Namespaces are handled elsewhere, except for template instantiations of
5920 // FunctionTemplateDecls in namespaces. We are interested in cases where the
5921 // local instantiations are added to an imported context. Only happens when
5922 // adding ADL lookup candidates, for example templated friends.
5923 if (isa<NamespaceDecl>(DC) && D->getFriendObjectKind() == Decl::FOK_None &&
5924 !isa<FunctionTemplateDecl>(D))
5925 return;
5927 // We're only interested in cases where a local declaration is added to an
5928 // imported context.
5929 if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC)))
5930 return;
5932 assert(DC == DC->getPrimaryContext() && "added to non-primary context");
5933 assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
5934 assert(!WritingAST && "Already writing the AST!");
5935 if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) {
5936 // We're adding a visible declaration to a predefined decl context. Ensure
5937 // that we write out all of its lookup results so we don't get a nasty
5938 // surprise when we try to emit its lookup table.
5939 llvm::append_range(DeclsToEmitEvenIfUnreferenced, DC->decls());
5941 DeclsToEmitEvenIfUnreferenced.push_back(D);
5944 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
5945 if (Chain && Chain->isProcessingUpdateRecords()) return;
5946 assert(D->isImplicit());
5948 // We're only interested in cases where a local declaration is added to an
5949 // imported context.
5950 if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD))
5951 return;
5953 if (!isa<CXXMethodDecl>(D))
5954 return;
5956 // A decl coming from PCH was modified.
5957 assert(RD->isCompleteDefinition());
5958 assert(!WritingAST && "Already writing the AST!");
5959 DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
5962 void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
5963 if (Chain && Chain->isProcessingUpdateRecords()) return;
5964 assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
5965 if (!Chain) return;
5966 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
5967 // If we don't already know the exception specification for this redecl
5968 // chain, add an update record for it.
5969 if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D)
5970 ->getType()
5971 ->castAs<FunctionProtoType>()
5972 ->getExceptionSpecType()))
5973 DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
5977 void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
5978 if (Chain && Chain->isProcessingUpdateRecords()) return;
5979 assert(!WritingAST && "Already writing the AST!");
5980 if (!Chain) return;
5981 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
5982 DeclUpdates[D].push_back(
5983 DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
5987 void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
5988 const FunctionDecl *Delete,
5989 Expr *ThisArg) {
5990 if (Chain && Chain->isProcessingUpdateRecords()) return;
5991 assert(!WritingAST && "Already writing the AST!");
5992 assert(Delete && "Not given an operator delete");
5993 if (!Chain) return;
5994 Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
5995 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete));
5999 void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
6000 if (Chain && Chain->isProcessingUpdateRecords()) return;
6001 assert(!WritingAST && "Already writing the AST!");
6002 if (!D->isFromASTFile())
6003 return; // Declaration not imported from PCH.
6005 // Implicit function decl from a PCH was defined.
6006 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
6009 void ASTWriter::VariableDefinitionInstantiated(const VarDecl *D) {
6010 if (Chain && Chain->isProcessingUpdateRecords()) return;
6011 assert(!WritingAST && "Already writing the AST!");
6012 if (!D->isFromASTFile())
6013 return;
6015 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_VAR_DEFINITION));
6018 void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
6019 if (Chain && Chain->isProcessingUpdateRecords()) return;
6020 assert(!WritingAST && "Already writing the AST!");
6021 if (!D->isFromASTFile())
6022 return;
6024 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
6027 void ASTWriter::InstantiationRequested(const ValueDecl *D) {
6028 if (Chain && Chain->isProcessingUpdateRecords()) return;
6029 assert(!WritingAST && "Already writing the AST!");
6030 if (!D->isFromASTFile())
6031 return;
6033 // Since the actual instantiation is delayed, this really means that we need
6034 // to update the instantiation location.
6035 SourceLocation POI;
6036 if (auto *VD = dyn_cast<VarDecl>(D))
6037 POI = VD->getPointOfInstantiation();
6038 else
6039 POI = cast<FunctionDecl>(D)->getPointOfInstantiation();
6040 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_POINT_OF_INSTANTIATION, POI));
6043 void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) {
6044 if (Chain && Chain->isProcessingUpdateRecords()) return;
6045 assert(!WritingAST && "Already writing the AST!");
6046 if (!D->isFromASTFile())
6047 return;
6049 DeclUpdates[D].push_back(
6050 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, D));
6053 void ASTWriter::DefaultMemberInitializerInstantiated(const FieldDecl *D) {
6054 assert(!WritingAST && "Already writing the AST!");
6055 if (!D->isFromASTFile())
6056 return;
6058 DeclUpdates[D].push_back(
6059 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER, D));
6062 void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
6063 const ObjCInterfaceDecl *IFD) {
6064 if (Chain && Chain->isProcessingUpdateRecords()) return;
6065 assert(!WritingAST && "Already writing the AST!");
6066 if (!IFD->isFromASTFile())
6067 return; // Declaration not imported from PCH.
6069 assert(IFD->getDefinition() && "Category on a class without a definition?");
6070 ObjCClassesWithCategories.insert(
6071 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
6074 void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
6075 if (Chain && Chain->isProcessingUpdateRecords()) return;
6076 assert(!WritingAST && "Already writing the AST!");
6078 // If there is *any* declaration of the entity that's not from an AST file,
6079 // we can skip writing the update record. We make sure that isUsed() triggers
6080 // completion of the redeclaration chain of the entity.
6081 for (auto Prev = D->getMostRecentDecl(); Prev; Prev = Prev->getPreviousDecl())
6082 if (IsLocalDecl(Prev))
6083 return;
6085 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));
6088 void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {
6089 if (Chain && Chain->isProcessingUpdateRecords()) return;
6090 assert(!WritingAST && "Already writing the AST!");
6091 if (!D->isFromASTFile())
6092 return;
6094 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE));
6097 void ASTWriter::DeclarationMarkedOpenMPAllocate(const Decl *D, const Attr *A) {
6098 if (Chain && Chain->isProcessingUpdateRecords()) return;
6099 assert(!WritingAST && "Already writing the AST!");
6100 if (!D->isFromASTFile())
6101 return;
6103 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_ALLOCATE, A));
6106 void ASTWriter::DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
6107 const Attr *Attr) {
6108 if (Chain && Chain->isProcessingUpdateRecords()) return;
6109 assert(!WritingAST && "Already writing the AST!");
6110 if (!D->isFromASTFile())
6111 return;
6113 DeclUpdates[D].push_back(
6114 DeclUpdate(UPD_DECL_MARKED_OPENMP_DECLARETARGET, Attr));
6117 void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {
6118 if (Chain && Chain->isProcessingUpdateRecords()) return;
6119 assert(!WritingAST && "Already writing the AST!");
6120 assert(!D->isUnconditionallyVisible() && "expected a hidden declaration");
6121 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M));
6124 void ASTWriter::AddedAttributeToRecord(const Attr *Attr,
6125 const RecordDecl *Record) {
6126 if (Chain && Chain->isProcessingUpdateRecords()) return;
6127 assert(!WritingAST && "Already writing the AST!");
6128 if (!Record->isFromASTFile())
6129 return;
6130 DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr));
6133 void ASTWriter::AddedCXXTemplateSpecialization(
6134 const ClassTemplateDecl *TD, const ClassTemplateSpecializationDecl *D) {
6135 assert(!WritingAST && "Already writing the AST!");
6137 if (!TD->getFirstDecl()->isFromASTFile())
6138 return;
6139 if (Chain && Chain->isProcessingUpdateRecords())
6140 return;
6142 DeclsToEmitEvenIfUnreferenced.push_back(D);
6145 void ASTWriter::AddedCXXTemplateSpecialization(
6146 const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) {
6147 assert(!WritingAST && "Already writing the AST!");
6149 if (!TD->getFirstDecl()->isFromASTFile())
6150 return;
6151 if (Chain && Chain->isProcessingUpdateRecords())
6152 return;
6154 DeclsToEmitEvenIfUnreferenced.push_back(D);
6157 void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
6158 const FunctionDecl *D) {
6159 assert(!WritingAST && "Already writing the AST!");
6161 if (!TD->getFirstDecl()->isFromASTFile())
6162 return;
6163 if (Chain && Chain->isProcessingUpdateRecords())
6164 return;
6166 DeclsToEmitEvenIfUnreferenced.push_back(D);
6169 //===----------------------------------------------------------------------===//
6170 //// OMPClause Serialization
6171 ////===----------------------------------------------------------------------===//
6173 namespace {
6175 class OMPClauseWriter : public OMPClauseVisitor<OMPClauseWriter> {
6176 ASTRecordWriter &Record;
6178 public:
6179 OMPClauseWriter(ASTRecordWriter &Record) : Record(Record) {}
6180 #define GEN_CLANG_CLAUSE_CLASS
6181 #define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *S);
6182 #include "llvm/Frontend/OpenMP/OMP.inc"
6183 void writeClause(OMPClause *C);
6184 void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C);
6185 void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C);
6190 void ASTRecordWriter::writeOMPClause(OMPClause *C) {
6191 OMPClauseWriter(*this).writeClause(C);
6194 void OMPClauseWriter::writeClause(OMPClause *C) {
6195 Record.push_back(unsigned(C->getClauseKind()));
6196 Visit(C);
6197 Record.AddSourceLocation(C->getBeginLoc());
6198 Record.AddSourceLocation(C->getEndLoc());
6201 void OMPClauseWriter::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
6202 Record.push_back(uint64_t(C->getCaptureRegion()));
6203 Record.AddStmt(C->getPreInitStmt());
6206 void OMPClauseWriter::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
6207 VisitOMPClauseWithPreInit(C);
6208 Record.AddStmt(C->getPostUpdateExpr());
6211 void OMPClauseWriter::VisitOMPIfClause(OMPIfClause *C) {
6212 VisitOMPClauseWithPreInit(C);
6213 Record.push_back(uint64_t(C->getNameModifier()));
6214 Record.AddSourceLocation(C->getNameModifierLoc());
6215 Record.AddSourceLocation(C->getColonLoc());
6216 Record.AddStmt(C->getCondition());
6217 Record.AddSourceLocation(C->getLParenLoc());
6220 void OMPClauseWriter::VisitOMPFinalClause(OMPFinalClause *C) {
6221 VisitOMPClauseWithPreInit(C);
6222 Record.AddStmt(C->getCondition());
6223 Record.AddSourceLocation(C->getLParenLoc());
6226 void OMPClauseWriter::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
6227 VisitOMPClauseWithPreInit(C);
6228 Record.AddStmt(C->getNumThreads());
6229 Record.AddSourceLocation(C->getLParenLoc());
6232 void OMPClauseWriter::VisitOMPSafelenClause(OMPSafelenClause *C) {
6233 Record.AddStmt(C->getSafelen());
6234 Record.AddSourceLocation(C->getLParenLoc());
6237 void OMPClauseWriter::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
6238 Record.AddStmt(C->getSimdlen());
6239 Record.AddSourceLocation(C->getLParenLoc());
6242 void OMPClauseWriter::VisitOMPSizesClause(OMPSizesClause *C) {
6243 Record.push_back(C->getNumSizes());
6244 for (Expr *Size : C->getSizesRefs())
6245 Record.AddStmt(Size);
6246 Record.AddSourceLocation(C->getLParenLoc());
6249 void OMPClauseWriter::VisitOMPFullClause(OMPFullClause *C) {}
6251 void OMPClauseWriter::VisitOMPPartialClause(OMPPartialClause *C) {
6252 Record.AddStmt(C->getFactor());
6253 Record.AddSourceLocation(C->getLParenLoc());
6256 void OMPClauseWriter::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
6257 Record.AddStmt(C->getAllocator());
6258 Record.AddSourceLocation(C->getLParenLoc());
6261 void OMPClauseWriter::VisitOMPCollapseClause(OMPCollapseClause *C) {
6262 Record.AddStmt(C->getNumForLoops());
6263 Record.AddSourceLocation(C->getLParenLoc());
6266 void OMPClauseWriter::VisitOMPDetachClause(OMPDetachClause *C) {
6267 Record.AddStmt(C->getEventHandler());
6268 Record.AddSourceLocation(C->getLParenLoc());
6271 void OMPClauseWriter::VisitOMPDefaultClause(OMPDefaultClause *C) {
6272 Record.push_back(unsigned(C->getDefaultKind()));
6273 Record.AddSourceLocation(C->getLParenLoc());
6274 Record.AddSourceLocation(C->getDefaultKindKwLoc());
6277 void OMPClauseWriter::VisitOMPProcBindClause(OMPProcBindClause *C) {
6278 Record.push_back(unsigned(C->getProcBindKind()));
6279 Record.AddSourceLocation(C->getLParenLoc());
6280 Record.AddSourceLocation(C->getProcBindKindKwLoc());
6283 void OMPClauseWriter::VisitOMPScheduleClause(OMPScheduleClause *C) {
6284 VisitOMPClauseWithPreInit(C);
6285 Record.push_back(C->getScheduleKind());
6286 Record.push_back(C->getFirstScheduleModifier());
6287 Record.push_back(C->getSecondScheduleModifier());
6288 Record.AddStmt(C->getChunkSize());
6289 Record.AddSourceLocation(C->getLParenLoc());
6290 Record.AddSourceLocation(C->getFirstScheduleModifierLoc());
6291 Record.AddSourceLocation(C->getSecondScheduleModifierLoc());
6292 Record.AddSourceLocation(C->getScheduleKindLoc());
6293 Record.AddSourceLocation(C->getCommaLoc());
6296 void OMPClauseWriter::VisitOMPOrderedClause(OMPOrderedClause *C) {
6297 Record.push_back(C->getLoopNumIterations().size());
6298 Record.AddStmt(C->getNumForLoops());
6299 for (Expr *NumIter : C->getLoopNumIterations())
6300 Record.AddStmt(NumIter);
6301 for (unsigned I = 0, E = C->getLoopNumIterations().size(); I <E; ++I)
6302 Record.AddStmt(C->getLoopCounter(I));
6303 Record.AddSourceLocation(C->getLParenLoc());
6306 void OMPClauseWriter::VisitOMPNowaitClause(OMPNowaitClause *) {}
6308 void OMPClauseWriter::VisitOMPUntiedClause(OMPUntiedClause *) {}
6310 void OMPClauseWriter::VisitOMPMergeableClause(OMPMergeableClause *) {}
6312 void OMPClauseWriter::VisitOMPReadClause(OMPReadClause *) {}
6314 void OMPClauseWriter::VisitOMPWriteClause(OMPWriteClause *) {}
6316 void OMPClauseWriter::VisitOMPUpdateClause(OMPUpdateClause *C) {
6317 Record.push_back(C->isExtended() ? 1 : 0);
6318 if (C->isExtended()) {
6319 Record.AddSourceLocation(C->getLParenLoc());
6320 Record.AddSourceLocation(C->getArgumentLoc());
6321 Record.writeEnum(C->getDependencyKind());
6325 void OMPClauseWriter::VisitOMPCaptureClause(OMPCaptureClause *) {}
6327 void OMPClauseWriter::VisitOMPCompareClause(OMPCompareClause *) {}
6329 void OMPClauseWriter::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
6331 void OMPClauseWriter::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
6333 void OMPClauseWriter::VisitOMPAcquireClause(OMPAcquireClause *) {}
6335 void OMPClauseWriter::VisitOMPReleaseClause(OMPReleaseClause *) {}
6337 void OMPClauseWriter::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
6339 void OMPClauseWriter::VisitOMPThreadsClause(OMPThreadsClause *) {}
6341 void OMPClauseWriter::VisitOMPSIMDClause(OMPSIMDClause *) {}
6343 void OMPClauseWriter::VisitOMPNogroupClause(OMPNogroupClause *) {}
6345 void OMPClauseWriter::VisitOMPInitClause(OMPInitClause *C) {
6346 Record.push_back(C->varlist_size());
6347 for (Expr *VE : C->varlists())
6348 Record.AddStmt(VE);
6349 Record.writeBool(C->getIsTarget());
6350 Record.writeBool(C->getIsTargetSync());
6351 Record.AddSourceLocation(C->getLParenLoc());
6352 Record.AddSourceLocation(C->getVarLoc());
6355 void OMPClauseWriter::VisitOMPUseClause(OMPUseClause *C) {
6356 Record.AddStmt(C->getInteropVar());
6357 Record.AddSourceLocation(C->getLParenLoc());
6358 Record.AddSourceLocation(C->getVarLoc());
6361 void OMPClauseWriter::VisitOMPDestroyClause(OMPDestroyClause *C) {
6362 Record.AddStmt(C->getInteropVar());
6363 Record.AddSourceLocation(C->getLParenLoc());
6364 Record.AddSourceLocation(C->getVarLoc());
6367 void OMPClauseWriter::VisitOMPNovariantsClause(OMPNovariantsClause *C) {
6368 VisitOMPClauseWithPreInit(C);
6369 Record.AddStmt(C->getCondition());
6370 Record.AddSourceLocation(C->getLParenLoc());
6373 void OMPClauseWriter::VisitOMPNocontextClause(OMPNocontextClause *C) {
6374 VisitOMPClauseWithPreInit(C);
6375 Record.AddStmt(C->getCondition());
6376 Record.AddSourceLocation(C->getLParenLoc());
6379 void OMPClauseWriter::VisitOMPFilterClause(OMPFilterClause *C) {
6380 VisitOMPClauseWithPreInit(C);
6381 Record.AddStmt(C->getThreadID());
6382 Record.AddSourceLocation(C->getLParenLoc());
6385 void OMPClauseWriter::VisitOMPAlignClause(OMPAlignClause *C) {
6386 Record.AddStmt(C->getAlignment());
6387 Record.AddSourceLocation(C->getLParenLoc());
6390 void OMPClauseWriter::VisitOMPPrivateClause(OMPPrivateClause *C) {
6391 Record.push_back(C->varlist_size());
6392 Record.AddSourceLocation(C->getLParenLoc());
6393 for (auto *VE : C->varlists()) {
6394 Record.AddStmt(VE);
6396 for (auto *VE : C->private_copies()) {
6397 Record.AddStmt(VE);
6401 void OMPClauseWriter::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
6402 Record.push_back(C->varlist_size());
6403 VisitOMPClauseWithPreInit(C);
6404 Record.AddSourceLocation(C->getLParenLoc());
6405 for (auto *VE : C->varlists()) {
6406 Record.AddStmt(VE);
6408 for (auto *VE : C->private_copies()) {
6409 Record.AddStmt(VE);
6411 for (auto *VE : C->inits()) {
6412 Record.AddStmt(VE);
6416 void OMPClauseWriter::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
6417 Record.push_back(C->varlist_size());
6418 VisitOMPClauseWithPostUpdate(C);
6419 Record.AddSourceLocation(C->getLParenLoc());
6420 Record.writeEnum(C->getKind());
6421 Record.AddSourceLocation(C->getKindLoc());
6422 Record.AddSourceLocation(C->getColonLoc());
6423 for (auto *VE : C->varlists())
6424 Record.AddStmt(VE);
6425 for (auto *E : C->private_copies())
6426 Record.AddStmt(E);
6427 for (auto *E : C->source_exprs())
6428 Record.AddStmt(E);
6429 for (auto *E : C->destination_exprs())
6430 Record.AddStmt(E);
6431 for (auto *E : C->assignment_ops())
6432 Record.AddStmt(E);
6435 void OMPClauseWriter::VisitOMPSharedClause(OMPSharedClause *C) {
6436 Record.push_back(C->varlist_size());
6437 Record.AddSourceLocation(C->getLParenLoc());
6438 for (auto *VE : C->varlists())
6439 Record.AddStmt(VE);
6442 void OMPClauseWriter::VisitOMPReductionClause(OMPReductionClause *C) {
6443 Record.push_back(C->varlist_size());
6444 Record.writeEnum(C->getModifier());
6445 VisitOMPClauseWithPostUpdate(C);
6446 Record.AddSourceLocation(C->getLParenLoc());
6447 Record.AddSourceLocation(C->getModifierLoc());
6448 Record.AddSourceLocation(C->getColonLoc());
6449 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
6450 Record.AddDeclarationNameInfo(C->getNameInfo());
6451 for (auto *VE : C->varlists())
6452 Record.AddStmt(VE);
6453 for (auto *VE : C->privates())
6454 Record.AddStmt(VE);
6455 for (auto *E : C->lhs_exprs())
6456 Record.AddStmt(E);
6457 for (auto *E : C->rhs_exprs())
6458 Record.AddStmt(E);
6459 for (auto *E : C->reduction_ops())
6460 Record.AddStmt(E);
6461 if (C->getModifier() == clang::OMPC_REDUCTION_inscan) {
6462 for (auto *E : C->copy_ops())
6463 Record.AddStmt(E);
6464 for (auto *E : C->copy_array_temps())
6465 Record.AddStmt(E);
6466 for (auto *E : C->copy_array_elems())
6467 Record.AddStmt(E);
6471 void OMPClauseWriter::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
6472 Record.push_back(C->varlist_size());
6473 VisitOMPClauseWithPostUpdate(C);
6474 Record.AddSourceLocation(C->getLParenLoc());
6475 Record.AddSourceLocation(C->getColonLoc());
6476 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
6477 Record.AddDeclarationNameInfo(C->getNameInfo());
6478 for (auto *VE : C->varlists())
6479 Record.AddStmt(VE);
6480 for (auto *VE : C->privates())
6481 Record.AddStmt(VE);
6482 for (auto *E : C->lhs_exprs())
6483 Record.AddStmt(E);
6484 for (auto *E : C->rhs_exprs())
6485 Record.AddStmt(E);
6486 for (auto *E : C->reduction_ops())
6487 Record.AddStmt(E);
6490 void OMPClauseWriter::VisitOMPInReductionClause(OMPInReductionClause *C) {
6491 Record.push_back(C->varlist_size());
6492 VisitOMPClauseWithPostUpdate(C);
6493 Record.AddSourceLocation(C->getLParenLoc());
6494 Record.AddSourceLocation(C->getColonLoc());
6495 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
6496 Record.AddDeclarationNameInfo(C->getNameInfo());
6497 for (auto *VE : C->varlists())
6498 Record.AddStmt(VE);
6499 for (auto *VE : C->privates())
6500 Record.AddStmt(VE);
6501 for (auto *E : C->lhs_exprs())
6502 Record.AddStmt(E);
6503 for (auto *E : C->rhs_exprs())
6504 Record.AddStmt(E);
6505 for (auto *E : C->reduction_ops())
6506 Record.AddStmt(E);
6507 for (auto *E : C->taskgroup_descriptors())
6508 Record.AddStmt(E);
6511 void OMPClauseWriter::VisitOMPLinearClause(OMPLinearClause *C) {
6512 Record.push_back(C->varlist_size());
6513 VisitOMPClauseWithPostUpdate(C);
6514 Record.AddSourceLocation(C->getLParenLoc());
6515 Record.AddSourceLocation(C->getColonLoc());
6516 Record.push_back(C->getModifier());
6517 Record.AddSourceLocation(C->getModifierLoc());
6518 for (auto *VE : C->varlists()) {
6519 Record.AddStmt(VE);
6521 for (auto *VE : C->privates()) {
6522 Record.AddStmt(VE);
6524 for (auto *VE : C->inits()) {
6525 Record.AddStmt(VE);
6527 for (auto *VE : C->updates()) {
6528 Record.AddStmt(VE);
6530 for (auto *VE : C->finals()) {
6531 Record.AddStmt(VE);
6533 Record.AddStmt(C->getStep());
6534 Record.AddStmt(C->getCalcStep());
6535 for (auto *VE : C->used_expressions())
6536 Record.AddStmt(VE);
6539 void OMPClauseWriter::VisitOMPAlignedClause(OMPAlignedClause *C) {
6540 Record.push_back(C->varlist_size());
6541 Record.AddSourceLocation(C->getLParenLoc());
6542 Record.AddSourceLocation(C->getColonLoc());
6543 for (auto *VE : C->varlists())
6544 Record.AddStmt(VE);
6545 Record.AddStmt(C->getAlignment());
6548 void OMPClauseWriter::VisitOMPCopyinClause(OMPCopyinClause *C) {
6549 Record.push_back(C->varlist_size());
6550 Record.AddSourceLocation(C->getLParenLoc());
6551 for (auto *VE : C->varlists())
6552 Record.AddStmt(VE);
6553 for (auto *E : C->source_exprs())
6554 Record.AddStmt(E);
6555 for (auto *E : C->destination_exprs())
6556 Record.AddStmt(E);
6557 for (auto *E : C->assignment_ops())
6558 Record.AddStmt(E);
6561 void OMPClauseWriter::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
6562 Record.push_back(C->varlist_size());
6563 Record.AddSourceLocation(C->getLParenLoc());
6564 for (auto *VE : C->varlists())
6565 Record.AddStmt(VE);
6566 for (auto *E : C->source_exprs())
6567 Record.AddStmt(E);
6568 for (auto *E : C->destination_exprs())
6569 Record.AddStmt(E);
6570 for (auto *E : C->assignment_ops())
6571 Record.AddStmt(E);
6574 void OMPClauseWriter::VisitOMPFlushClause(OMPFlushClause *C) {
6575 Record.push_back(C->varlist_size());
6576 Record.AddSourceLocation(C->getLParenLoc());
6577 for (auto *VE : C->varlists())
6578 Record.AddStmt(VE);
6581 void OMPClauseWriter::VisitOMPDepobjClause(OMPDepobjClause *C) {
6582 Record.AddStmt(C->getDepobj());
6583 Record.AddSourceLocation(C->getLParenLoc());
6586 void OMPClauseWriter::VisitOMPDependClause(OMPDependClause *C) {
6587 Record.push_back(C->varlist_size());
6588 Record.push_back(C->getNumLoops());
6589 Record.AddSourceLocation(C->getLParenLoc());
6590 Record.AddStmt(C->getModifier());
6591 Record.push_back(C->getDependencyKind());
6592 Record.AddSourceLocation(C->getDependencyLoc());
6593 Record.AddSourceLocation(C->getColonLoc());
6594 Record.AddSourceLocation(C->getOmpAllMemoryLoc());
6595 for (auto *VE : C->varlists())
6596 Record.AddStmt(VE);
6597 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
6598 Record.AddStmt(C->getLoopData(I));
6601 void OMPClauseWriter::VisitOMPDeviceClause(OMPDeviceClause *C) {
6602 VisitOMPClauseWithPreInit(C);
6603 Record.writeEnum(C->getModifier());
6604 Record.AddStmt(C->getDevice());
6605 Record.AddSourceLocation(C->getModifierLoc());
6606 Record.AddSourceLocation(C->getLParenLoc());
6609 void OMPClauseWriter::VisitOMPMapClause(OMPMapClause *C) {
6610 Record.push_back(C->varlist_size());
6611 Record.push_back(C->getUniqueDeclarationsNum());
6612 Record.push_back(C->getTotalComponentListNum());
6613 Record.push_back(C->getTotalComponentsNum());
6614 Record.AddSourceLocation(C->getLParenLoc());
6615 for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
6616 Record.push_back(C->getMapTypeModifier(I));
6617 Record.AddSourceLocation(C->getMapTypeModifierLoc(I));
6619 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
6620 Record.AddDeclarationNameInfo(C->getMapperIdInfo());
6621 Record.push_back(C->getMapType());
6622 Record.AddSourceLocation(C->getMapLoc());
6623 Record.AddSourceLocation(C->getColonLoc());
6624 for (auto *E : C->varlists())
6625 Record.AddStmt(E);
6626 for (auto *E : C->mapperlists())
6627 Record.AddStmt(E);
6628 for (auto *D : C->all_decls())
6629 Record.AddDeclRef(D);
6630 for (auto N : C->all_num_lists())
6631 Record.push_back(N);
6632 for (auto N : C->all_lists_sizes())
6633 Record.push_back(N);
6634 for (auto &M : C->all_components()) {
6635 Record.AddStmt(M.getAssociatedExpression());
6636 Record.AddDeclRef(M.getAssociatedDeclaration());
6640 void OMPClauseWriter::VisitOMPAllocateClause(OMPAllocateClause *C) {
6641 Record.push_back(C->varlist_size());
6642 Record.AddSourceLocation(C->getLParenLoc());
6643 Record.AddSourceLocation(C->getColonLoc());
6644 Record.AddStmt(C->getAllocator());
6645 for (auto *VE : C->varlists())
6646 Record.AddStmt(VE);
6649 void OMPClauseWriter::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
6650 VisitOMPClauseWithPreInit(C);
6651 Record.AddStmt(C->getNumTeams());
6652 Record.AddSourceLocation(C->getLParenLoc());
6655 void OMPClauseWriter::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
6656 VisitOMPClauseWithPreInit(C);
6657 Record.AddStmt(C->getThreadLimit());
6658 Record.AddSourceLocation(C->getLParenLoc());
6661 void OMPClauseWriter::VisitOMPPriorityClause(OMPPriorityClause *C) {
6662 VisitOMPClauseWithPreInit(C);
6663 Record.AddStmt(C->getPriority());
6664 Record.AddSourceLocation(C->getLParenLoc());
6667 void OMPClauseWriter::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
6668 VisitOMPClauseWithPreInit(C);
6669 Record.AddStmt(C->getGrainsize());
6670 Record.AddSourceLocation(C->getLParenLoc());
6673 void OMPClauseWriter::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
6674 VisitOMPClauseWithPreInit(C);
6675 Record.AddStmt(C->getNumTasks());
6676 Record.AddSourceLocation(C->getLParenLoc());
6679 void OMPClauseWriter::VisitOMPHintClause(OMPHintClause *C) {
6680 Record.AddStmt(C->getHint());
6681 Record.AddSourceLocation(C->getLParenLoc());
6684 void OMPClauseWriter::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
6685 VisitOMPClauseWithPreInit(C);
6686 Record.push_back(C->getDistScheduleKind());
6687 Record.AddStmt(C->getChunkSize());
6688 Record.AddSourceLocation(C->getLParenLoc());
6689 Record.AddSourceLocation(C->getDistScheduleKindLoc());
6690 Record.AddSourceLocation(C->getCommaLoc());
6693 void OMPClauseWriter::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
6694 Record.push_back(C->getDefaultmapKind());
6695 Record.push_back(C->getDefaultmapModifier());
6696 Record.AddSourceLocation(C->getLParenLoc());
6697 Record.AddSourceLocation(C->getDefaultmapModifierLoc());
6698 Record.AddSourceLocation(C->getDefaultmapKindLoc());
6701 void OMPClauseWriter::VisitOMPToClause(OMPToClause *C) {
6702 Record.push_back(C->varlist_size());
6703 Record.push_back(C->getUniqueDeclarationsNum());
6704 Record.push_back(C->getTotalComponentListNum());
6705 Record.push_back(C->getTotalComponentsNum());
6706 Record.AddSourceLocation(C->getLParenLoc());
6707 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
6708 Record.push_back(C->getMotionModifier(I));
6709 Record.AddSourceLocation(C->getMotionModifierLoc(I));
6711 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
6712 Record.AddDeclarationNameInfo(C->getMapperIdInfo());
6713 Record.AddSourceLocation(C->getColonLoc());
6714 for (auto *E : C->varlists())
6715 Record.AddStmt(E);
6716 for (auto *E : C->mapperlists())
6717 Record.AddStmt(E);
6718 for (auto *D : C->all_decls())
6719 Record.AddDeclRef(D);
6720 for (auto N : C->all_num_lists())
6721 Record.push_back(N);
6722 for (auto N : C->all_lists_sizes())
6723 Record.push_back(N);
6724 for (auto &M : C->all_components()) {
6725 Record.AddStmt(M.getAssociatedExpression());
6726 Record.writeBool(M.isNonContiguous());
6727 Record.AddDeclRef(M.getAssociatedDeclaration());
6731 void OMPClauseWriter::VisitOMPFromClause(OMPFromClause *C) {
6732 Record.push_back(C->varlist_size());
6733 Record.push_back(C->getUniqueDeclarationsNum());
6734 Record.push_back(C->getTotalComponentListNum());
6735 Record.push_back(C->getTotalComponentsNum());
6736 Record.AddSourceLocation(C->getLParenLoc());
6737 for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
6738 Record.push_back(C->getMotionModifier(I));
6739 Record.AddSourceLocation(C->getMotionModifierLoc(I));
6741 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
6742 Record.AddDeclarationNameInfo(C->getMapperIdInfo());
6743 Record.AddSourceLocation(C->getColonLoc());
6744 for (auto *E : C->varlists())
6745 Record.AddStmt(E);
6746 for (auto *E : C->mapperlists())
6747 Record.AddStmt(E);
6748 for (auto *D : C->all_decls())
6749 Record.AddDeclRef(D);
6750 for (auto N : C->all_num_lists())
6751 Record.push_back(N);
6752 for (auto N : C->all_lists_sizes())
6753 Record.push_back(N);
6754 for (auto &M : C->all_components()) {
6755 Record.AddStmt(M.getAssociatedExpression());
6756 Record.writeBool(M.isNonContiguous());
6757 Record.AddDeclRef(M.getAssociatedDeclaration());
6761 void OMPClauseWriter::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
6762 Record.push_back(C->varlist_size());
6763 Record.push_back(C->getUniqueDeclarationsNum());
6764 Record.push_back(C->getTotalComponentListNum());
6765 Record.push_back(C->getTotalComponentsNum());
6766 Record.AddSourceLocation(C->getLParenLoc());
6767 for (auto *E : C->varlists())
6768 Record.AddStmt(E);
6769 for (auto *VE : C->private_copies())
6770 Record.AddStmt(VE);
6771 for (auto *VE : C->inits())
6772 Record.AddStmt(VE);
6773 for (auto *D : C->all_decls())
6774 Record.AddDeclRef(D);
6775 for (auto N : C->all_num_lists())
6776 Record.push_back(N);
6777 for (auto N : C->all_lists_sizes())
6778 Record.push_back(N);
6779 for (auto &M : C->all_components()) {
6780 Record.AddStmt(M.getAssociatedExpression());
6781 Record.AddDeclRef(M.getAssociatedDeclaration());
6785 void OMPClauseWriter::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
6786 Record.push_back(C->varlist_size());
6787 Record.push_back(C->getUniqueDeclarationsNum());
6788 Record.push_back(C->getTotalComponentListNum());
6789 Record.push_back(C->getTotalComponentsNum());
6790 Record.AddSourceLocation(C->getLParenLoc());
6791 for (auto *E : C->varlists())
6792 Record.AddStmt(E);
6793 for (auto *D : C->all_decls())
6794 Record.AddDeclRef(D);
6795 for (auto N : C->all_num_lists())
6796 Record.push_back(N);
6797 for (auto N : C->all_lists_sizes())
6798 Record.push_back(N);
6799 for (auto &M : C->all_components()) {
6800 Record.AddStmt(M.getAssociatedExpression());
6801 Record.AddDeclRef(M.getAssociatedDeclaration());
6805 void OMPClauseWriter::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
6806 Record.push_back(C->varlist_size());
6807 Record.push_back(C->getUniqueDeclarationsNum());
6808 Record.push_back(C->getTotalComponentListNum());
6809 Record.push_back(C->getTotalComponentsNum());
6810 Record.AddSourceLocation(C->getLParenLoc());
6811 for (auto *E : C->varlists())
6812 Record.AddStmt(E);
6813 for (auto *D : C->all_decls())
6814 Record.AddDeclRef(D);
6815 for (auto N : C->all_num_lists())
6816 Record.push_back(N);
6817 for (auto N : C->all_lists_sizes())
6818 Record.push_back(N);
6819 for (auto &M : C->all_components()) {
6820 Record.AddStmt(M.getAssociatedExpression());
6821 Record.AddDeclRef(M.getAssociatedDeclaration());
6825 void OMPClauseWriter::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) {
6826 Record.push_back(C->varlist_size());
6827 Record.push_back(C->getUniqueDeclarationsNum());
6828 Record.push_back(C->getTotalComponentListNum());
6829 Record.push_back(C->getTotalComponentsNum());
6830 Record.AddSourceLocation(C->getLParenLoc());
6831 for (auto *E : C->varlists())
6832 Record.AddStmt(E);
6833 for (auto *D : C->all_decls())
6834 Record.AddDeclRef(D);
6835 for (auto N : C->all_num_lists())
6836 Record.push_back(N);
6837 for (auto N : C->all_lists_sizes())
6838 Record.push_back(N);
6839 for (auto &M : C->all_components()) {
6840 Record.AddStmt(M.getAssociatedExpression());
6841 Record.AddDeclRef(M.getAssociatedDeclaration());
6845 void OMPClauseWriter::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
6847 void OMPClauseWriter::VisitOMPUnifiedSharedMemoryClause(
6848 OMPUnifiedSharedMemoryClause *) {}
6850 void OMPClauseWriter::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
6852 void
6853 OMPClauseWriter::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
6856 void OMPClauseWriter::VisitOMPAtomicDefaultMemOrderClause(
6857 OMPAtomicDefaultMemOrderClause *C) {
6858 Record.push_back(C->getAtomicDefaultMemOrderKind());
6859 Record.AddSourceLocation(C->getLParenLoc());
6860 Record.AddSourceLocation(C->getAtomicDefaultMemOrderKindKwLoc());
6863 void OMPClauseWriter::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
6864 Record.push_back(C->varlist_size());
6865 Record.AddSourceLocation(C->getLParenLoc());
6866 for (auto *VE : C->varlists())
6867 Record.AddStmt(VE);
6868 for (auto *E : C->private_refs())
6869 Record.AddStmt(E);
6872 void OMPClauseWriter::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
6873 Record.push_back(C->varlist_size());
6874 Record.AddSourceLocation(C->getLParenLoc());
6875 for (auto *VE : C->varlists())
6876 Record.AddStmt(VE);
6879 void OMPClauseWriter::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
6880 Record.push_back(C->varlist_size());
6881 Record.AddSourceLocation(C->getLParenLoc());
6882 for (auto *VE : C->varlists())
6883 Record.AddStmt(VE);
6886 void OMPClauseWriter::VisitOMPOrderClause(OMPOrderClause *C) {
6887 Record.writeEnum(C->getKind());
6888 Record.AddSourceLocation(C->getLParenLoc());
6889 Record.AddSourceLocation(C->getKindKwLoc());
6892 void OMPClauseWriter::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
6893 Record.push_back(C->getNumberOfAllocators());
6894 Record.AddSourceLocation(C->getLParenLoc());
6895 for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) {
6896 OMPUsesAllocatorsClause::Data Data = C->getAllocatorData(I);
6897 Record.AddStmt(Data.Allocator);
6898 Record.AddStmt(Data.AllocatorTraits);
6899 Record.AddSourceLocation(Data.LParenLoc);
6900 Record.AddSourceLocation(Data.RParenLoc);
6904 void OMPClauseWriter::VisitOMPAffinityClause(OMPAffinityClause *C) {
6905 Record.push_back(C->varlist_size());
6906 Record.AddSourceLocation(C->getLParenLoc());
6907 Record.AddStmt(C->getModifier());
6908 Record.AddSourceLocation(C->getColonLoc());
6909 for (Expr *E : C->varlists())
6910 Record.AddStmt(E);
6913 void OMPClauseWriter::VisitOMPBindClause(OMPBindClause *C) {
6914 Record.writeEnum(C->getBindKind());
6915 Record.AddSourceLocation(C->getLParenLoc());
6916 Record.AddSourceLocation(C->getBindKindLoc());
6919 void ASTRecordWriter::writeOMPTraitInfo(const OMPTraitInfo *TI) {
6920 writeUInt32(TI->Sets.size());
6921 for (const auto &Set : TI->Sets) {
6922 writeEnum(Set.Kind);
6923 writeUInt32(Set.Selectors.size());
6924 for (const auto &Selector : Set.Selectors) {
6925 writeEnum(Selector.Kind);
6926 writeBool(Selector.ScoreOrCondition);
6927 if (Selector.ScoreOrCondition)
6928 writeExprRef(Selector.ScoreOrCondition);
6929 writeUInt32(Selector.Properties.size());
6930 for (const auto &Property : Selector.Properties)
6931 writeEnum(Property.Kind);
6936 void ASTRecordWriter::writeOMPChildren(OMPChildren *Data) {
6937 if (!Data)
6938 return;
6939 writeUInt32(Data->getNumClauses());
6940 writeUInt32(Data->getNumChildren());
6941 writeBool(Data->hasAssociatedStmt());
6942 for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I)
6943 writeOMPClause(Data->getClauses()[I]);
6944 if (Data->hasAssociatedStmt())
6945 AddStmt(Data->getAssociatedStmt());
6946 for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)
6947 AddStmt(Data->getChildren()[I]);