33#include "llvm/Config/llvm-config.h"
95 cl::desc(
"Number of metadatas above which we emit an index "
96 "to enable lazy-loading"));
99 cl::desc(
"The threshold (unit M) for flushing LLVM bitcode."));
119 cl::desc(
"Preserve use-list order when writing LLVM bitcode."));
130 VST_BBENTRY_6_ABBREV,
134 CONSTANTS_INTEGER_ABBREV,
135 CONSTANTS_BYTE_ABBREV,
136 CONSTANTS_CE_CAST_Abbrev,
137 CONSTANTS_NULL_Abbrev,
141 FUNCTION_INST_STORE_ABBREV,
142 FUNCTION_INST_UNOP_ABBREV,
143 FUNCTION_INST_UNOP_FLAGS_ABBREV,
144 FUNCTION_INST_BINOP_ABBREV,
145 FUNCTION_INST_BINOP_FLAGS_ABBREV,
146 FUNCTION_INST_CAST_ABBREV,
147 FUNCTION_INST_CAST_FLAGS_ABBREV,
148 FUNCTION_INST_RET_VOID_ABBREV,
149 FUNCTION_INST_RET_VAL_ABBREV,
150 FUNCTION_INST_BR_UNCOND_ABBREV,
151 FUNCTION_INST_BR_COND_ABBREV,
152 FUNCTION_INST_UNREACHABLE_ABBREV,
153 FUNCTION_INST_GEP_ABBREV,
154 FUNCTION_INST_CMP_ABBREV,
155 FUNCTION_INST_CMP_FLAGS_ABBREV,
156 FUNCTION_DEBUG_RECORD_VALUE_ABBREV,
157 FUNCTION_DEBUG_LOC_ABBREV,
158 FUNCTION_DEBUG_LOC_LAYERS_ABBREV,
163class BitcodeWriterBase {
166 BitstreamWriter &Stream;
168 StringTableBuilder &StrtabBuilder;
173 BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
174 : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
177 void writeModuleVersion();
180void BitcodeWriterBase::writeModuleVersion() {
187class ModuleBitcodeWriterBase :
public BitcodeWriterBase {
196 const ModuleSummaryIndex *Index;
201 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
204 unsigned GlobalValueId;
213 ModuleBitcodeWriterBase(
const Module &M, StringTableBuilder &StrtabBuilder,
214 BitstreamWriter &Stream,
215 bool ShouldPreserveUseListOrder,
216 const ModuleSummaryIndex *Index)
217 : BitcodeWriterBase(Stream, StrtabBuilder),
M(
M),
220 : ShouldPreserveUseListOrder),
231 for (
const auto &GUIDSummaryLists :
232 Index->sortedGlobalValueSummariesRange())
234 for (
auto &Summary : GUIDSummaryLists.second.getSummaryList())
240 for (auto &CallEdge : FS->calls())
241 if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())
242 assignValueId(CallEdge.first.getGUID());
248 for (auto &RefEdge : FS->refs())
249 if (!RefEdge.haveGVs() || !RefEdge.getValue())
250 assignValueId(RefEdge.getGUID());
255 void writePerModuleGlobalValueSummary();
256 void writeGUIDList();
259 void writePerModuleFunctionSummaryRecord(
260 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
261 unsigned ValueID,
unsigned FSCallsProfileAbbrev,
unsigned CallsiteAbbrev,
262 unsigned AllocAbbrev,
unsigned ContextIdAbbvId,
const Function &
F,
263 DenseMap<CallStackId, LinearCallStackId> &CallStackPos,
265 void writeModuleLevelReferences(
const GlobalVariable &
V,
266 SmallVector<uint64_t, 64> &NameVals,
267 unsigned FSModRefsAbbrev,
268 unsigned FSModVTableRefsAbbrev);
271 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
275 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
278 assert(VMI != GUIDToValueIdMap.end() &&
279 "GUID does not have assigned value Id");
284 unsigned getValueId(ValueInfo VI) {
285 if (!
VI.haveGVs() || !
VI.getValue())
286 return getValueId(
VI.getGUID());
290 std::map<GlobalValue::GUID, unsigned> &valueIds() {
return GUIDToValueIdMap; }
294class ModuleBitcodeWriter :
public ModuleBitcodeWriterBase {
310 unsigned DILocationLayersAbbrev = 0;
315 ModuleBitcodeWriter(
const Module &M, StringTableBuilder &StrtabBuilder,
316 BitstreamWriter &Stream,
bool ShouldPreserveUseListOrder,
317 const ModuleSummaryIndex *Index,
bool GenerateHash,
319 : ModuleBitcodeWriterBase(
M, StrtabBuilder, Stream,
320 ShouldPreserveUseListOrder,
Index),
321 GenerateHash(GenerateHash), ModHash(ModHash),
322 BitcodeStartBit(Stream.GetCurrentBitNo()) {}
328 uint64_t bitcodeStartBit() {
return BitcodeStartBit; }
330 size_t addToStrtab(StringRef Str);
332 void writeAttributeGroupTable();
333 void writeAttributeTable();
334 void writeTypeTable();
336 void writeValueSymbolTableForwardDecl();
337 void writeModuleInfo();
338 void writeValueAsMetadata(
const ValueAsMetadata *MD,
339 SmallVectorImpl<uint64_t> &Record);
340 void writeMDTuple(
const MDTuple *
N, SmallVectorImpl<uint64_t> &Record,
342 unsigned createDILocationAbbrev(
bool WithIRLayers);
343 void writeDILocation(
const DILocation *
N, SmallVectorImpl<uint64_t> &Record,
345 void writeDILayerLoc(
const DILayerLoc *
N, SmallVectorImpl<uint64_t> &Record,
348 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
349 unsigned createGenericDINodeAbbrev();
351 SmallVectorImpl<uint64_t> &Record,
unsigned &Abbrev);
352 void writeDISubrange(
const DISubrange *
N, SmallVectorImpl<uint64_t> &Record,
355 SmallVectorImpl<uint64_t> &Record,
358 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
362 SmallVectorImpl<uint64_t> &Record,
365 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
367 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
369 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
371 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
373 SmallVectorImpl<uint64_t> &Record,
375 void writeDIFile(
const DIFile *
N, SmallVectorImpl<uint64_t> &Record,
378 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
380 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
382 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
384 SmallVectorImpl<uint64_t> &Record,
387 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
390 void writeDIMacro(
const DIMacro *
N, SmallVectorImpl<uint64_t> &Record,
394 void writeDIArgList(
const DIArgList *
N, SmallVectorImpl<uint64_t> &Record);
395 void writeDIModule(
const DIModule *
N, SmallVectorImpl<uint64_t> &Record,
397 void writeDIAssignID(
const DIAssignID *
N, SmallVectorImpl<uint64_t> &Record,
400 SmallVectorImpl<uint64_t> &Record,
403 SmallVectorImpl<uint64_t> &Record,
406 SmallVectorImpl<uint64_t> &Record,
409 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
411 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
413 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
415 SmallVectorImpl<uint64_t> &Record,
418 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
419 void writeDIProperty(
const DIProperty *
N, SmallVectorImpl<uint64_t> &Record,
422 SmallVectorImpl<uint64_t> &Record,
424 unsigned createNamedMetadataAbbrev();
425 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
426 unsigned createMetadataStringsAbbrev();
428 SmallVectorImpl<uint64_t> &Record);
430 SmallVectorImpl<uint64_t> &Record,
431 std::vector<unsigned> *MDAbbrevs =
nullptr,
432 std::vector<uint64_t> *IndexPos =
nullptr);
433 void writeModuleMetadata();
434 void writeFunctionMetadata(
const Function &
F);
435 void writeFunctionMetadataAttachment(
const Function &
F);
436 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
437 const GlobalObject &GO);
438 void writeModuleMetadataKinds();
439 void writeOperandBundleTags();
440 void writeSyncScopeNames();
441 void writeConstants(
unsigned FirstVal,
unsigned LastVal,
bool isGlobal);
442 void writeModuleConstants();
443 bool pushValueAndType(
const Value *
V,
unsigned InstID,
444 SmallVectorImpl<unsigned> &Vals);
445 bool pushValueOrMetadata(
const Value *
V,
unsigned InstID,
446 SmallVectorImpl<unsigned> &Vals);
447 void writeOperandBundles(
const CallBase &CB,
unsigned InstID);
448 void pushValue(
const Value *
V,
unsigned InstID,
449 SmallVectorImpl<unsigned> &Vals);
450 void pushValueSigned(
const Value *
V,
unsigned InstID,
451 SmallVectorImpl<uint64_t> &Vals);
452 void writeInstruction(
const Instruction &
I,
unsigned InstID,
453 SmallVectorImpl<unsigned> &Vals);
454 void writeFunctionLevelValueSymbolTable(
const ValueSymbolTable &VST);
455 void writeGlobalValueSymbolTable(
456 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
457 void writeUseList(UseListOrder &&Order);
458 void writeUseListBlock(
const Function *
F);
461 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
462 void writeBlockInfo();
463 void writeModuleHash(StringRef View);
466 return unsigned(SSID);
469 unsigned getEncodedAlign(MaybeAlign Alignment) {
return encode(Alignment); }
473class IndexBitcodeWriter :
public BitcodeWriterBase {
475 const ModuleSummaryIndex &
Index;
491 SortedSummariesForIndex;
495 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
499 std::vector<uint64_t> StackIds;
504 DenseMap<unsigned, unsigned> StackIdIndicesToIndex;
507 unsigned GlobalValueId = 0;
511 DenseMap<StringRef, uint64_t> ModuleIdMap;
521 BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
522 const ModuleSummaryIndex &Index,
525 : BitcodeWriterBase(Stream, StrtabBuilder),
Index(
Index),
526 DecSummaries(DecSummaries),
527 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
528 if (ModuleToSummariesForIndex) {
529 for (
const auto &[ModPath, Summaries] : *ModuleToSummariesForIndex)
540 auto RecordStackIdReference = [&](
unsigned StackIdIndex) {
545 StackIdIndicesToIndex.
insert({StackIdIndex, StackIds.size()});
547 StackIds.push_back(
Index.getStackIdAtIndex(StackIdIndex));
554 forEachSummary([&](GVInfo
I,
bool IsAliasee) {
555 GUIDToValueIdMap[
I.first] = ++GlobalValueId;
567 for (
auto &CI :
FS->callsites()) {
578 if (CI.StackIdIndices.empty()) {
579 GUIDToValueIdMap[CI.Callee.getGUID()] = ++GlobalValueId;
582 for (
auto Idx : CI.StackIdIndices)
583 RecordStackIdReference(Idx);
586 for (
auto &AI :
FS->allocs())
587 for (
auto &MIB : AI.MIBs)
588 for (
auto Idx : MIB.StackIdIndices)
589 RecordStackIdReference(Idx);
595 using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
600 template<
typename Functor>
601 void forEachSummary(Functor Callback) {
602 if (ModuleToSummariesForIndex) {
603 for (
auto &[GUID, GVS] : SortedSummariesForIndex) {
609 Callback({AS->getAliaseeGUID(), &AS->getAliasee()},
true);
613 for (
const auto &Summaries :
Index.sortedGlobalValueSummariesRange())
614 for (
auto &Summary : Summaries.second.getSummaryList())
623 template <
typename Functor>
void forEachModule(Functor Callback) {
624 if (ModuleToSummariesForIndex) {
625 for (
const auto &M : *ModuleToSummariesForIndex) {
626 const auto &MPI =
Index.modulePaths().find(
M.first);
627 if (MPI ==
Index.modulePaths().end()) {
631 assert(ModuleToSummariesForIndex->size() == 1);
641 std::vector<StringRef> ModulePaths;
642 for (
auto &[ModPath,
_] :
Index.modulePaths())
643 ModulePaths.push_back(ModPath);
645 for (
auto &ModPath : ModulePaths)
654 void writeModStrings();
655 void writeCombinedGlobalValueSummary();
658 auto VMI = GUIDToValueIdMap.find(ValGUID);
659 if (VMI == GUIDToValueIdMap.end())
664 std::map<GlobalValue::GUID, unsigned> &valueIds() {
return GUIDToValueIdMap; }
699 case Instruction::Add:
701 case Instruction::Sub:
703 case Instruction::Mul:
706 case Instruction::FDiv:
709 case Instruction::FRem:
721 unsigned Encoding = 0;
722 switch (
I.getOperation()) {
795 if (
I.isElementwise())
830 case Attribute::Alignment:
832 case Attribute::AllocAlign:
834 case Attribute::AllocSize:
836 case Attribute::AlwaysInline:
838 case Attribute::Builtin:
840 case Attribute::ByVal:
842 case Attribute::Convergent:
844 case Attribute::InAlloca:
846 case Attribute::Cold:
848 case Attribute::DisableSanitizerInstrumentation:
850 case Attribute::FnRetThunkExtern:
852 case Attribute::Flatten:
856 case Attribute::ElementType:
858 case Attribute::HybridPatchable:
860 case Attribute::InlineHint:
862 case Attribute::InReg:
864 case Attribute::JumpTable:
866 case Attribute::MinSize:
868 case Attribute::AllocatedPointer:
870 case Attribute::AllocKind:
872 case Attribute::Memory:
874 case Attribute::NoFPClass:
876 case Attribute::Naked:
878 case Attribute::Nest:
880 case Attribute::NoAlias:
882 case Attribute::NoBuiltin:
884 case Attribute::NoCallback:
886 case Attribute::NoDivergenceSource:
888 case Attribute::NoDuplicate:
890 case Attribute::NoFree:
892 case Attribute::NoFreeObj:
894 case Attribute::NoImplicitFloat:
896 case Attribute::NoInline:
898 case Attribute::NoRecurse:
900 case Attribute::NoMerge:
902 case Attribute::NonLazyBind:
904 case Attribute::NonNull:
906 case Attribute::Dereferenceable:
908 case Attribute::DereferenceableOrNull:
910 case Attribute::NoRedZone:
912 case Attribute::NoReturn:
914 case Attribute::NoSync:
916 case Attribute::NoCfCheck:
918 case Attribute::NoProfile:
920 case Attribute::SkipProfile:
922 case Attribute::NoUnwind:
924 case Attribute::NoSanitizeBounds:
926 case Attribute::NoSanitizeCoverage:
928 case Attribute::NullPointerIsValid:
930 case Attribute::OptimizeForDebugging:
932 case Attribute::OptForFuzzing:
934 case Attribute::OptimizeForSize:
936 case Attribute::OptimizeNone:
938 case Attribute::ReadNone:
940 case Attribute::ReadOnly:
942 case Attribute::Returned:
944 case Attribute::ReturnsTwice:
946 case Attribute::SExt:
948 case Attribute::Speculatable:
950 case Attribute::StackAlignment:
952 case Attribute::StackProtect:
954 case Attribute::StackProtectReq:
956 case Attribute::StackProtectStrong:
958 case Attribute::SafeStack:
960 case Attribute::ShadowCallStack:
962 case Attribute::StrictFP:
964 case Attribute::StructRet:
966 case Attribute::SanitizeAddress:
968 case Attribute::SanitizeAllocToken:
970 case Attribute::SanitizeHWAddress:
972 case Attribute::SanitizeThread:
974 case Attribute::SanitizeConcurrency:
976 case Attribute::SanitizeType:
978 case Attribute::SanitizeMemory:
980 case Attribute::SanitizeNumericalStability:
982 case Attribute::SanitizeRealtime:
984 case Attribute::SanitizeRealtimeBlocking:
986 case Attribute::SpeculativeLoadHardening:
988 case Attribute::SwiftError:
990 case Attribute::SwiftSelf:
992 case Attribute::SwiftAsync:
994 case Attribute::UWTable:
996 case Attribute::VScaleRange:
998 case Attribute::WillReturn:
1000 case Attribute::WriteOnly:
1002 case Attribute::ZExt:
1004 case Attribute::ImmArg:
1006 case Attribute::SanitizeMemTag:
1008 case Attribute::Preallocated:
1010 case Attribute::NoUndef:
1012 case Attribute::ByRef:
1014 case Attribute::MustProgress:
1016 case Attribute::PresplitCoroutine:
1018 case Attribute::Writable:
1020 case Attribute::CoroDestroyOnlyWhenComplete:
1022 case Attribute::CoroElideSafe:
1024 case Attribute::DeadOnUnwind:
1026 case Attribute::Range:
1028 case Attribute::Initializes:
1030 case Attribute::NoExt:
1032 case Attribute::Captures:
1034 case Attribute::DeadOnReturn:
1036 case Attribute::NoCreateUndefOrPoison:
1038 case Attribute::DenormalFPEnv:
1040 case Attribute::NoOutline:
1042 case Attribute::NoIPA:
1044 case Attribute::LikelyModuleLocal:
1059 if ((int64_t)
V >= 0)
1070 unsigned NumWords =
A.getActiveWords();
1071 const uint64_t *RawData =
A.getRawData();
1072 for (
unsigned i = 0; i < NumWords; i++)
1092void ModuleBitcodeWriter::writeAttributeGroupTable() {
1093 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
1095 if (AttrGrps.empty())
return;
1099 SmallVector<uint64_t, 64>
Record;
1101 unsigned AttrListIndex = Pair.first;
1102 AttributeSet AS = Pair.second;
1104 Record.push_back(AttrListIndex);
1107 if (Attr.isEnumAttribute()) {
1110 }
else if (Attr.isIntAttribute()) {
1112 Attribute::AttrKind
Kind = Attr.getKindAsEnum();
1114 if (Kind == Attribute::Memory) {
1119 Record.push_back(Attr.getValueAsInt());
1121 }
else if (Attr.isStringAttribute()) {
1122 StringRef
Kind = Attr.getKindAsString();
1123 StringRef Val = Attr.getValueAsString();
1132 }
else if (Attr.isTypeAttribute()) {
1133 Type *Ty = Attr.getValueAsType();
1134 Record.push_back(Ty ? 6 : 5);
1138 }
else if (Attr.isConstantRangeAttribute()) {
1144 assert(Attr.isConstantRangeListAttribute());
1150 for (
auto &CR : Val)
1162void ModuleBitcodeWriter::writeAttributeTable() {
1164 if (
Attrs.empty())
return;
1168 SmallVector<uint64_t, 64>
Record;
1169 for (
const AttributeList &AL : Attrs) {
1170 for (
unsigned i :
AL.indexes()) {
1171 AttributeSet AS =
AL.getAttributes(i);
1184void ModuleBitcodeWriter::writeTypeTable() {
1188 SmallVector<uint64_t, 64> TypeVals;
1193 auto Abbv = std::make_shared<BitCodeAbbrev>();
1195 Abbv->Add(BitCodeAbbrevOp(0));
1196 unsigned OpaquePtrAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1199 Abbv = std::make_shared<BitCodeAbbrev>();
1204 unsigned FunctionAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1207 Abbv = std::make_shared<BitCodeAbbrev>();
1212 unsigned StructAnonAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1215 Abbv = std::make_shared<BitCodeAbbrev>();
1219 unsigned StructNameAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1222 Abbv = std::make_shared<BitCodeAbbrev>();
1227 unsigned StructNamedAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1230 Abbv = std::make_shared<BitCodeAbbrev>();
1234 unsigned ArrayAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1242 for (
Type *
T : TypeList) {
1243 int AbbrevToUse = 0;
1246 switch (
T->getTypeID()) {
1256 case Type::MetadataTyID:
1261 case Type::ByteTyID:
1266 case Type::IntegerTyID:
1271 case Type::PointerTyID: {
1278 AbbrevToUse = OpaquePtrAbbrev;
1281 case Type::FunctionTyID: {
1287 for (
unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
1289 AbbrevToUse = FunctionAbbrev;
1292 case Type::StructTyID: {
1297 for (
Type *ET :
ST->elements())
1300 if (
ST->isLiteral()) {
1302 AbbrevToUse = StructAnonAbbrev;
1304 if (
ST->isOpaque()) {
1308 AbbrevToUse = StructNamedAbbrev;
1312 if (!
ST->getName().empty())
1318 case Type::ArrayTyID: {
1322 TypeVals.
push_back(AT->getNumElements());
1324 AbbrevToUse = ArrayAbbrev;
1327 case Type::FixedVectorTyID:
1328 case Type::ScalableVectorTyID: {
1333 TypeVals.
push_back(VT->getElementCount().getKnownMinValue());
1339 case Type::TargetExtTyID: {
1345 for (
Type *InnerTy :
TET->type_params())
1350 case Type::TypedPointerTyID:
1355 Stream.
EmitRecord(Code, TypeVals, AbbrevToUse);
1396 RawFlags |= Flags.ReadNone;
1397 RawFlags |= (Flags.ReadOnly << 1);
1398 RawFlags |= (Flags.NoRecurse << 2);
1399 RawFlags |= (Flags.ReturnDoesNotAlias << 3);
1400 RawFlags |= (Flags.NoInline << 4);
1401 RawFlags |= (Flags.AlwaysInline << 5);
1402 RawFlags |= (Flags.NoUnwind << 6);
1403 RawFlags |= (Flags.MayThrow << 7);
1404 RawFlags |= (Flags.HasUnknownCall << 8);
1405 RawFlags |= (Flags.MustBeUnreachable << 9);
1412 bool ImportAsDecl =
false) {
1415 RawFlags |= Flags.NotEligibleToImport;
1416 RawFlags |= (Flags.Live << 1);
1417 RawFlags |= (Flags.DSOLocal << 2);
1418 RawFlags |= (Flags.CanAutoHide << 3);
1423 RawFlags = (RawFlags << 4) | Flags.Linkage;
1425 RawFlags |= (Flags.Visibility << 8);
1427 unsigned ImportType = Flags.ImportType | ImportAsDecl;
1428 RawFlags |= (ImportType << 10);
1430 RawFlags |= (Flags.NoRenameOnPromotion << 11);
1436 uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) |
1437 (Flags.Constant << 2) | Flags.VCallVisibility << 3;
1481 switch (
C.getSelectionKind()) {
1505size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1508 return StrtabBuilder.
add(Str);
1511void ModuleBitcodeWriter::writeComdats() {
1526void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
1531 auto Abbv = std::make_shared<BitCodeAbbrev>();
1537 unsigned VSTOffsetAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1553 bool isChar6 =
true;
1554 for (
char C : Str) {
1557 if ((
unsigned char)
C & 128)
1566static_assert(
sizeof(GlobalValue::SanitizerMetadata) <=
sizeof(unsigned),
1567 "Sanitizer Metadata is too large for naive serialization.");
1570 return Meta.NoAddress | (
Meta.NoHWAddress << 1) |
1571 (
Meta.Memtag << 2) | (
Meta.IsDynInit << 3);
1577void ModuleBitcodeWriter::writeModuleInfo() {
1579 if (!
M.getTargetTriple().empty())
1581 M.getTargetTriple().str(), 0 );
1582 const std::string &
DL =
M.getDataLayoutStr();
1586 for (
const Module::GlobalAsmFragment &Frag :
M.getModuleInlineAsm()) {
1588 Frag.Props.getAsStrings();
1601 std::map<std::string, unsigned> SectionMap;
1602 std::map<std::string, unsigned> GCMap;
1603 MaybeAlign MaxGVarAlignment;
1604 unsigned MaxGlobalType = 0;
1605 for (
const GlobalVariable &GV :
M.globals()) {
1606 if (MaybeAlign
A = GV.getAlign())
1607 MaxGVarAlignment = !MaxGVarAlignment ? *
A : std::max(*MaxGVarAlignment, *
A);
1608 MaxGlobalType = std::max(MaxGlobalType, VE.
getTypeID(GV.getValueType()));
1609 if (GV.hasSection()) {
1611 unsigned &
Entry = SectionMap[std::string(GV.getSection())];
1615 Entry = SectionMap.size();
1620 if (
F.hasSection()) {
1622 unsigned &
Entry = SectionMap[std::string(
F.getSection())];
1626 Entry = SectionMap.size();
1631 unsigned &
Entry = GCMap[
F.getGC()];
1635 Entry = GCMap.size();
1641 unsigned SimpleGVarAbbrev = 0;
1642 if (!
M.global_empty()) {
1644 auto Abbv = std::make_shared<BitCodeAbbrev>();
1655 if (!MaxGVarAlignment)
1656 Abbv->Add(BitCodeAbbrevOp(0));
1658 unsigned MaxEncAlignment = getEncodedAlign(MaxGVarAlignment);
1662 if (SectionMap.empty())
1663 Abbv->Add(BitCodeAbbrevOp(0));
1668 SimpleGVarAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1682 auto Abbv = std::make_shared<BitCodeAbbrev>();
1685 Abbv->Add(AbbrevOpToUse);
1686 unsigned FilenameAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1688 for (
const auto P :
M.getSourceFileName())
1699 for (
const GlobalVariable &GV :
M.globals()) {
1700 unsigned AbbrevToUse = 0;
1706 Vals.
push_back(addToStrtab(GV.getName()));
1709 Vals.
push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1713 Vals.
push_back(getEncodedAlign(GV.getAlign()));
1714 Vals.
push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]
1716 if (GV.isThreadLocal() ||
1718 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1719 GV.isExternallyInitialized() ||
1721 GV.hasComdat() || GV.hasAttributes() || GV.isDSOLocal() ||
1722 GV.hasPartition() || GV.hasSanitizerMetadata() || GV.getCodeModel()) {
1726 Vals.
push_back(GV.isExternallyInitialized());
1730 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1734 Vals.
push_back(addToStrtab(GV.getPartition()));
1735 Vals.
push_back(GV.getPartition().size());
1738 GV.getSanitizerMetadata())
1742 AbbrevToUse = SimpleGVarAbbrev;
1763 Vals.
push_back(getEncodedAlign(
F.getAlign()));
1764 Vals.
push_back(
F.hasSection() ? SectionMap[std::string(
F.getSection())]
1776 F.hasPersonalityFn() ? (VE.
getValueID(
F.getPersonalityFn()) + 1) : 0);
1780 Vals.
push_back(addToStrtab(
F.getPartition()));
1782 Vals.
push_back(getEncodedAlign(
F.getPreferredAlignment()));
1784 unsigned AbbrevToUse = 0;
1790 for (
const GlobalAlias &
A :
M.aliases()) {
1797 Vals.
push_back(
A.getType()->getAddressSpace());
1805 Vals.
push_back(addToStrtab(
A.getPartition()));
1808 unsigned AbbrevToUse = 0;
1814 for (
const GlobalIFunc &
I :
M.ifuncs()) {
1820 Vals.
push_back(
I.getType()->getAddressSpace());
1825 Vals.
push_back(addToStrtab(
I.getPartition()));
1831 writeValueSymbolTableForwardDecl();
1838 if (OBO->hasNoSignedWrap())
1840 if (OBO->hasNoUnsignedWrap())
1846 if (PDI->isDisjoint())
1849 if (FPMO->hasAllowReassoc())
1851 if (FPMO->hasNoNaNs())
1853 if (FPMO->hasNoInfs())
1855 if (FPMO->hasNoSignedZeros())
1857 if (FPMO->hasAllowReciprocal())
1859 if (FPMO->hasAllowContract())
1861 if (FPMO->hasApproxFunc())
1867 if (NNI->hasNonNeg())
1871 if (NNI->hasNonNeg())
1874 if (TI->hasNoSignedWrap())
1876 if (TI->hasNoUnsignedWrap())
1879 if (
GEP->isInBounds())
1881 if (
GEP->hasNoUnsignedSignedWrap())
1883 if (
GEP->hasNoUnsignedWrap())
1886 if (ICmp->hasSameSign())
1889 if (ASC->hasNonNull())
1896void ModuleBitcodeWriter::writeValueAsMetadata(
1897 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
1906void ModuleBitcodeWriter::writeMDTuple(
const MDTuple *
N,
1907 SmallVectorImpl<uint64_t> &Record,
1909 for (
const MDOperand &MDO :
N->operands()) {
1912 "Unexpected function-local metadata");
1921unsigned ModuleBitcodeWriter::createDILocationAbbrev(
bool WithIRLayers) {
1927 auto Abbv = std::make_shared<BitCodeAbbrev>();
1942void ModuleBitcodeWriter::writeDILocation(
const DILocation *
N,
1943 SmallVectorImpl<uint64_t> &Record,
1946 Abbrev = createDILocationAbbrev(
false);
1948 Record.push_back(
N->isDistinct());
1949 Record.push_back(
N->getLine());
1950 Record.push_back(
N->getColumn());
1953 Record.push_back(
N->isImplicitCode());
1954 Record.push_back(
N->getAtomGroup());
1955 Record.push_back(
N->getAtomRank());
1957 unsigned AbbrevToUse = Abbrev;
1958 if (DILayerLocList *IRLayers =
N->getIRLayers()) {
1959 if (!DILocationLayersAbbrev)
1960 DILocationLayersAbbrev = createDILocationAbbrev(
true);
1961 AbbrevToUse = DILocationLayersAbbrev;
1969void ModuleBitcodeWriter::writeDILayerLoc(
const DILayerLoc *
N,
1970 SmallVectorImpl<uint64_t> &Record,
1972 Record.push_back(
N->isDistinct());
1973 Record.push_back(
N->getLine());
1974 Record.push_back(
N->getColumn());
1981void ModuleBitcodeWriter::writeDILayerLocList(
const DILayerLocList *
N,
1982 SmallVectorImpl<uint64_t> &Record,
1984 Record.push_back(
N->isDistinct());
1985 for (
const MDOperand &
Op :
N->layers())
1991unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1994 auto Abbv = std::make_shared<BitCodeAbbrev>();
2005void ModuleBitcodeWriter::writeGenericDINode(
const GenericDINode *
N,
2006 SmallVectorImpl<uint64_t> &Record,
2009 Abbrev = createGenericDINodeAbbrev();
2011 Record.push_back(
N->isDistinct());
2012 Record.push_back(
N->getTag());
2015 for (
auto &
I :
N->operands())
2022void ModuleBitcodeWriter::writeDISubrange(
const DISubrange *
N,
2023 SmallVectorImpl<uint64_t> &Record,
2036void ModuleBitcodeWriter::writeDIGenericSubrange(
2037 const DIGenericSubrange *
N, SmallVectorImpl<uint64_t> &Record,
2049void ModuleBitcodeWriter::writeDIEnumerator(
const DIEnumerator *
N,
2050 SmallVectorImpl<uint64_t> &Record,
2053 Record.push_back(IsBigInt | (
N->isUnsigned() << 1) |
N->isDistinct());
2054 Record.push_back(
N->getValue().getBitWidth());
2062void ModuleBitcodeWriter::writeDIBasicType(
const DIBasicType *
N,
2063 SmallVectorImpl<uint64_t> &Record,
2065 const unsigned SizeIsMetadata = 0x2;
2066 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2067 Record.push_back(
N->getTag());
2070 Record.push_back(
N->getAlignInBits());
2071 Record.push_back(
N->getEncoding());
2072 Record.push_back(
N->getFlags());
2073 Record.push_back(
N->getNumExtraInhabitants());
2074 Record.push_back(
N->getDataSizeInBits());
2076 Record.push_back(
N->getLine());
2083void ModuleBitcodeWriter::writeDIFixedPointType(
2084 const DIFixedPointType *
N, SmallVectorImpl<uint64_t> &Record,
2086 const unsigned SizeIsMetadata = 0x2;
2087 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2088 Record.push_back(
N->getTag());
2091 Record.push_back(
N->getAlignInBits());
2092 Record.push_back(
N->getEncoding());
2093 Record.push_back(
N->getFlags());
2094 Record.push_back(
N->getKind());
2095 Record.push_back(
N->getFactorRaw());
2097 auto WriteWideInt = [&](
const APInt &
Value) {
2102 Record.push_back(Encoded);
2106 WriteWideInt(
N->getNumeratorRaw());
2107 WriteWideInt(
N->getDenominatorRaw());
2110 Record.push_back(
N->getLine());
2117void ModuleBitcodeWriter::writeDIStringType(
const DIStringType *
N,
2118 SmallVectorImpl<uint64_t> &Record,
2120 const unsigned SizeIsMetadata = 0x2;
2121 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2122 Record.push_back(
N->getTag());
2128 Record.push_back(
N->getAlignInBits());
2129 Record.push_back(
N->getEncoding());
2136void ModuleBitcodeWriter::writeDIDerivedType(
const DIDerivedType *
N,
2137 SmallVectorImpl<uint64_t> &Record,
2139 const unsigned SizeIsMetadata = 0x2;
2140 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2141 Record.push_back(
N->getTag());
2144 Record.push_back(
N->getLine());
2148 Record.push_back(
N->getAlignInBits());
2150 Record.push_back(
N->getFlags());
2155 if (
const auto &DWARFAddressSpace =
N->getDWARFAddressSpace())
2156 Record.push_back(*DWARFAddressSpace + 1);
2162 if (
auto PtrAuthData =
N->getPtrAuthData())
2163 Record.push_back(PtrAuthData->RawData);
2171void ModuleBitcodeWriter::writeDISubrangeType(
const DISubrangeType *
N,
2172 SmallVectorImpl<uint64_t> &Record,
2174 const unsigned SizeIsMetadata = 0x2;
2175 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2178 Record.push_back(
N->getLine());
2181 Record.push_back(
N->getAlignInBits());
2182 Record.push_back(
N->getFlags());
2193void ModuleBitcodeWriter::writeDICompositeType(
2194 const DICompositeType *
N, SmallVectorImpl<uint64_t> &Record,
2196 const unsigned IsNotUsedInOldTypeRef = 0x2;
2197 const unsigned SizeIsMetadata = 0x4;
2198 Record.push_back(SizeIsMetadata | IsNotUsedInOldTypeRef |
2199 (
unsigned)
N->isDistinct());
2200 Record.push_back(
N->getTag());
2203 Record.push_back(
N->getLine());
2207 Record.push_back(
N->getAlignInBits());
2209 Record.push_back(
N->getFlags());
2211 Record.push_back(
N->getRuntimeLang());
2221 Record.push_back(
N->getNumExtraInhabitants());
2231void ModuleBitcodeWriter::writeDISubroutineType(
2232 const DISubroutineType *
N, SmallVectorImpl<uint64_t> &Record,
2234 const unsigned HasNoOldTypeRefs = 0x2;
2235 Record.push_back(HasNoOldTypeRefs | (
unsigned)
N->isDistinct());
2236 Record.push_back(
N->getFlags());
2244void ModuleBitcodeWriter::writeDIFile(
const DIFile *
N,
2245 SmallVectorImpl<uint64_t> &Record,
2247 Record.push_back(
N->isDistinct());
2250 if (
N->getRawChecksum()) {
2251 Record.push_back(
N->getRawChecksum()->Kind);
2259 auto Source =
N->getRawSource();
2267void ModuleBitcodeWriter::writeDICompileUnit(
const DICompileUnit *
N,
2268 SmallVectorImpl<uint64_t> &Record,
2270 assert(
N->isDistinct() &&
"Expected distinct compile units");
2273 auto Lang =
N->getSourceLanguage();
2274 Record.push_back(Lang.getName());
2277 if (Lang.hasVersionedName())
2282 Record.push_back(
N->isOptimized());
2284 Record.push_back(
N->getRuntimeVersion());
2286 Record.push_back(
N->getEmissionKind());
2292 Record.push_back(
N->getDWOId());
2294 Record.push_back(
N->getSplitDebugInlining());
2295 Record.push_back(
N->getDebugInfoForProfiling());
2296 Record.push_back((
unsigned)
N->getNameTableKind());
2297 Record.push_back(
N->getRangesBaseAddress());
2300 Record.push_back(Lang.hasVersionedName() ? Lang.getVersion() : 0);
2301 Record.push_back(Lang.getDialect());
2307void ModuleBitcodeWriter::writeDISubprogram(
const DISubprogram *
N,
2308 SmallVectorImpl<uint64_t> &Record,
2310 const uint64_t HasUnitFlag = 1 << 1;
2311 const uint64_t HasSPFlagsFlag = 1 << 2;
2312 Record.push_back(
uint64_t(
N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
2317 Record.push_back(
N->getLine());
2319 Record.push_back(
N->getScopeLine());
2321 Record.push_back(
N->getSPFlags());
2322 Record.push_back(
N->getVirtualIndex());
2323 Record.push_back(
N->getFlags());
2328 Record.push_back(
N->getThisAdjustment());
2332 Record.push_back(
N->getKeyInstructionsEnabled());
2338void ModuleBitcodeWriter::writeDILexicalBlock(
const DILexicalBlock *
N,
2339 SmallVectorImpl<uint64_t> &Record,
2341 Record.push_back(
N->isDistinct());
2344 Record.push_back(
N->getLine());
2345 Record.push_back(
N->getColumn());
2351void ModuleBitcodeWriter::writeDILexicalBlockFile(
2352 const DILexicalBlockFile *
N, SmallVectorImpl<uint64_t> &Record,
2354 Record.push_back(
N->isDistinct());
2357 Record.push_back(
N->getDiscriminator());
2363void ModuleBitcodeWriter::writeDICommonBlock(
const DICommonBlock *
N,
2364 SmallVectorImpl<uint64_t> &Record,
2366 Record.push_back(
N->isDistinct());
2371 Record.push_back(
N->getLineNo());
2377void ModuleBitcodeWriter::writeDINamespace(
const DINamespace *
N,
2378 SmallVectorImpl<uint64_t> &Record,
2380 Record.push_back(
N->isDistinct() |
N->getExportSymbols() << 1);
2388void ModuleBitcodeWriter::writeDIMacro(
const DIMacro *
N,
2389 SmallVectorImpl<uint64_t> &Record,
2391 Record.push_back(
N->isDistinct());
2392 Record.push_back(
N->getMacinfoType());
2393 Record.push_back(
N->getLine());
2401void ModuleBitcodeWriter::writeDIMacroFile(
const DIMacroFile *
N,
2402 SmallVectorImpl<uint64_t> &Record,
2404 Record.push_back(
N->isDistinct());
2405 Record.push_back(
N->getMacinfoType());
2406 Record.push_back(
N->getLine());
2414void ModuleBitcodeWriter::writeDIArgList(
const DIArgList *
N,
2415 SmallVectorImpl<uint64_t> &Record) {
2416 Record.reserve(
N->getArgs().size());
2417 for (ValueAsMetadata *MD :
N->getArgs())
2424void ModuleBitcodeWriter::writeDIModule(
const DIModule *
N,
2425 SmallVectorImpl<uint64_t> &Record,
2427 Record.push_back(
N->isDistinct());
2428 for (
auto &
I :
N->operands())
2430 Record.push_back(
N->getLineNo());
2431 Record.push_back(
N->getIsDecl());
2437void ModuleBitcodeWriter::writeDIAssignID(
const DIAssignID *
N,
2438 SmallVectorImpl<uint64_t> &Record,
2441 Record.push_back(
N->isDistinct());
2446void ModuleBitcodeWriter::writeDITemplateTypeParameter(
2447 const DITemplateTypeParameter *
N, SmallVectorImpl<uint64_t> &Record,
2449 Record.push_back(
N->isDistinct());
2452 Record.push_back(
N->isDefault());
2458void ModuleBitcodeWriter::writeDITemplateValueParameter(
2459 const DITemplateValueParameter *
N, SmallVectorImpl<uint64_t> &Record,
2461 Record.push_back(
N->isDistinct());
2462 Record.push_back(
N->getTag());
2465 Record.push_back(
N->isDefault());
2472void ModuleBitcodeWriter::writeDIGlobalVariable(
2473 const DIGlobalVariable *
N, SmallVectorImpl<uint64_t> &Record,
2481 Record.push_back(
N->getLine());
2483 Record.push_back(
N->isLocalToUnit());
2484 Record.push_back(
N->isDefinition());
2487 Record.push_back(
N->getAlignInBits());
2494void ModuleBitcodeWriter::writeDILocalVariable(
2495 const DILocalVariable *
N, SmallVectorImpl<uint64_t> &Record,
2510 const uint64_t HasAlignmentFlag = 1 << 1;
2515 Record.push_back(
N->getLine());
2517 Record.push_back(
N->getArg());
2518 Record.push_back(
N->getFlags());
2519 Record.push_back(
N->getAlignInBits());
2526void ModuleBitcodeWriter::writeDILabel(
2527 const DILabel *
N, SmallVectorImpl<uint64_t> &Record,
2534 Record.push_back(
N->getLine());
2535 Record.push_back(
N->getColumn());
2536 Record.push_back(
N->getCoroSuspendIdx().has_value()
2537 ? (
uint64_t)
N->getCoroSuspendIdx().value()
2538 : std::numeric_limits<uint64_t>::max());
2544void ModuleBitcodeWriter::writeDIExpression(
const DIExpression *
N,
2545 SmallVectorImpl<uint64_t> &Record,
2547 Record.reserve(
N->getElements().size() + 1);
2550 Record.append(
N->elements_begin(),
N->elements_end());
2556void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
2557 const DIGlobalVariableExpression *
N, SmallVectorImpl<uint64_t> &Record,
2559 Record.push_back(
N->isDistinct());
2567void ModuleBitcodeWriter::writeDIObjCProperty(
const DIObjCProperty *
N,
2568 SmallVectorImpl<uint64_t> &Record,
2570 Record.push_back(
N->isDistinct());
2573 Record.push_back(
N->getLine());
2576 Record.push_back(
N->getAttributes());
2583void ModuleBitcodeWriter::writeDIProperty(
const DIProperty *
N,
2584 SmallVectorImpl<uint64_t> &Record,
2586 Record.push_back(
N->isDistinct());
2589 Record.push_back(
N->getLine());
2597void ModuleBitcodeWriter::writeDIImportedEntity(
2598 const DIImportedEntity *
N, SmallVectorImpl<uint64_t> &Record,
2600 Record.push_back(
N->isDistinct());
2601 Record.push_back(
N->getTag());
2604 Record.push_back(
N->getLine());
2613unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
2614 auto Abbv = std::make_shared<BitCodeAbbrev>();
2621void ModuleBitcodeWriter::writeNamedMetadata(
2622 SmallVectorImpl<uint64_t> &Record) {
2623 if (
M.named_metadata_empty())
2626 unsigned Abbrev = createNamedMetadataAbbrev();
2627 for (
const NamedMDNode &NMD :
M.named_metadata()) {
2629 StringRef Str = NMD.getName();
2630 Record.append(Str.bytes_begin(), Str.bytes_end());
2635 for (
const MDNode *
N : NMD.operands())
2642unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
2643 auto Abbv = std::make_shared<BitCodeAbbrev>();
2655void ModuleBitcodeWriter::writeMetadataStrings(
2657 if (Strings.
empty())
2665 SmallString<256> Blob;
2667 BitstreamWriter
W(Blob);
2687#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
2688#include "llvm/IR/Metadata.def"
2692void ModuleBitcodeWriter::writeMetadataRecords(
2694 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
2699#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
2700#include "llvm/IR/Metadata.def"
2706 assert(
N->isResolved() &&
"Expected forward references to be resolved");
2708 switch (
N->getMetadataID()) {
2711#define HANDLE_MDNODE_LEAF(CLASS) \
2712 case Metadata::CLASS##Kind: \
2714 write##CLASS(cast<CLASS>(N), Record, \
2715 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
2717 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
2719#include "llvm/IR/Metadata.def"
2730void ModuleBitcodeWriter::writeModuleMetadata() {
2731 if (!VE.
hasMDs() &&
M.named_metadata_empty())
2735 SmallVector<uint64_t, 64>
Record;
2739 std::vector<unsigned> MDAbbrevs;
2742 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] =
2743 createDILocationAbbrev(
false);
2744 DILocationLayersAbbrev = createDILocationAbbrev(
true);
2745 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
2746 createGenericDINodeAbbrev();
2748 auto Abbv = std::make_shared<BitCodeAbbrev>();
2752 unsigned OffsetAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
2754 Abbv = std::make_shared<BitCodeAbbrev>();
2758 unsigned IndexAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
2780 std::vector<uint64_t> IndexPos;
2784 writeMetadataRecords(VE.
getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2795 uint64_t PreviousValue = IndexOffsetRecordBitPos;
2796 for (
auto &Elt : IndexPos) {
2797 auto EltDelta = Elt - PreviousValue;
2798 PreviousValue = Elt;
2807 writeNamedMetadata(Record);
2809 auto AddDeclAttachedMetadata = [&](
const GlobalObject &GO) {
2810 SmallVector<uint64_t, 4>
Record;
2812 pushGlobalMetadataAttachment(Record, GO);
2816 if (
F.isDeclaration() &&
F.hasMetadata())
2817 AddDeclAttachedMetadata(
F);
2818 for (
const GlobalIFunc &GI :
M.ifuncs())
2819 if (GI.hasMetadata())
2820 AddDeclAttachedMetadata(GI);
2823 for (
const GlobalVariable &GV :
M.globals())
2824 if (GV.hasMetadata())
2825 AddDeclAttachedMetadata(GV);
2830void ModuleBitcodeWriter::writeFunctionMetadata(
const Function &
F) {
2837 DILocationLayersAbbrev = 0;
2838 SmallVector<uint64_t, 64>
Record;
2844void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2845 SmallVectorImpl<uint64_t> &Record,
const GlobalObject &GO) {
2849 for (
const auto &
I : MDs) {
2855void ModuleBitcodeWriter::writeFunctionMetadataAttachment(
const Function &
F) {
2858 SmallVector<uint64_t, 64>
Record;
2860 if (
F.hasMetadata()) {
2861 pushGlobalMetadataAttachment(Record,
F);
2869 for (
const BasicBlock &BB :
F)
2870 for (
const Instruction &
I : BB) {
2872 I.getAllMetadataOtherThanDebugLoc(MDs);
2875 if (MDs.
empty())
continue;
2879 for (
const auto &[ID, MD] : MDs) {
2890void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2891 SmallVector<uint64_t, 64>
Record;
2896 M.getMDKindNames(Names);
2898 if (Names.
empty())
return;
2902 for (
unsigned MDKindID = 0, e = Names.
size(); MDKindID != e; ++MDKindID) {
2903 Record.push_back(MDKindID);
2904 StringRef KName = Names[MDKindID];
2914void ModuleBitcodeWriter::writeOperandBundleTags() {
2922 M.getOperandBundleTags(Tags);
2929 SmallVector<uint64_t, 64>
Record;
2931 for (
auto Tag : Tags) {
2941void ModuleBitcodeWriter::writeSyncScopeNames() {
2943 M.getContext().getSyncScopeNames(SSNs);
2949 SmallVector<uint64_t, 64>
Record;
2950 for (
auto SSN : SSNs) {
2951 Record.append(SSN.begin(), SSN.end());
2959void ModuleBitcodeWriter::writeConstants(
unsigned FirstVal,
unsigned LastVal,
2961 if (FirstVal == LastVal)
return;
2965 unsigned AggregateAbbrev = 0;
2966 unsigned String8Abbrev = 0;
2967 unsigned CString7Abbrev = 0;
2968 unsigned CString6Abbrev = 0;
2972 auto Abbv = std::make_shared<BitCodeAbbrev>();
2976 AggregateAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
2979 Abbv = std::make_shared<BitCodeAbbrev>();
2983 String8Abbrev = Stream.
EmitAbbrev(std::move(Abbv));
2985 Abbv = std::make_shared<BitCodeAbbrev>();
2989 CString7Abbrev = Stream.
EmitAbbrev(std::move(Abbv));
2991 Abbv = std::make_shared<BitCodeAbbrev>();
2995 CString6Abbrev = Stream.
EmitAbbrev(std::move(Abbv));
2998 SmallVector<uint64_t, 64>
Record;
3001 Type *LastTy =
nullptr;
3002 for (
unsigned i = FirstVal; i != LastVal; ++i) {
3003 const Value *
V = Vals[i].first;
3005 if (
V->getType() != LastTy) {
3006 LastTy =
V->getType();
3009 CONSTANTS_SETTYPE_ABBREV);
3016 unsigned(
IA->hasSideEffects()) |
unsigned(
IA->isAlignStack()) << 1 |
3017 unsigned(
IA->getDialect() & 1) << 2 |
unsigned(
IA->canThrow()) << 3);
3020 StringRef AsmStr =
IA->getAsmString();
3025 StringRef ConstraintStr =
IA->getConstraintString();
3033 unsigned Code = -1U;
3034 unsigned AbbrevToUse = 0;
3035 if (
C->isNullValue()) {
3042 if (
IV->getBitWidth() <= 64) {
3046 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
3052 if (BV->getBitWidth() <= 64) {
3056 AbbrevToUse = CONSTANTS_BYTE_ABBREV;
3066 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
3070 APInt api = CFP->getValueAPF().bitcastToAPInt();
3072 Record.push_back((p[1] << 48) | (p[0] >> 16));
3073 Record.push_back(p[0] & 0xffffLL);
3075 APInt api = CFP->getValueAPF().bitcastToAPInt();
3080 assert(0 &&
"Unknown FP type!");
3086 uint64_t NumElts = Str->getNumElements();
3088 if (Str->isCString()) {
3093 AbbrevToUse = String8Abbrev;
3097 for (
uint64_t i = 0; i != NumElts; ++i) {
3098 unsigned char V = Str->getElementAsInteger(i);
3100 isCStr7 &= (
V & 128) == 0;
3106 AbbrevToUse = CString6Abbrev;
3108 AbbrevToUse = CString7Abbrev;
3109 }
else if (
const ConstantDataSequential *CDS =
3112 Type *EltTy = CDS->getElementType();
3114 for (
uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i)
3115 Record.push_back(CDS->getElementAsInteger(i));
3117 for (
uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i)
3119 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
3123 for (
const Value *
Op :
C->operands())
3125 AbbrevToUse = AggregateAbbrev;
3127 switch (
CE->getOpcode()) {
3134 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
3136 assert(
CE->getNumOperands() == 2 &&
"Unknown constant expr!");
3146 case Instruction::GetElementPtr: {
3151 if (std::optional<ConstantRange>
Range = GO->getInRange()) {
3155 for (
const Value *
Op :
CE->operands()) {
3161 case Instruction::ExtractElement:
3168 case Instruction::InsertElement:
3175 case Instruction::ShuffleVector:
3180 if (
C->getType() ==
C->getOperand(0)->getType()) {
3217 Stream.
EmitRecord(Code, Record, AbbrevToUse);
3224void ModuleBitcodeWriter::writeModuleConstants() {
3229 for (
unsigned i = 0, e = Vals.size(); i != e; ++i) {
3231 writeConstants(i, Vals.size(),
true);
3245bool ModuleBitcodeWriter::pushValueAndType(
const Value *
V,
unsigned InstID,
3246 SmallVectorImpl<unsigned> &Vals) {
3250 if (ValID >= InstID) {
3257bool ModuleBitcodeWriter::pushValueOrMetadata(
const Value *
V,
unsigned InstID,
3258 SmallVectorImpl<unsigned> &Vals) {
3259 bool IsMetadata =
V->getType()->isMetadataTy();
3267 return pushValueAndType(
V, InstID, Vals);
3270void ModuleBitcodeWriter::writeOperandBundles(
const CallBase &CS,
3277 Record.push_back(
C.getOperandBundleTagID(Bundle.getTagName()));
3279 for (
auto &Input : Bundle.Inputs)
3280 pushValueOrMetadata(Input, InstID, Record);
3289void ModuleBitcodeWriter::pushValue(
const Value *
V,
unsigned InstID,
3290 SmallVectorImpl<unsigned> &Vals) {
3295void ModuleBitcodeWriter::pushValueSigned(
const Value *
V,
unsigned InstID,
3296 SmallVectorImpl<uint64_t> &Vals) {
3298 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
3303void ModuleBitcodeWriter::writeInstruction(
const Instruction &
I,
3305 SmallVectorImpl<unsigned> &Vals) {
3307 unsigned AbbrevToUse = 0;
3309 switch (
I.getOpcode()) {
3313 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3314 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
3319 if (AbbrevToUse == FUNCTION_INST_CAST_ABBREV)
3320 AbbrevToUse = FUNCTION_INST_CAST_FLAGS_ABBREV;
3326 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3327 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
3328 pushValue(
I.getOperand(1), InstID, Vals);
3332 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
3333 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
3338 case Instruction::FNeg: {
3340 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3341 AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
3345 if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
3346 AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
3351 case Instruction::GetElementPtr: {
3353 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
3357 for (
const Value *
Op :
I.operands())
3358 pushValueAndType(
Op, InstID, Vals);
3361 case Instruction::ExtractValue: {
3363 pushValueAndType(
I.getOperand(0), InstID, Vals);
3368 case Instruction::InsertValue: {
3370 pushValueAndType(
I.getOperand(0), InstID, Vals);
3371 pushValueAndType(
I.getOperand(1), InstID, Vals);
3376 case Instruction::Select: {
3378 pushValueAndType(
I.getOperand(1), InstID, Vals);
3379 pushValue(
I.getOperand(2), InstID, Vals);
3380 pushValueAndType(
I.getOperand(0), InstID, Vals);
3386 case Instruction::ExtractElement:
3388 pushValueAndType(
I.getOperand(0), InstID, Vals);
3389 pushValueAndType(
I.getOperand(1), InstID, Vals);
3391 case Instruction::InsertElement:
3393 pushValueAndType(
I.getOperand(0), InstID, Vals);
3394 pushValue(
I.getOperand(1), InstID, Vals);
3395 pushValueAndType(
I.getOperand(2), InstID, Vals);
3397 case Instruction::BitExtract:
3400 pushValueAndType(
I.getOperand(0), InstID, Vals);
3401 pushValueAndType(
I.getOperand(1), InstID, Vals);
3403 case Instruction::BitInsert:
3405 pushValueAndType(
I.getOperand(0), InstID, Vals);
3406 pushValueAndType(
I.getOperand(1), InstID, Vals);
3407 pushValueAndType(
I.getOperand(2), InstID, Vals);
3409 case Instruction::ShuffleVector:
3411 pushValueAndType(
I.getOperand(0), InstID, Vals);
3412 pushValue(
I.getOperand(1), InstID, Vals);
3416 case Instruction::ICmp:
3417 case Instruction::FCmp: {
3420 AbbrevToUse = FUNCTION_INST_CMP_ABBREV;
3421 if (pushValueAndType(
I.getOperand(0), InstID, Vals))
3423 pushValue(
I.getOperand(1), InstID, Vals);
3429 AbbrevToUse = FUNCTION_INST_CMP_FLAGS_ABBREV;
3434 case Instruction::Ret:
3437 unsigned NumOperands =
I.getNumOperands();
3438 if (NumOperands == 0)
3439 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
3440 else if (NumOperands == 1) {
3441 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3442 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
3444 for (
const Value *
Op :
I.operands())
3445 pushValueAndType(
Op, InstID, Vals);
3449 case Instruction::UncondBr: {
3451 AbbrevToUse = FUNCTION_INST_BR_UNCOND_ABBREV;
3455 case Instruction::CondBr: {
3457 AbbrevToUse = FUNCTION_INST_BR_COND_ABBREV;
3461 pushValue(
II.getCondition(), InstID, Vals);
3463 case Instruction::Switch:
3468 pushValue(
SI.getCondition(), InstID, Vals);
3470 for (
auto Case :
SI.cases()) {
3476 case Instruction::IndirectBr:
3480 pushValue(
I.getOperand(0), InstID, Vals);
3485 case Instruction::Invoke: {
3488 FunctionType *FTy =
II->getFunctionType();
3490 if (
II->hasOperandBundles())
3491 writeOperandBundles(*
II, InstID);
3500 pushValueAndType(Callee, InstID, Vals);
3503 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3504 pushValue(
I.getOperand(i), InstID, Vals);
3507 if (FTy->isVarArg()) {
3508 for (
unsigned i = FTy->getNumParams(), e =
II->arg_size(); i != e; ++i)
3509 pushValueAndType(
I.getOperand(i), InstID, Vals);
3513 case Instruction::Resume:
3515 pushValueAndType(
I.getOperand(0), InstID, Vals);
3517 case Instruction::CleanupRet: {
3520 pushValue(CRI.getCleanupPad(), InstID, Vals);
3521 if (CRI.hasUnwindDest())
3525 case Instruction::CatchRet: {
3528 pushValue(CRI.getCatchPad(), InstID, Vals);
3532 case Instruction::CleanupPad:
3533 case Instruction::CatchPad: {
3537 pushValue(FuncletPad.getParentPad(), InstID, Vals);
3539 unsigned NumArgOperands = FuncletPad.arg_size();
3541 for (
unsigned Op = 0;
Op != NumArgOperands; ++
Op)
3542 pushValueAndType(FuncletPad.getArgOperand(
Op), InstID, Vals);
3545 case Instruction::CatchSwitch: {
3549 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
3551 unsigned NumHandlers = CatchSwitch.getNumHandlers();
3553 for (
const BasicBlock *CatchPadBB : CatchSwitch.handlers())
3556 if (CatchSwitch.hasUnwindDest())
3560 case Instruction::CallBr: {
3566 writeOperandBundles(*CBI, InstID);
3581 pushValueAndType(Callee, InstID, Vals);
3584 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3585 pushValue(
I.getOperand(i), InstID, Vals);
3588 if (FTy->isVarArg()) {
3589 for (
unsigned i = FTy->getNumParams(), e = CBI->
arg_size(); i != e; ++i)
3590 pushValueAndType(
I.getOperand(i), InstID, Vals);
3594 case Instruction::Unreachable:
3596 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
3599 case Instruction::PHI: {
3617 Stream.
EmitRecord(Code, Vals64, AbbrevToUse);
3622 case Instruction::LandingPad: {
3633 pushValueAndType(LP.
getClause(
I), InstID, Vals);
3638 case Instruction::Alloca: {
3644 using APV = AllocaPackedValues;
3646 unsigned EncodedAlign = getEncodedAlign(AI.
getAlign());
3648 Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1));
3650 EncodedAlign >> APV::AlignLower::Bits);
3657 if (AS !=
M.getDataLayout().getAllocaAddrSpace())
3662 case Instruction::Load: {
3664 if (LI.isAtomic()) {
3666 pushValueAndType(LI.getOperand(0), InstID, Vals);
3669 if (!pushValueAndType(LI.getOperand(0), InstID, Vals))
3670 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
3673 Vals.
push_back(getEncodedAlign(LI.getAlign()));
3675 if (LI.isAtomic()) {
3677 Vals.
push_back(getEncodedSyncScopeID(LI.getSyncScopeID()));
3678 if (LI.isElementwise())
3684 case Instruction::Store: {
3686 if (
SI.isAtomic()) {
3690 AbbrevToUse = FUNCTION_INST_STORE_ABBREV;
3692 if (pushValueAndType(
I.getOperand(1), InstID, Vals))
3694 if (pushValueAndType(
I.getOperand(0), InstID, Vals))
3698 if (
SI.isAtomic()) {
3700 Vals.
push_back(getEncodedSyncScopeID(
SI.getSyncScopeID()));
3701 if (
SI.isElementwise())
3707 case Instruction::AtomicCmpXchg:
3709 pushValueAndType(
I.getOperand(0), InstID, Vals);
3710 pushValueAndType(
I.getOperand(1), InstID, Vals);
3711 pushValue(
I.getOperand(2), InstID, Vals);
3722 case Instruction::AtomicRMW:
3724 pushValueAndType(
I.getOperand(0), InstID, Vals);
3725 pushValueAndType(
I.getOperand(1), InstID, Vals);
3733 case Instruction::Fence:
3738 case Instruction::Call: {
3743 writeOperandBundles(CI, InstID);
3763 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3767 if (FTy->isVarArg()) {
3768 for (
unsigned i = FTy->getNumParams(), e = CI.
arg_size(); i != e; ++i)
3773 case Instruction::VAArg:
3776 pushValue(
I.getOperand(0), InstID, Vals);
3779 case Instruction::Freeze:
3781 pushValueAndType(
I.getOperand(0), InstID, Vals);
3791void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3792 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3797 VSTOffset -= bitcodeStartBit();
3798 assert((VSTOffset & 31) == 0 &&
"VST block not 32-bit aligned");
3802 Stream.
BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
3806 auto Abbv = std::make_shared<BitCodeAbbrev>();
3810 unsigned FnEntryAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
3815 if (
F.isDeclaration())
3822 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&
F] - bitcodeStartBit();
3823 assert((BitcodeIndex & 31) == 0 &&
"function block not 32-bit aligned");
3827 Record[1] = BitcodeIndex / 32 + 1;
3836void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3837 const ValueSymbolTable &VST) {
3845 SmallVector<uint64_t, 64> NameVals;
3851 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3860 AbbrevToUse = VST_BBENTRY_6_ABBREV;
3864 AbbrevToUse = VST_ENTRY_6_ABBREV;
3866 AbbrevToUse = VST_ENTRY_7_ABBREV;
3869 for (
const auto P :
Name.getKey())
3873 Stream.
EmitRecord(Code, NameVals, AbbrevToUse);
3880void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3881 assert(Order.Shuffle.size() >= 2 &&
"Shuffle too small");
3888 SmallVector<uint64_t, 64>
Record(Order.Shuffle.begin(), Order.Shuffle.end());
3893void ModuleBitcodeWriter::writeUseListBlock(
const Function *
F) {
3895 "Expected to be preserving use-list order");
3897 auto hasMore = [&]() {
3913void ModuleBitcodeWriter::writeFunction(
3915 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3932 unsigned CstStart, CstEnd;
3934 writeConstants(CstStart, CstEnd,
false);
3937 writeFunctionMetadata(
F);
3940 unsigned InstID = CstEnd;
3942 bool NeedsMetadataAttachment =
F.hasMetadata();
3944 DILocation *LastDL =
nullptr;
3945 SmallSetVector<Function *, 4> BlockAddressUsers;
3948 for (
const BasicBlock &BB :
F) {
3949 for (
const Instruction &
I : BB) {
3950 writeInstruction(
I, InstID, Vals);
3952 if (!
I.getType()->isVoidTy())
3956 NeedsMetadataAttachment |=
I.hasMetadataOtherThanDebugLoc();
3959 if (DILocation *
DL =
I.getDebugLoc()) {
3972 unsigned DLAbbrev = FUNCTION_DEBUG_LOC_ABBREV;
3973 if (DILayerLocList *IRLayers =
DL->getIRLayers()) {
3974 DLAbbrev = FUNCTION_DEBUG_LOC_LAYERS_ABBREV;
3988 if (
I.hasDbgRecords()) {
3992 auto PushValueOrMetadata = [&Vals, InstID,
3995 "RawLocation unexpectedly null in DbgVariableRecord");
3997 SmallVector<unsigned, 2> ValAndType;
4001 if (!pushValueAndType(VAM->getValue(), InstID, ValAndType)) {
4015 for (DbgRecord &DR :
I.getDbgMarker()->getDbgRecordRange()) {
4041 FUNCTION_DEBUG_RECORD_VALUE_ABBREV);
4065 SmallPtrSet<Value *, 8> Visited{BA};
4066 while (!Worklist.
empty()) {
4068 for (User *U :
V->users()) {
4074 Visited.
insert(U).second)
4081 if (!BlockAddressUsers.
empty()) {
4090 if (
auto *Symtab =
F.getValueSymbolTable())
4091 writeFunctionLevelValueSymbolTable(*Symtab);
4093 if (NeedsMetadataAttachment)
4094 writeFunctionMetadataAttachment(
F);
4096 writeUseListBlock(&
F);
4102void ModuleBitcodeWriter::writeBlockInfo() {
4115 auto Abbv = std::make_shared<BitCodeAbbrev>();
4126 auto Abbv = std::make_shared<BitCodeAbbrev>();
4136 auto Abbv = std::make_shared<BitCodeAbbrev>();
4146 auto Abbv = std::make_shared<BitCodeAbbrev>();
4152 VST_BBENTRY_6_ABBREV)
4157 auto Abbv = std::make_shared<BitCodeAbbrev>();
4159 Abbv->Add(TypeAbbrevOp);
4161 CONSTANTS_SETTYPE_ABBREV)
4166 auto Abbv = std::make_shared<BitCodeAbbrev>();
4170 CONSTANTS_INTEGER_ABBREV)
4175 auto Abbv = std::make_shared<BitCodeAbbrev>();
4179 CONSTANTS_BYTE_ABBREV)
4184 auto Abbv = std::make_shared<BitCodeAbbrev>();
4192 CONSTANTS_CE_CAST_Abbrev)
4196 auto Abbv = std::make_shared<BitCodeAbbrev>();
4199 CONSTANTS_NULL_Abbrev)
4206 auto Abbv = std::make_shared<BitCodeAbbrev>();
4208 Abbv->Add(ValAbbrevOp);
4209 Abbv->Add(TypeAbbrevOp);
4213 FUNCTION_INST_LOAD_ABBREV)
4217 auto Abbv = std::make_shared<BitCodeAbbrev>();
4219 Abbv->Add(ValAbbrevOp);
4220 Abbv->Add(ValAbbrevOp);
4224 FUNCTION_INST_STORE_ABBREV)
4228 auto Abbv = std::make_shared<BitCodeAbbrev>();
4230 Abbv->Add(ValAbbrevOp);
4233 FUNCTION_INST_UNOP_ABBREV)
4237 auto Abbv = std::make_shared<BitCodeAbbrev>();
4239 Abbv->Add(ValAbbrevOp);
4243 FUNCTION_INST_UNOP_FLAGS_ABBREV)
4247 auto Abbv = std::make_shared<BitCodeAbbrev>();
4249 Abbv->Add(ValAbbrevOp);
4250 Abbv->Add(ValAbbrevOp);
4253 FUNCTION_INST_BINOP_ABBREV)
4257 auto Abbv = std::make_shared<BitCodeAbbrev>();
4259 Abbv->Add(ValAbbrevOp);
4260 Abbv->Add(ValAbbrevOp);
4264 FUNCTION_INST_BINOP_FLAGS_ABBREV)
4268 auto Abbv = std::make_shared<BitCodeAbbrev>();
4270 Abbv->Add(ValAbbrevOp);
4271 Abbv->Add(TypeAbbrevOp);
4274 FUNCTION_INST_CAST_ABBREV)
4278 auto Abbv = std::make_shared<BitCodeAbbrev>();
4280 Abbv->Add(ValAbbrevOp);
4281 Abbv->Add(TypeAbbrevOp);
4285 FUNCTION_INST_CAST_FLAGS_ABBREV)
4290 auto Abbv = std::make_shared<BitCodeAbbrev>();
4293 FUNCTION_INST_RET_VOID_ABBREV)
4297 auto Abbv = std::make_shared<BitCodeAbbrev>();
4299 Abbv->Add(ValAbbrevOp);
4301 FUNCTION_INST_RET_VAL_ABBREV)
4305 auto Abbv = std::make_shared<BitCodeAbbrev>();
4308 Abbv->Add(ValAbbrevOp);
4310 FUNCTION_INST_BR_UNCOND_ABBREV)
4314 auto Abbv = std::make_shared<BitCodeAbbrev>();
4317 Abbv->Add(ValAbbrevOp);
4318 Abbv->Add(ValAbbrevOp);
4319 Abbv->Add(ValAbbrevOp);
4321 FUNCTION_INST_BR_COND_ABBREV)
4325 auto Abbv = std::make_shared<BitCodeAbbrev>();
4328 FUNCTION_INST_UNREACHABLE_ABBREV)
4332 auto Abbv = std::make_shared<BitCodeAbbrev>();
4335 Abbv->Add(TypeAbbrevOp);
4337 Abbv->Add(ValAbbrevOp);
4339 FUNCTION_INST_GEP_ABBREV)
4343 auto Abbv = std::make_shared<BitCodeAbbrev>();
4345 Abbv->Add(ValAbbrevOp);
4346 Abbv->Add(ValAbbrevOp);
4349 FUNCTION_INST_CMP_ABBREV)
4353 auto Abbv = std::make_shared<BitCodeAbbrev>();
4355 Abbv->Add(ValAbbrevOp);
4356 Abbv->Add(ValAbbrevOp);
4360 FUNCTION_INST_CMP_FLAGS_ABBREV)
4364 auto Abbv = std::make_shared<BitCodeAbbrev>();
4369 Abbv->Add(ValAbbrevOp);
4371 FUNCTION_DEBUG_RECORD_VALUE_ABBREV)
4375 auto Abbv = std::make_shared<BitCodeAbbrev>();
4386 FUNCTION_DEBUG_LOC_ABBREV)
4392 auto Abbv = std::make_shared<BitCodeAbbrev>();
4403 FUNCTION_DEBUG_LOC_LAYERS_ABBREV)
4411void IndexBitcodeWriter::writeModStrings() {
4417 auto Abbv = std::make_shared<BitCodeAbbrev>();
4422 unsigned Abbrev8Bit = Stream.
EmitAbbrev(std::move(Abbv));
4425 Abbv = std::make_shared<BitCodeAbbrev>();
4430 unsigned Abbrev7Bit = Stream.
EmitAbbrev(std::move(Abbv));
4433 Abbv = std::make_shared<BitCodeAbbrev>();
4438 unsigned Abbrev6Bit = Stream.
EmitAbbrev(std::move(Abbv));
4441 Abbv = std::make_shared<BitCodeAbbrev>();
4448 unsigned AbbrevHash = Stream.
EmitAbbrev(std::move(Abbv));
4451 forEachModule([&](
const StringMapEntry<ModuleHash> &MPSE) {
4453 const auto &Hash = MPSE.
getValue();
4455 unsigned AbbrevToUse = Abbrev8Bit;
4457 AbbrevToUse = Abbrev6Bit;
4459 AbbrevToUse = Abbrev7Bit;
4461 auto ModuleId = ModuleIdMap.
size();
4462 ModuleIdMap[
Key] = ModuleId;
4472 Vals.
assign(Hash.begin(), Hash.end());
4484template <
typename Fn>
4488 if (!FS->type_tests().empty())
4493 auto WriteVFuncIdVec = [&](
uint64_t Ty,
4498 for (
auto &VF : VFs) {
4499 Record.push_back(VF.GUID);
4500 Record.push_back(VF.Offset);
4506 FS->type_test_assume_vcalls());
4508 FS->type_checked_load_vcalls());
4510 auto WriteConstVCallVec = [&](
uint64_t Ty,
4512 for (
auto &VC : VCs) {
4514 Record.push_back(VC.VFunc.GUID);
4515 Record.push_back(VC.VFunc.Offset);
4522 FS->type_test_assume_const_vcalls());
4524 FS->type_checked_load_const_vcalls());
4534 if (!FS->paramAccesses().empty()) {
4536 for (
auto &Arg : FS->paramAccesses()) {
4537 size_t UndoSize =
Record.size();
4538 Record.push_back(Arg.ParamNo);
4539 WriteRange(Arg.Use);
4540 Record.push_back(Arg.Calls.size());
4541 for (
auto &
Call : Arg.Calls) {
4543 std::optional<unsigned> ValueID = GetValueID(
Call.Callee);
4550 Record.push_back(*ValueID);
4551 WriteRange(
Call.Offsets);
4562 std::set<GlobalValue::GUID> &ReferencedTypeIds) {
4563 if (!FS->type_tests().empty())
4564 for (
auto &TT : FS->type_tests())
4565 ReferencedTypeIds.insert(TT);
4567 auto GetReferencedTypesFromVFuncIdVec =
4569 for (
auto &VF : VFs)
4570 ReferencedTypeIds.insert(VF.GUID);
4573 GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
4574 GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
4576 auto GetReferencedTypesFromConstVCallVec =
4578 for (
auto &VC : VCs)
4579 ReferencedTypeIds.insert(VC.VFunc.GUID);
4582 GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
4583 GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
4619 NameVals.
push_back(Summary.TTRes.TheKind);
4620 NameVals.
push_back(Summary.TTRes.SizeM1BitWidth);
4621 NameVals.
push_back(Summary.TTRes.AlignLog2);
4622 NameVals.
push_back(Summary.TTRes.SizeM1);
4623 NameVals.
push_back(Summary.TTRes.BitMask);
4624 NameVals.
push_back(Summary.TTRes.InlineBits);
4626 for (
auto &W : Summary.WPDRes)
4638 for (
auto &
P : Summary) {
4640 NameVals.
push_back(
VE.getValueID(
P.VTableVI.getValue()));
4654 static_assert(std::is_same_v<LinearFrameId, unsigned>);
4655 for (
auto &AI : FS->allocs()) {
4656 for (
auto &MIB : AI.MIBs) {
4658 StackIdIndices.
reserve(MIB.StackIdIndices.size());
4659 for (
auto Id : MIB.StackIdIndices)
4660 StackIdIndices.
push_back(GetStackIndex(Id));
4662 CallStacks.insert({CallStacks.size(), StackIdIndices});
4675 assert(!CallStacks.empty());
4681 Builder.
build(std::move(CallStacks),
nullptr,
4685 return Builder.takeCallStackPos();
4690 unsigned AllocAbbrev,
unsigned ContextIdAbbvId,
bool PerModule,
4691 std::function<
unsigned(
const ValueInfo &VI)> GetValueID,
4692 std::function<
unsigned(
unsigned)> GetStackIndex,
4693 bool WriteContextSizeInfoIndex,
4698 for (
auto &CI : FS->callsites()) {
4702 assert(!PerModule || (CI.Clones.size() == 1 && CI.Clones[0] == 0));
4703 Record.push_back(GetValueID(CI.Callee));
4705 Record.push_back(CI.StackIdIndices.size());
4706 Record.push_back(CI.Clones.size());
4708 for (
auto Id : CI.StackIdIndices)
4709 Record.push_back(GetStackIndex(Id));
4717 for (
auto &AI : FS->allocs()) {
4721 assert(!PerModule || (AI.Versions.size() == 1 && AI.Versions[0] == 0));
4722 Record.push_back(AI.MIBs.size());
4724 Record.push_back(AI.Versions.size());
4725 for (
auto &MIB : AI.MIBs) {
4732 assert(CallStackCount <= CallStackPos.
size());
4733 Record.push_back(CallStackPos[CallStackCount++]);
4738 assert(AI.ContextSizeInfos.empty() ||
4739 AI.ContextSizeInfos.size() == AI.MIBs.size());
4741 if (WriteContextSizeInfoIndex && !AI.ContextSizeInfos.empty()) {
4749 ContextIds.
reserve(AI.ContextSizeInfos.size() * 2);
4750 for (
auto &Infos : AI.ContextSizeInfos) {
4751 Record.push_back(Infos.size());
4752 for (
auto [FullStackId, TotalSize] : Infos) {
4759 Record.push_back(TotalSize);
4777void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
4778 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
4779 unsigned ValueID,
unsigned FSCallsProfileAbbrev,
unsigned CallsiteAbbrev,
4780 unsigned AllocAbbrev,
unsigned ContextIdAbbvId,
const Function &
F,
4781 DenseMap<CallStackId, LinearCallStackId> &CallStackPos,
4788 Stream, FS, [&](
const ValueInfo &VI) -> std::optional<unsigned> {
4792 auto SpecialRefCnts =
FS->specialRefCounts();
4797 NameVals.
push_back(SpecialRefCnts.first);
4798 NameVals.
push_back(SpecialRefCnts.second);
4800 for (
auto &RI :
FS->refs())
4803 for (
auto &ECI :
FS->calls()) {
4804 NameVals.
push_back(getValueId(ECI.first));
4813 Stream, FS, CallsiteAbbrev, AllocAbbrev, ContextIdAbbvId,
4815 [&](
const ValueInfo &VI) {
return getValueId(VI); },
4816 [&](
unsigned I) {
return I; },
4817 true, CallStackPos, CallStackCount);
4822void ModuleBitcodeWriterBase::writeModuleLevelReferences(
4823 const GlobalVariable &
V, SmallVector<uint64_t, 64> &NameVals,
4824 unsigned FSModRefsAbbrev,
unsigned FSModVTableRefsAbbrev) {
4829 auto VI =
Index->getValueInfo(GUID);
4830 if (!VI ||
VI.getSummaryList().empty()) {
4836 auto *
Summary =
VI.getSummaryList()[0].get();
4842 auto VTableFuncs =
VS->vTableFuncs();
4843 if (!VTableFuncs.empty())
4846 unsigned SizeBeforeRefs = NameVals.
size();
4847 for (
auto &RI :
VS->refs())
4853 if (VTableFuncs.empty())
4858 for (
auto &
P : VTableFuncs) {
4864 FSModVTableRefsAbbrev);
4871void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
4874 bool IsThinLTO =
true;
4877 IsThinLTO = MD->getZExtValue();
4889 if (
Index->enableSplitLTOUnit())
4891 if (
Index->hasUnifiedLTO())
4901 auto Abbv = std::make_shared<BitCodeAbbrev>();
4907 unsigned ValueGuidAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4909 for (
const auto &GVI : valueIds()) {
4911 ArrayRef<uint32_t>{GVI.second,
4912 static_cast<uint32_t
>(GVI.first >> 32),
4913 static_cast<uint32_t
>(GVI.first)},
4917 if (!
Index->stackIds().empty()) {
4918 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4925 unsigned StackIdAbbvId = Stream.
EmitAbbrev(std::move(StackIdAbbv));
4926 SmallVector<uint32_t> Vals;
4928 for (
auto Id :
Index->stackIds()) {
4929 Vals.
push_back(
static_cast<uint32_t
>(Id >> 32));
4930 Vals.
push_back(
static_cast<uint32_t
>(Id));
4935 unsigned ContextIdAbbvId = 0;
4938 auto ContextIdAbbv = std::make_shared<BitCodeAbbrev>();
4950 ContextIdAbbvId = Stream.
EmitAbbrev(std::move(ContextIdAbbv));
4954 Abbv = std::make_shared<BitCodeAbbrev>();
4966 unsigned FSCallsProfileAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4969 Abbv = std::make_shared<BitCodeAbbrev>();
4975 unsigned FSModRefsAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4978 Abbv = std::make_shared<BitCodeAbbrev>();
4986 unsigned FSModVTableRefsAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4989 Abbv = std::make_shared<BitCodeAbbrev>();
4994 unsigned FSAliasAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4997 Abbv = std::make_shared<BitCodeAbbrev>();
5004 unsigned TypeIdCompatibleVtableAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5006 Abbv = std::make_shared<BitCodeAbbrev>();
5012 unsigned CallsiteAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5014 Abbv = std::make_shared<BitCodeAbbrev>();
5021 unsigned AllocAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5023 Abbv = std::make_shared<BitCodeAbbrev>();
5028 unsigned RadixAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5035 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks;
5046 ValueInfo
VI =
Index->getValueInfo(GUID);
5047 if (!VI ||
VI.getSummaryList().empty()) {
5050 if (!
F.isDeclaration())
5052 " to have an associated value info.");
5055 auto *
Summary =
VI.getSummaryList()[0].get();
5058 FS, [](
unsigned I) {
return I; }, CallStacks);
5062 DenseMap<CallStackId, LinearCallStackId> CallStackPos;
5063 if (!CallStacks.
empty()) {
5071 SmallVector<uint64_t, 64> NameVals;
5082 ValueInfo
VI =
Index->getValueInfo(GUID);
5083 if (!VI ||
VI.getSummaryList().empty()) {
5089 auto *
Summary =
VI.getSummaryList()[0].get();
5090 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.
getValueID(&
F),
5091 FSCallsProfileAbbrev, CallsiteAbbrev,
5092 AllocAbbrev, ContextIdAbbvId,
F,
5093 CallStackPos, CallStackCount);
5098 for (
const GlobalVariable &
G :
M.globals())
5099 writeModuleLevelReferences(
G, NameVals, FSModRefsAbbrev,
5100 FSModVTableRefsAbbrev);
5102 for (
const GlobalAlias &
A :
M.aliases()) {
5103 auto *Aliasee =
A.getAliaseeObject();
5119 for (
auto &S :
Index->typeIdCompatibleVtableMap()) {
5123 TypeIdCompatibleVtableAbbrev);
5127 if (
Index->getBlockCount())
5129 ArrayRef<uint64_t>{
Index->getBlockCount()});
5134void ModuleBitcodeWriterBase::writeGUIDList() {
5136 for (
const GlobalValue &GV :
M.global_values()) {
5137 auto MaybeGUID = GV.getGUIDIfAssigned();
5138 if (!MaybeGUID || *MaybeGUID == 0)
5141 if (ValueID >= GUIDs.
size())
5142 GUIDs.
resize(ValueID + 1);
5143 GUIDs[ValueID] = *MaybeGUID;
5146 auto Abbv = std::make_shared<BitCodeAbbrev>();
5150 unsigned GUIDListAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5152 SmallVector<uint32_t> RecordVals;
5154 for (
auto GUID : GUIDs) {
5155 RecordVals.
push_back(
static_cast<uint32_t
>(GUID >> 32));
5156 RecordVals.
push_back(
static_cast<uint32_t
>(GUID));
5163void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
5172 auto Abbv = std::make_shared<BitCodeAbbrev>();
5178 unsigned ValueGuidAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5180 for (
const auto &GVI : valueIds()) {
5182 ArrayRef<uint32_t>{GVI.second,
5183 static_cast<uint32_t
>(GVI.first >> 32),
5184 static_cast<uint32_t
>(GVI.first)},
5190 if (!StackIds.empty()) {
5191 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
5198 unsigned StackIdAbbvId = Stream.
EmitAbbrev(std::move(StackIdAbbv));
5199 SmallVector<uint32_t> Vals;
5200 Vals.
reserve(StackIds.size() * 2);
5201 for (
auto Id : StackIds) {
5202 Vals.
push_back(
static_cast<uint32_t
>(Id >> 32));
5203 Vals.
push_back(
static_cast<uint32_t
>(Id));
5209 Abbv = std::make_shared<BitCodeAbbrev>();
5223 unsigned FSCallsProfileAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5226 Abbv = std::make_shared<BitCodeAbbrev>();
5233 unsigned FSModRefsAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5236 Abbv = std::make_shared<BitCodeAbbrev>();
5242 unsigned FSAliasAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5244 Abbv = std::make_shared<BitCodeAbbrev>();
5252 unsigned CallsiteAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5254 Abbv = std::make_shared<BitCodeAbbrev>();
5265 unsigned AllocAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5267 auto shouldImportValueAsDecl = [&](GlobalValueSummary *GVS) ->
bool {
5268 if (DecSummaries ==
nullptr)
5270 return DecSummaries->
count(GVS);
5278 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
5280 SmallVector<uint64_t, 64> NameVals;
5284 std::set<GlobalValue::GUID> ReferencedTypeIds;
5288 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
5298 NameVals.
push_back(S.getOriginalName());
5303 DenseMap<CallStackId, LinearCallStackId> CallStackPos;
5305 Abbv = std::make_shared<BitCodeAbbrev>();
5310 unsigned RadixAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5317 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks;
5318 forEachSummary([&](GVInfo
I,
bool IsAliasee) {
5324 GlobalValueSummary *S =
I.second;
5337 return StackIdIndicesToIndex[
I];
5343 if (!CallStacks.
empty()) {
5353 DenseSet<GlobalValue::GUID> DefOrUseGUIDs;
5354 forEachSummary([&](GVInfo
I,
bool IsAliasee) {
5355 GlobalValueSummary *S =
I.second;
5357 DefOrUseGUIDs.
insert(
I.first);
5358 for (
const ValueInfo &VI : S->
refs())
5359 DefOrUseGUIDs.
insert(
VI.getGUID());
5361 auto ValueId = getValueId(
I.first);
5363 SummaryToValueIdMap[S] = *ValueId;
5381 NameVals.
push_back(ModuleIdMap[
VS->modulePath()]);
5385 for (
auto &RI :
VS->refs()) {
5386 auto RefValueId = getValueId(RI.getGUID());
5396 MaybeEmitOriginalName(*S);
5400 auto GetValueId = [&](
const ValueInfo &
VI) -> std::optional<unsigned> {
5402 return std::nullopt;
5403 return getValueId(
VI.getGUID());
5412 NameVals.
push_back(ModuleIdMap[
FS->modulePath()]);
5425 unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;
5426 for (
auto &RI :
FS->refs()) {
5427 auto RefValueId = getValueId(RI.getGUID());
5431 if (RI.isReadOnly())
5433 else if (RI.isWriteOnly())
5437 NameVals[6] =
Count;
5438 NameVals[7] = RORefCnt;
5439 NameVals[8] = WORefCnt;
5441 for (
auto &EI :
FS->calls()) {
5444 std::optional<unsigned> CallValueId = GetValueId(EI.first);
5453 FSCallsProfileAbbrev);
5457 Stream, FS, CallsiteAbbrev, AllocAbbrev, 0,
5460 [&](
const ValueInfo &VI) ->
unsigned {
5461 std::optional<unsigned> ValueID = GetValueId(VI);
5476 return StackIdIndicesToIndex[
I];
5478 false, CallStackPos, CallStackCount);
5480 MaybeEmitOriginalName(*S);
5483 for (
auto *AS : Aliases) {
5484 auto AliasValueId = SummaryToValueIdMap[AS];
5493 auto AliaseeValueId =
5500 MaybeEmitOriginalName(*AS);
5508 auto EmitCfiFunctions = [&](
const CfiFunctionIndex &CfiIndex,
5510 if (CfiIndex.
empty())
5514 for (StringRef Name : Names)
5517 if (Functions.
empty())
5520 for (
const auto &Record : Functions) {
5535 for (
auto &
T : ReferencedTypeIds) {
5536 auto TidIter =
Index.typeIds().equal_range(
T);
5537 for (
const auto &[GUID, TypeIdPair] :
make_range(TidIter)) {
5545 if (
Index.getBlockCount())
5547 ArrayRef<uint64_t>{
Index.getBlockCount()});
5558 auto Abbv = std::make_shared<BitCodeAbbrev>();
5562 auto StringAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5564 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
5567 Abbv = std::make_shared<BitCodeAbbrev>();
5570 auto EpochAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5576void ModuleBitcodeWriter::writeModuleHash(StringRef View) {
5581 Hasher.
update(ArrayRef<uint8_t>(
5582 reinterpret_cast<const uint8_t *
>(
View.data()),
View.size()));
5583 std::array<uint8_t, 20> Hash = Hasher.
result();
5584 for (
int Pos = 0; Pos < 20; Pos += 4) {
5597void ModuleBitcodeWriter::write() {
5605 writeModuleVersion();
5614 writeAttributeGroupTable();
5617 writeAttributeTable();
5626 writeModuleConstants();
5629 writeModuleMetadataKinds();
5632 writeModuleMetadata();
5636 writeUseListBlock(
nullptr);
5638 writeOperandBundleTags();
5639 writeSyncScopeNames();
5642 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
5644 if (!
F.isDeclaration())
5645 writeFunction(
F, FunctionToBitcodeIndex);
5650 writePerModuleGlobalValueSummary();
5652 writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
5680 unsigned CPUType = ~0U;
5687 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
5688 DARWIN_CPU_TYPE_X86 = 7,
5689 DARWIN_CPU_TYPE_ARM = 12,
5690 DARWIN_CPU_TYPE_POWERPC = 18
5695 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
5697 CPUType = DARWIN_CPU_TYPE_X86;
5699 CPUType = DARWIN_CPU_TYPE_POWERPC;
5701 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
5703 CPUType = DARWIN_CPU_TYPE_ARM;
5707 "Expected header size to be reserved");
5712 unsigned Position = 0;
5720 while (Buffer.
size() & 15)
5727 Stream.
Emit((
unsigned)
'B', 8);
5728 Stream.
Emit((
unsigned)
'C', 8);
5729 Stream.
Emit(0x0, 4);
5730 Stream.
Emit(0xC, 4);
5731 Stream.
Emit(0xE, 4);
5732 Stream.
Emit(0xD, 4);
5750 auto Abbv = std::make_shared<BitCodeAbbrev>();
5753 auto AbbrevNo = Stream->
EmitAbbrev(std::move(Abbv));
5761 assert(!WroteStrtab && !WroteSymtab);
5767 if (M->getModuleInlineAsm().empty())
5771 const Triple TT(M->getTargetTriple());
5773 if (!
T || !
T->hasMCAsmParser())
5795 std::vector<char> Strtab;
5796 StrtabBuilder.finalizeInOrder();
5797 Strtab.resize(StrtabBuilder.getSize());
5798 StrtabBuilder.write((
uint8_t *)Strtab.data());
5801 {Strtab.data(), Strtab.size()});
5812 bool ShouldPreserveUseListOrder,
5821 assert(M.isMaterialized());
5822 Mods.push_back(
const_cast<Module *
>(&M));
5824 ModuleBitcodeWriter ModuleWriter(M, StrtabBuilder, *Stream,
5825 ShouldPreserveUseListOrder, Index,
5826 GenerateHash, ModHash);
5827 ModuleWriter.write();
5834 IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index, DecSummaries,
5835 ModuleToSummariesForIndex);
5836 IndexWriter.write();
5841 bool ShouldPreserveUseListOrder,
5845 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
5847 Writer.writeSymtab();
5848 Writer.writeStrtab();
5850 Triple TT(M.getTargetTriple());
5851 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) {
5862 Out.write(Buffer.
data(), Buffer.
size());
5869void IndexBitcodeWriter::write() {
5872 writeModuleVersion();
5878 writeCombinedGlobalValueSummary();
5895 Writer.
writeIndex(&Index, ModuleToSummariesForIndex, DecSummaries);
5898 Out.write((
char *)&Buffer.
front(), Buffer.
size());
5904class ThinLinkBitcodeWriter :
public ModuleBitcodeWriterBase {
5914 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
5916 ModHash(&ModHash) {}
5921 void writeSimplifiedModuleInfo();
5931void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
5943 auto Abbv = std::make_shared<BitCodeAbbrev>();
5946 Abbv->Add(AbbrevOpToUse);
5947 unsigned FilenameAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5949 for (
const auto P :
M.getSourceFileName())
6015void ThinLinkBitcodeWriter::write() {
6018 writeModuleVersion();
6020 writeSimplifiedModuleInfo();
6022 writePerModuleGlobalValueSummary();
6039 assert(M.isMaterialized());
6040 Mods.push_back(
const_cast<Module *
>(&M));
6042 ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
6044 ThinLinkWriter.write();
6061 Out.write((
char *)&Buffer.
front(), Buffer.
size());
6065 switch (
T.getObjectFormat()) {
6067 return "__LLVM,__bitcode";
6092 switch (
T.getObjectFormat()) {
6094 return "__LLVM,__cmdline";
6120 const std::vector<uint8_t> &CmdArgs) {
6125 Type *UsedElementType = Used ? Used->getValueType()->getArrayElementType()
6127 for (
auto *GV : UsedGlobals) {
6128 if (GV->getName() !=
"llvm.embedded.module" &&
6129 GV->getName() !=
"llvm.cmdline")
6134 Used->eraseFromParent();
6139 Triple T(M.getTargetTriple());
6168 M.getGlobalVariable(
"llvm.embedded.module",
true)) {
6169 assert(Old->hasZeroLiveUses() &&
6170 "llvm.embedded.module can only be used once in llvm.compiler.used");
6172 Old->eraseFromParent();
6174 GV->
setName(
"llvm.embedded.module");
6192 assert(Old->hasZeroLiveUses() &&
6193 "llvm.cmdline can only be used once in llvm.compiler.used");
6195 Old->eraseFromParent();
6201 if (UsedArray.
empty())
6209 NewUsed->setSection(
"llvm.metadata");
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void writeDIMacro(raw_ostream &Out, const DIMacro *N, AsmWriterContext &WriterCtx)
static void writeDIGlobalVariableExpression(raw_ostream &Out, const DIGlobalVariableExpression *N, AsmWriterContext &WriterCtx)
static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N, AsmWriterContext &WriterCtx)
static void writeDIFixedPointType(raw_ostream &Out, const DIFixedPointType *N, AsmWriterContext &WriterCtx)
static void writeDISubrangeType(raw_ostream &Out, const DISubrangeType *N, AsmWriterContext &WriterCtx)
static void writeDIStringType(raw_ostream &Out, const DIStringType *N, AsmWriterContext &WriterCtx)
static void writeDILayerLocList(raw_ostream &Out, const DILayerLocList *N, AsmWriterContext &WriterCtx)
static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N, AsmWriterContext &WriterCtx)
static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N, AsmWriterContext &WriterCtx)
static void writeDILayerLoc(raw_ostream &Out, const DILayerLoc *N, AsmWriterContext &WriterCtx)
static void writeDIModule(raw_ostream &Out, const DIModule *N, AsmWriterContext &WriterCtx)
static void writeDIFile(raw_ostream &Out, const DIFile *N, AsmWriterContext &)
static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N, AsmWriterContext &WriterCtx)
static void writeDILabel(raw_ostream &Out, const DILabel *N, AsmWriterContext &WriterCtx)
static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N, AsmWriterContext &WriterCtx)
static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N, AsmWriterContext &WriterCtx)
static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N, AsmWriterContext &WriterCtx)
static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N, AsmWriterContext &WriterCtx)
static void writeDILocation(raw_ostream &Out, const DILocation *DL, AsmWriterContext &WriterCtx)
static void writeDINamespace(raw_ostream &Out, const DINamespace *N, AsmWriterContext &WriterCtx)
static void writeDICommonBlock(raw_ostream &Out, const DICommonBlock *N, AsmWriterContext &WriterCtx)
static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N, AsmWriterContext &WriterCtx)
static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N, AsmWriterContext &WriterCtx)
static void writeDITemplateTypeParameter(raw_ostream &Out, const DITemplateTypeParameter *N, AsmWriterContext &WriterCtx)
static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N, AsmWriterContext &WriterCtx)
static void writeDIGenericSubrange(raw_ostream &Out, const DIGenericSubrange *N, AsmWriterContext &WriterCtx)
static void writeDISubrange(raw_ostream &Out, const DISubrange *N, AsmWriterContext &WriterCtx)
static void writeDIProperty(raw_ostream &Out, const DIProperty *N, AsmWriterContext &WriterCtx)
static void writeDILexicalBlockFile(raw_ostream &Out, const DILexicalBlockFile *N, AsmWriterContext &WriterCtx)
static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N, AsmWriterContext &)
static void writeMDTuple(raw_ostream &Out, const MDTuple *Node, AsmWriterContext &WriterCtx)
static void writeDIExpression(raw_ostream &Out, const DIExpression *N, AsmWriterContext &WriterCtx)
static void writeDIAssignID(raw_ostream &Out, const DIAssignID *DL, AsmWriterContext &WriterCtx)
static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N, AsmWriterContext &WriterCtx)
static void writeDIArgList(raw_ostream &Out, const DIArgList *N, AsmWriterContext &WriterCtx, bool FromValue=false)
static void writeDITemplateValueParameter(raw_ostream &Out, const DITemplateValueParameter *N, AsmWriterContext &WriterCtx)
static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N, AsmWriterContext &WriterCtx)
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
static void writeFunctionHeapProfileRecords(BitstreamWriter &Stream, FunctionSummary *FS, unsigned CallsiteAbbrev, unsigned AllocAbbrev, unsigned ContextIdAbbvId, bool PerModule, std::function< unsigned(const ValueInfo &VI)> GetValueID, std::function< unsigned(unsigned)> GetStackIndex, bool WriteContextSizeInfoIndex, DenseMap< CallStackId, LinearCallStackId > &CallStackPos, CallStackId &CallStackCount)
static unsigned serializeSanitizerMetadata(const GlobalValue::SanitizerMetadata &Meta)
static void writeTypeIdCompatibleVtableSummaryRecord(SmallVector< uint64_t, 64 > &NameVals, StringTableBuilder &StrtabBuilder, StringRef Id, const TypeIdCompatibleVtableInfo &Summary, ValueEnumerator &VE)
static void getReferencedTypeIds(FunctionSummary *FS, std::set< GlobalValue::GUID > &ReferencedTypeIds)
Collect type IDs from type tests used by function.
static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind)
static void collectMemProfCallStacks(FunctionSummary *FS, std::function< LinearFrameId(unsigned)> GetStackIndex, MapVector< CallStackId, llvm::SmallVector< LinearFrameId > > &CallStacks)
static unsigned getEncodedUnaryOpcode(unsigned Opcode)
static void emitSignedInt64(SmallVectorImpl< uint64_t > &Vals, uint64_t V)
static unsigned getEncodedVisibility(const GlobalValue &GV)
static uint64_t getOptimizationFlags(const Value *V)
static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage)
static cl::opt< bool > PreserveBitcodeUseListOrder("preserve-bc-uselistorder", cl::Hidden, cl::init(true), cl::desc("Preserve use-list order when writing LLVM bitcode."))
static unsigned getEncodedThreadLocalMode(const GlobalValue &GV)
static DenseMap< CallStackId, LinearCallStackId > writeMemoryProfileRadixTree(MapVector< CallStackId, llvm::SmallVector< LinearFrameId > > &&CallStacks, BitstreamWriter &Stream, unsigned RadixAbbrev)
static void writeIdentificationBlock(BitstreamWriter &Stream)
Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the current llvm version,...
static unsigned getEncodedCastOpcode(unsigned Opcode)
static cl::opt< uint32_t > FlushThreshold("bitcode-flush-threshold", cl::Hidden, cl::init(512), cl::desc("The threshold (unit M) for flushing LLVM bitcode."))
static unsigned getEncodedOrdering(AtomicOrdering Ordering)
static unsigned getEncodedUnnamedAddr(const GlobalValue &GV)
static unsigned getEncodedComdatSelectionKind(const Comdat &C)
static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags, bool ImportAsDecl=false)
static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl< char > &Buffer, const Triple &TT)
If generating a bc file on darwin, we have to emit a header and trailer to make it compatible with th...
static void writeBitcodeHeader(BitstreamWriter &Stream)
Helper to write the header common to all bitcode files.
static void writeWholeProgramDevirtResolutionByArg(SmallVector< uint64_t, 64 > &NameVals, const std::vector< uint64_t > &args, const WholeProgramDevirtResolution::ByArg &ByArg)
static void emitConstantRange(SmallVectorImpl< uint64_t > &Record, const ConstantRange &CR, bool EmitBitWidth)
static StringEncoding getStringEncoding(StringRef Str)
Determine the encoding to use for the given string name and length.
static uint64_t getEncodedGVarFlags(GlobalVarSummary::GVarFlags Flags)
static const char * getSectionNameForCommandline(const Triple &T)
static cl::opt< unsigned > IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25), cl::desc("Number of metadatas above which we emit an index " "to enable lazy-loading"))
static void writeTypeIdSummaryRecord(SmallVector< uint64_t, 64 > &NameVals, StringTableBuilder &StrtabBuilder, StringRef Id, const TypeIdSummary &Summary)
static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream, FunctionSummary *FS, Fn GetValueID)
Write the function type metadata related records that need to appear before a function summary entry ...
static uint64_t getEncodedHotnessCallEdgeInfo(const CalleeInfo &CI)
static void emitWideAPInt(SmallVectorImpl< uint64_t > &Vals, const APInt &A)
static void writeStringRecord(BitstreamWriter &Stream, unsigned Code, StringRef Str, unsigned AbbrevToUse)
static unsigned getEncodedRMWOperation(const AtomicRMWInst &I)
static void writeWholeProgramDevirtResolution(SmallVector< uint64_t, 64 > &NameVals, StringTableBuilder &StrtabBuilder, uint64_t Id, const WholeProgramDevirtResolution &Wpd)
static unsigned getEncodedDLLStorageClass(const GlobalValue &GV)
static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl< char > &Buffer, uint32_t &Position)
static const char * getSectionNameForBitcode(const Triple &T)
static cl::opt< bool > CombinedIndexMemProfContext("combined-index-memprof-context", cl::Hidden, cl::init(true), cl::desc(""))
static unsigned getEncodedBinaryOpcode(unsigned Opcode)
static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
static MaybeAlign getAlign(Value *Ptr)
Module.h This file contains the declarations for the Module class.
static cl::opt< LTOBitcodeEmbedding > EmbedBitcode("lto-embed-bitcode", cl::init(LTOBitcodeEmbedding::DoNotEmbed), cl::values(clEnumValN(LTOBitcodeEmbedding::DoNotEmbed, "none", "Do not embed"), clEnumValN(LTOBitcodeEmbedding::EmbedOptimized, "optimized", "Embed after all optimization passes"), clEnumValN(LTOBitcodeEmbedding::EmbedPostMergePreOptimized, "post-merge-pre-opt", "Embed post merge, but before optimizations")), cl::desc("Embed LLVM bitcode in object files produced by LTO"))
Machine Check Debug Module
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallString class.
This file defines the SmallVector class.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static const uint32_t IV[8]
Class for arbitrary precision integers.
unsigned getActiveWords() const
Compute the number of active words in the value of this APInt.
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
int64_t getSExtValue() const
Get sign extended value.
const GlobalValueSummary & getAliasee() const
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
bool isUsedWithInAlloca() const
Return true if this alloca is used as an inalloca argument to a call.
unsigned getAddressSpace() const
Return the address space for the allocation.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
bool empty() const
Check if the array is empty.
Class to represent array types.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
an instruction that atomically reads a memory location, combines it with another value,...
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
bool hasAttributes() const
Return true if attributes exists in this set.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
@ TombstoneKey
Use as Tombstone key for DenseMap of AttrKind.
@ None
No attributes have been set.
@ EmptyKey
Use as Empty key for DenseMap of AttrKind.
@ EndAttrKinds
Sentinel value useful for loops.
BitCodeAbbrevOp - This describes one or more operands in an abbreviation.
static bool isChar6(char C)
isChar6 - Return true if this character is legal in the Char6 encoding.
LLVM_ABI void writeThinLinkBitcode(const Module &M, const ModuleSummaryIndex &Index, const ModuleHash &ModHash)
Write the specified thin link bitcode file (i.e., the minimized bitcode file) to the buffer specified...
LLVM_ABI void writeIndex(const ModuleSummaryIndex *Index, const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex, const GVSummaryPtrSet *DecSummaries)
LLVM_ABI void copyStrtab(StringRef Strtab)
Copy the string table for another module into this bitcode file.
LLVM_ABI void writeStrtab()
Write the bitcode file's string table.
LLVM_ABI ~BitcodeWriter()
LLVM_ABI void writeSymtab()
Attempt to write a symbol table to the bitcode file.
LLVM_ABI void writeModule(const Module &M, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false, ModuleHash *ModHash=nullptr)
Write the specified module to the buffer specified at construction time.
LLVM_ABI BitcodeWriter(SmallVectorImpl< char > &Buffer)
Create a BitcodeWriter that writes to Buffer.
unsigned EmitAbbrev(std::shared_ptr< BitCodeAbbrev > Abbv)
Emits the abbreviation Abbv to the stream.
void markAndBlockFlushing()
For scenarios where the user wants to access a section of the stream to (for example) compute some ch...
StringRef getMarkedBufferAndResumeFlushing()
resumes flushing, but does not flush, and returns the section in the internal buffer starting from th...
void EmitRecord(unsigned Code, const Container &Vals, unsigned Abbrev=0)
EmitRecord - Emit the specified record to the stream, using an abbrev if we have one to compress the ...
void Emit(uint32_t Val, unsigned NumBits)
void EmitRecordWithBlob(unsigned Abbrev, const Container &Vals, StringRef Blob)
EmitRecordWithBlob - Emit the specified record to the stream, using an abbrev that includes a blob at...
unsigned EmitBlockInfoAbbrev(unsigned BlockID, std::shared_ptr< BitCodeAbbrev > Abbv)
EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified BlockID.
void EnterBlockInfoBlock()
EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
void BackpatchWord(uint64_t BitNo, unsigned Val)
void BackpatchWord64(uint64_t BitNo, uint64_t Val)
void EnterSubblock(unsigned BlockID, unsigned CodeLen)
uint64_t GetCurrentBitNo() const
Retrieve the current position in the stream, in bits.
void EmitRecordWithAbbrev(unsigned Abbrev, const Container &Vals)
EmitRecordWithAbbrev - Emit a record with the specified abbreviation.
static LLVM_ABI BlockAddress * lookup(const BasicBlock *BB)
Lookup an existing BlockAddress constant for the given BasicBlock.
OperandBundleUse getOperandBundleAt(unsigned Index) const
Return the operand bundle at a specific index.
unsigned getNumOperandBundles() const
Return the number of operand bundles associated with this User.
CallingConv::ID getCallingConv() const
Value * getCalledOperand() const
Value * getArgOperand(unsigned i) const
FunctionType * getFunctionType() const
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
bool hasOperandBundles() const
Return true if this User has any operand bundles.
BasicBlock * getIndirectDest(unsigned i) const
BasicBlock * getDefaultDest() const
unsigned getNumIndirectDests() const
Return the number of callbr indirect dest labels.
bool isNoTailCall() const
bool isMustTailCall() const
auto getNamesForGUID(GlobalValue::GUID GUID) const
get the name(s) associated with a given ThinLTO GUID.
@ Largest
The linker will choose the largest COMDAT.
@ SameSize
The data referenced by the COMDAT must be the same size.
@ Any
The linker may choose any COMDAT.
@ NoDeduplicate
No deduplication is performed.
@ ExactMatch
The data referenced by the COMDAT must be the same.
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
This class represents a range of values.
const APInt & getLower() const
Return the lower value for this range.
const APInt & getUpper() const
Return the upper value for this range.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
This is an important base class in LLVM.
DebugLoc getDebugLoc() const
LLVM_ABI DIAssignID * getAssignID() const
DIExpression * getExpression() const
DILocalVariable * getVariable() const
bool isDbgDeclareValue() const
Metadata * getRawLocation() const
Returns the metadata operand for the first location description.
bool isDbgDeclare() const
Metadata * getRawAddress() const
DIExpression * getAddressExpression() const
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Lightweight error class with error context and mandatory checking.
Function summary information to aid decisions and implementation of importing.
LLVM_ABI void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
Appends all metadata attached to this value to MDs, sorting by KindID.
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
GVFlags flags() const
Get the flags for this GlobalValue (see struct GVFlags).
StringRef modulePath() const
Get the path to the module containing this function.
ArrayRef< ValueInfo > refs() const
Return the list of values referenced by this global value definition.
VisibilityTypes getVisibility() const
static bool isLocalLinkage(LinkageTypes Linkage)
LinkageTypes getLinkage() const
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
ThreadLocalMode getThreadLocalMode() const
@ DLLExportStorageClass
Function to be accessible from DLL.
@ DLLImportStorageClass
Function to be imported from DLL.
@ DefaultVisibility
The GV is visible.
@ HiddenVisibility
The GV is hidden.
@ ProtectedVisibility
The GV is protected.
UnnamedAddr getUnnamedAddr() const
LinkageTypes
An enumeration for the kinds of linkage for global values.
@ PrivateLinkage
Like Internal, but omit from symbol table.
@ CommonLinkage
Tentative definitions.
@ InternalLinkage
Rename collisions when linking (static functions).
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
@ WeakODRLinkage
Same, but only replaced by something equivalent.
@ ExternalLinkage
Externally visible function.
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
@ AppendingLinkage
Special purpose, only applies to global arrays.
@ AvailableExternallyLinkage
Available for inspection, not emission.
@ ExternalWeakLinkage
ExternalWeak linkage description.
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
DLLStorageClassTypes getDLLStorageClass() const
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
idx_iterator idx_end() const
idx_iterator idx_begin() const
bool isCleanup() const
Return 'true' if this landingpad instruction is a cleanup.
unsigned getNumClauses() const
Get the number of clauses for this landing pad.
bool isCatch(unsigned Idx) const
Return 'true' if the clause and index Idx is a catch clause.
Constant * getClause(unsigned Idx) const
Get the value of the clause at index Idx.
This class implements a map that also provides access to all stored values in a deterministic order.
size_t getBufferSize() const
const char * getBufferStart() const
const char * getBufferEnd() const
Class to hold module path string table and global value map, and encapsulate methods for operating on...
static constexpr uint64_t BitcodeSummaryVersion
A Module instance is used to store all the information related to an LLVM module.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Digest more data.
LLVM_ABI std::array< uint8_t, 20 > result()
Return the current raw 160-bits SHA1 for the digested data since the last call to init().
size_type size() const
Determine the number of elements in the SetVector.
bool empty() const
Determine if the SetVector is empty or not.
bool insert(const value_type &X)
Insert a new element into the SetVector.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void append(StringRef RHS)
Append from a StringRef.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
const ValueTy & getValue() const
Represent a constant reference to a string, i.e.
constexpr bool empty() const
Check if the string is empty.
constexpr size_t size() const
Get the string size.
Utility for building string tables with deduplicated suffixes.
LLVM_ABI size_t add(CachedHashStringRef S, uint8_t Priority=0)
Add a string to the builder.
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
The instances of the Type class are immutable: once they are created, they are never changed.
bool isX86_FP80Ty() const
Return true if this is x86 long double.
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
bool isFP128Ty() const
Return true if this is 'fp128'.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
std::vector< std::pair< const Value *, unsigned > > ValueList
unsigned getTypeID(Type *T) const
unsigned getMetadataID(const Metadata *MD) const
UseListOrderStack UseListOrders
ArrayRef< const Metadata * > getNonMDStrings() const
Get the non-MDString metadata for this block.
unsigned getInstructionID(const Instruction *I) const
unsigned getAttributeListID(AttributeList PAL) const
void incorporateFunction(const Function &F)
incorporateFunction/purgeFunction - If you'd like to deal with a function, use these two methods to g...
void getFunctionConstantRange(unsigned &Start, unsigned &End) const
getFunctionConstantRange - Return the range of values that corresponds to function-local constants.
unsigned getAttributeGroupID(IndexAndAttrSet Group) const
bool hasMDs() const
Check whether the current block has any metadata to emit.
unsigned getComdatID(const Comdat *C) const
uint64_t computeBitsRequiredForTypeIndices() const
unsigned getValueID(const Value *V) const
unsigned getMetadataOrNullID(const Metadata *MD) const
const std::vector< IndexAndAttrSet > & getAttributeGroups() const
const ValueList & getValues() const
unsigned getGlobalBasicBlockID(const BasicBlock *BB) const
getGlobalBasicBlockID - This returns the function-specific ID for the specified basic block.
void setInstructionID(const Instruction *I)
const std::vector< const BasicBlock * > & getBasicBlocks() const
const std::vector< AttributeList > & getAttributeLists() const
bool shouldPreserveUseListOrder() const
const ComdatSetType & getComdats() const
std::vector< Type * > TypeList
ArrayRef< const Metadata * > getMDStrings() const
Get the MDString metadata for this block.
std::pair< unsigned, AttributeSet > IndexAndAttrSet
Attribute groups as encoded in bitcode are almost AttributeSets, but they include the AttributeList i...
const TypeList & getTypes() const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
LLVMContext & getContext() const
All values hold a context through their type.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
std::pair< iterator, bool > insert(const ValueT &V)
void build(llvm::MapVector< CallStackId, llvm::SmallVector< FrameIdTy > > &&MemProfCallStackData, const llvm::DenseMap< FrameIdTy, LinearFrameId > *MemProfFrameIndexes, llvm::DenseMap< FrameIdTy, FrameStat > &FrameHistogram)
This class implements an extremely fast bulk output stream that can only output to a stream.
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
Predicate getPredicate(unsigned Condition, unsigned Hint)
Return predicate consisting of specified condition and hint bits.
@ CE
Windows NT (Windows on ARM)
@ TYPE_CODE_OPAQUE_POINTER
@ METADATA_TEMPLATE_VALUE
@ METADATA_LEXICAL_BLOCK_FILE
@ METADATA_SUBROUTINE_TYPE
@ METADATA_GLOBAL_DECL_ATTACHMENT
@ METADATA_IMPORTED_ENTITY
@ METADATA_GENERIC_SUBRANGE
@ METADATA_COMPOSITE_TYPE
@ METADATA_FIXED_POINT_TYPE
@ METADATA_GLOBAL_VAR_EXPR
GlobalValueSummarySymtabCodes
@ FS_CONTEXT_RADIX_TREE_ARRAY
@ FS_COMBINED_GLOBALVAR_INIT_REFS
@ FS_TYPE_CHECKED_LOAD_VCALLS
@ FS_COMBINED_ORIGINAL_NAME
@ FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_CONST_VCALL
@ FS_PERMODULE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_VCALLS
@ FS_COMBINED_ALLOC_INFO_NO_CONTEXT
@ FS_COMBINED_CALLSITE_INFO
@ FS_PERMODULE_CALLSITE_INFO
@ FS_PERMODULE_ALLOC_INFO
@ FS_TYPE_CHECKED_LOAD_CONST_VCALL
@ IDENTIFICATION_CODE_EPOCH
@ IDENTIFICATION_CODE_STRING
@ CST_CODE_DSO_LOCAL_EQUIVALENT
@ CST_CODE_CE_GEP_WITH_INRANGE
@ COMDAT_SELECTION_KIND_LARGEST
@ COMDAT_SELECTION_KIND_ANY
@ COMDAT_SELECTION_KIND_SAME_SIZE
@ COMDAT_SELECTION_KIND_EXACT_MATCH
@ COMDAT_SELECTION_KIND_NO_DUPLICATES
@ ATTR_KIND_STACK_PROTECT
@ ATTR_KIND_STACK_PROTECT_STRONG
@ ATTR_KIND_SANITIZE_MEMORY
@ ATTR_KIND_OPTIMIZE_FOR_SIZE
@ ATTR_KIND_FNRETTHUNK_EXTERN
@ ATTR_KIND_NO_DIVERGENCE_SOURCE
@ ATTR_KIND_SANITIZE_ADDRESS
@ ATTR_KIND_NO_IMPLICIT_FLOAT
@ ATTR_KIND_DEAD_ON_UNWIND
@ ATTR_KIND_STACK_ALIGNMENT
@ ATTR_KIND_STACK_PROTECT_REQ
@ ATTR_KIND_NULL_POINTER_IS_VALID
@ ATTR_KIND_SANITIZE_HWADDRESS
@ ATTR_KIND_RETURNS_TWICE
@ ATTR_KIND_SHADOWCALLSTACK
@ ATTR_KIND_OPT_FOR_FUZZING
@ ATTR_KIND_DENORMAL_FPENV
@ ATTR_KIND_SANITIZE_NUMERICAL_STABILITY
@ ATTR_KIND_SANITIZE_CONCURRENCY
@ ATTR_KIND_ALLOCATED_POINTER
@ ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION
@ ATTR_KIND_CORO_ELIDE_SAFE
@ ATTR_KIND_NON_LAZY_BIND
@ ATTR_KIND_DEREFERENCEABLE
@ ATTR_KIND_LIKELY_MODULE_LOCAL
@ ATTR_KIND_OPTIMIZE_NONE
@ ATTR_KIND_HYBRID_PATCHABLE
@ ATTR_KIND_DEREFERENCEABLE_OR_NULL
@ ATTR_KIND_SANITIZE_REALTIME
@ ATTR_KIND_SPECULATIVE_LOAD_HARDENING
@ ATTR_KIND_ALWAYS_INLINE
@ ATTR_KIND_SANITIZE_TYPE
@ ATTR_KIND_PRESPLIT_COROUTINE
@ ATTR_KIND_SANITIZE_ALLOC_TOKEN
@ ATTR_KIND_NO_SANITIZE_COVERAGE
@ ATTR_KIND_NO_CREATE_UNDEF_OR_POISON
@ ATTR_KIND_DEAD_ON_RETURN
@ ATTR_KIND_SANITIZE_REALTIME_BLOCKING
@ ATTR_KIND_NO_SANITIZE_BOUNDS
@ ATTR_KIND_SANITIZE_MEMTAG
@ ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE
@ ATTR_KIND_SANITIZE_THREAD
@ ATTR_KIND_OPTIMIZE_FOR_DEBUGGING
@ SYNC_SCOPE_NAMES_BLOCK_ID
@ PARAMATTR_GROUP_BLOCK_ID
@ IDENTIFICATION_BLOCK_ID
@ GLOBALVAL_SUMMARY_BLOCK_ID
@ FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID
@ OPERAND_BUNDLE_TAGS_BLOCK_ID
@ MODULE_CODE_SOURCE_FILENAME
@ MODULE_CODE_SECTIONNAME
@ MODULE_CODE_ASM_PROPERTY
@ FUNC_CODE_INST_CATCHRET
@ FUNC_CODE_INST_LANDINGPAD
@ FUNC_CODE_INST_EXTRACTVAL
@ FUNC_CODE_INST_CATCHPAD
@ FUNC_CODE_INST_CATCHSWITCH
@ FUNC_CODE_INST_CLEANUPRET
@ FUNC_CODE_DEBUG_RECORD_VALUE
@ FUNC_CODE_INST_LOADATOMIC
@ FUNC_CODE_DEBUG_RECORD_ASSIGN
@ FUNC_CODE_INST_STOREATOMIC
@ FUNC_CODE_INST_BITEXTRACT
@ FUNC_CODE_INST_ATOMICRMW
@ FUNC_CODE_DEBUG_RECORD_DECLARE_VALUE
@ FUNC_CODE_DEBUG_LOC_AGAIN
@ FUNC_CODE_INST_EXTRACTELT
@ FUNC_CODE_INST_INDIRECTBR
@ FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE
@ FUNC_CODE_INST_INSERTVAL
@ FUNC_CODE_DECLAREBLOCKS
@ FUNC_CODE_DEBUG_RECORD_LABEL
@ FUNC_CODE_INST_INSERTELT
@ FUNC_CODE_BLOCKADDR_USERS
@ FUNC_CODE_INST_CLEANUPPAD
@ FUNC_CODE_INST_SHUFFLEVEC
@ FUNC_CODE_INST_UNREACHABLE
@ FUNC_CODE_INST_BITINSERT
@ FUNC_CODE_DEBUG_RECORD_DECLARE
@ FUNC_CODE_OPERAND_BUNDLE
@ FIRST_APPLICATION_ABBREV
@ PARAMATTR_GRP_CODE_ENTRY
initializer< Ty > init(const Ty &Val)
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
LLVM_ABI Error build(ArrayRef< Module * > Mods, SmallVector< char, 0 > &Symtab, StringTableBuilder &StrtabBuilder, BumpPtrAllocator &Alloc)
Fills in Symtab and StrtabBuilder with a valid symbol and string table for Mods.
llvm::unique_function< void(llvm::Expected< T >)> Callback
A Callback<T> is a void function that accepts Expected<T>.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract_or_null(Y &&MD)
Extract a Value from Metadata, allowing null.
LLVM_ABI bool metadataIncludesAllContextSizeInfo()
Whether the alloc memeprof metadata will include context size info for all MIBs.
template LLVM_ABI llvm::DenseMap< LinearFrameId, FrameStat > computeFrameHistogram< LinearFrameId >(llvm::MapVector< CallStackId, llvm::SmallVector< LinearFrameId > > &MemProfCallStackData)
LLVM_ABI bool metadataMayIncludeContextSizeInfo()
Whether the alloc memprof metadata may include context size info for some MIBs (but possibly not all)...
NodeAddr< CodeNode * > Code
void write32le(void *P, uint32_t V)
uint32_t read32be(const void *P)
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
void stable_sort(R &&Range)
StringMapEntry< Value * > ValueName
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
unsigned encode(MaybeAlign A)
Returns a representation of the alignment that encodes undefined as 0.
LLVM_ABI void WriteBitcodeToFile(const Module &M, raw_ostream &Out, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false, ModuleHash *ModHash=nullptr)
Write the specified module to the specified raw output stream.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
LLVM_ABI void writeThinLinkBitcodeToFile(const Module &M, raw_ostream &Out, const ModuleSummaryIndex &Index, const ModuleHash &ModHash)
Write the specified thin link bitcode file (i.e., the minimized bitcode file) to the given raw output...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI void writeIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out, const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex=nullptr, const GVSummaryPtrSet *DecSummaries=nullptr)
Write the specified module summary index to the given raw output stream, where it will be written in ...
LLVM_ABI void embedBitcodeInModule(Module &M, MemoryBufferRef Buf, bool EmbedBitcode, bool EmbedCmdline, const std::vector< uint8_t > &CmdArgs)
If EmbedBitcode is set, save a copy of the llvm IR as data in the __LLVM,__bitcode section (....
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
std::map< std::string, GVSummaryMapTy, std::less<> > ModuleToSummariesForIndexTy
Map of a module name to the GUIDs and summaries we will import from that module.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
AtomicOrdering
Atomic ordering for LLVM's memory model.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt copy(R &&Range, OutputIt Out)
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
bool isBitcode(const unsigned char *BufPtr, const unsigned char *BufEnd)
isBitcode - Return true if the given bytes are the magic bytes for LLVM IR bitcode,...
SmallPtrSet< GlobalValueSummary *, 0 > GVSummaryPtrSet
A set of global value summary pointers.
void consumeError(Error Err)
Consume a Error without doing anything.
LLVM_ABI Error write(DWPWriter &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue, Dwarf64StrOffsetsPromotion StrOffsetsOptValue, raw_pwrite_stream *OS=nullptr)
LLVM_ABI GlobalVariable * collectUsedGlobalVariables(const Module &M, SmallVectorImpl< GlobalValue * > &Vec, bool CompilerUsed)
Given "llvm.used" or "llvm.compiler.used" as a global name, collect the initializer elements of that ...
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
This struct is a compact representation of a valid (non-zero power of two) alignment.
static void set(StorageType &Packed, typename Bitfield::Type Value)
Sets the typed value in the provided Packed value.
Class to accumulate and hold information about a callee.
Flags specific to function summaries.
static constexpr uint32_t RangeWidth
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
static LLVM_ABI const Target * lookupTarget(const Triple &TheTriple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
Struct that holds a reference to a particular GUID in a global value summary.
uint64_t Info
Additional information for the resolution:
enum llvm::WholeProgramDevirtResolution::ByArg::Kind TheKind
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
std::string SingleImplName