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."));
134 VST_BBENTRY_6_ABBREV,
138 CONSTANTS_INTEGER_ABBREV,
139 CONSTANTS_BYTE_ABBREV,
140 CONSTANTS_CE_CAST_Abbrev,
141 CONSTANTS_NULL_Abbrev,
145 FUNCTION_INST_STORE_ABBREV,
146 FUNCTION_INST_UNOP_ABBREV,
147 FUNCTION_INST_UNOP_FLAGS_ABBREV,
148 FUNCTION_INST_BINOP_ABBREV,
149 FUNCTION_INST_BINOP_FLAGS_ABBREV,
150 FUNCTION_INST_CAST_ABBREV,
151 FUNCTION_INST_CAST_FLAGS_ABBREV,
152 FUNCTION_INST_RET_VOID_ABBREV,
153 FUNCTION_INST_RET_VAL_ABBREV,
154 FUNCTION_INST_BR_UNCOND_ABBREV,
155 FUNCTION_INST_BR_COND_ABBREV,
156 FUNCTION_INST_UNREACHABLE_ABBREV,
157 FUNCTION_INST_GEP_ABBREV,
158 FUNCTION_INST_CMP_ABBREV,
159 FUNCTION_INST_CMP_FLAGS_ABBREV,
160 FUNCTION_DEBUG_RECORD_VALUE_ABBREV,
161 FUNCTION_DEBUG_LOC_ABBREV,
162 FUNCTION_DEBUG_LOC_LAYERS_ABBREV,
167class BitcodeWriterBase {
170 BitstreamWriter &Stream;
172 StringTableBuilder &StrtabBuilder;
177 BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
178 : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
181 void writeModuleVersion();
184void BitcodeWriterBase::writeModuleVersion() {
191class ModuleBitcodeWriterBase :
public BitcodeWriterBase {
200 const ModuleSummaryIndex *Index;
205 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
208 unsigned GlobalValueId;
217 ModuleBitcodeWriterBase(
const Module &M, StringTableBuilder &StrtabBuilder,
218 BitstreamWriter &Stream,
219 bool ShouldPreserveUseListOrder,
220 const ModuleSummaryIndex *Index)
221 : BitcodeWriterBase(Stream, StrtabBuilder),
M(
M),
224 : ShouldPreserveUseListOrder),
235 for (
const auto &GUIDSummaryLists :
236 Index->sortedGlobalValueSummariesRange())
238 for (
auto &Summary : GUIDSummaryLists.second.getSummaryList())
244 for (auto &CallEdge : FS->calls())
245 if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())
246 assignValueId(CallEdge.first.getGUID());
252 for (auto &RefEdge : FS->refs())
253 if (!RefEdge.haveGVs() || !RefEdge.getValue())
254 assignValueId(RefEdge.getGUID());
259 void writePerModuleGlobalValueSummary();
260 void writeGUIDList();
263 void writePerModuleFunctionSummaryRecord(
264 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
265 unsigned ValueID,
unsigned FSCallsProfileAbbrev,
unsigned CallsiteAbbrev,
266 unsigned AllocAbbrev,
unsigned ContextIdAbbvId,
const Function &
F,
267 DenseMap<CallStackId, LinearCallStackId> &CallStackPos,
269 void writeModuleLevelReferences(
const GlobalVariable &V,
270 SmallVector<uint64_t, 64> &NameVals,
271 unsigned FSModRefsAbbrev,
272 unsigned FSModVTableRefsAbbrev);
275 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
279 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
282 assert(VMI != GUIDToValueIdMap.end() &&
283 "GUID does not have assigned value Id");
288 unsigned getValueId(ValueInfo VI) {
289 if (!
VI.haveGVs() || !
VI.getValue())
290 return getValueId(
VI.getGUID());
294 std::map<GlobalValue::GUID, unsigned> &valueIds() {
return GUIDToValueIdMap; }
298class ModuleBitcodeWriter :
public ModuleBitcodeWriterBase {
314 unsigned DILocationLayersAbbrev = 0;
319 ModuleBitcodeWriter(
const Module &M, StringTableBuilder &StrtabBuilder,
320 BitstreamWriter &Stream,
bool ShouldPreserveUseListOrder,
321 const ModuleSummaryIndex *Index,
bool GenerateHash,
323 : ModuleBitcodeWriterBase(
M, StrtabBuilder, Stream,
324 ShouldPreserveUseListOrder,
Index),
325 GenerateHash(GenerateHash), ModHash(ModHash),
326 BitcodeStartBit(Stream.GetCurrentBitNo()) {}
332 uint64_t bitcodeStartBit() {
return BitcodeStartBit; }
334 size_t addToStrtab(StringRef Str);
336 void writeAttributeGroupTable();
337 void writeAttributeTable();
338 void writeTypeTable();
340 void writeValueSymbolTableForwardDecl();
341 void writeModuleInfo();
342 void writeValueAsMetadata(
const ValueAsMetadata *MD,
343 SmallVectorImpl<uint64_t> &Record);
344 void writeMDTuple(
const MDTuple *
N, SmallVectorImpl<uint64_t> &Record,
346 unsigned createDILocationAbbrev(
bool WithIRLayers);
347 void writeDILocation(
const DILocation *
N, SmallVectorImpl<uint64_t> &Record,
349 void writeDILayerLoc(
const DILayerLoc *
N, SmallVectorImpl<uint64_t> &Record,
352 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
353 unsigned createGenericDINodeAbbrev();
355 SmallVectorImpl<uint64_t> &Record,
unsigned &Abbrev);
356 void writeDISubrange(
const DISubrange *
N, SmallVectorImpl<uint64_t> &Record,
359 SmallVectorImpl<uint64_t> &Record,
362 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
366 SmallVectorImpl<uint64_t> &Record,
369 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
371 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
373 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
375 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
377 SmallVectorImpl<uint64_t> &Record,
379 void writeDIFile(
const DIFile *
N, SmallVectorImpl<uint64_t> &Record,
382 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
384 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
386 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
388 SmallVectorImpl<uint64_t> &Record,
391 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
394 void writeDIMacro(
const DIMacro *
N, SmallVectorImpl<uint64_t> &Record,
398 void writeDIArgList(
const DIArgList *
N, SmallVectorImpl<uint64_t> &Record);
399 void writeDIModule(
const DIModule *
N, SmallVectorImpl<uint64_t> &Record,
401 void writeDIAssignID(
const DIAssignID *
N, SmallVectorImpl<uint64_t> &Record,
404 SmallVectorImpl<uint64_t> &Record,
407 SmallVectorImpl<uint64_t> &Record,
410 SmallVectorImpl<uint64_t> &Record,
413 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
415 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
417 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
419 SmallVectorImpl<uint64_t> &Record,
422 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
423 void writeDIProperty(
const DIProperty *
N, SmallVectorImpl<uint64_t> &Record,
426 SmallVectorImpl<uint64_t> &Record,
428 unsigned createNamedMetadataAbbrev();
429 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
430 unsigned createMetadataStringsAbbrev();
432 SmallVectorImpl<uint64_t> &Record);
434 SmallVectorImpl<uint64_t> &Record,
435 std::vector<unsigned> *MDAbbrevs =
nullptr,
436 std::vector<uint64_t> *IndexPos =
nullptr);
437 void writeModuleMetadata();
438 void writeFunctionMetadata(
const Function &
F);
439 void writeFunctionMetadataAttachment(
const Function &
F);
440 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
441 const GlobalObject &GO);
442 void writeModuleMetadataKinds();
443 void writeOperandBundleTags();
444 void writeSyncScopeNames();
445 void writeConstants(
unsigned FirstVal,
unsigned LastVal,
bool isGlobal);
446 void writeModuleConstants();
447 bool pushValueAndType(
const Value *V,
unsigned InstID,
448 SmallVectorImpl<unsigned> &Vals);
449 bool pushValueOrMetadata(
const Value *V,
unsigned InstID,
450 SmallVectorImpl<unsigned> &Vals);
451 void writeOperandBundles(
const CallBase &CB,
unsigned InstID);
452 void pushValue(
const Value *V,
unsigned InstID,
453 SmallVectorImpl<unsigned> &Vals);
454 void pushValueSigned(
const Value *V,
unsigned InstID,
455 SmallVectorImpl<uint64_t> &Vals);
456 void writeInstruction(
const Instruction &
I,
unsigned InstID,
457 SmallVectorImpl<unsigned> &Vals);
458 void writeFunctionLevelValueSymbolTable(
const ValueSymbolTable &VST);
459 void writeGlobalValueSymbolTable(
460 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
461 void writeUseList(UseListOrder &&Order);
462 void writeUseListBlock(
const Function *
F);
465 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
466 void writeBlockInfo();
467 void writeModuleHash(StringRef View);
470 return unsigned(SSID);
473 unsigned getEncodedAlign(MaybeAlign Alignment) {
return encode(Alignment); }
477class IndexBitcodeWriter :
public BitcodeWriterBase {
479 const ModuleSummaryIndex &
Index;
495 SortedSummariesForIndex;
499 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
503 std::vector<uint64_t> StackIds;
508 DenseMap<unsigned, unsigned> StackIdIndicesToIndex;
511 unsigned GlobalValueId = 0;
515 DenseMap<StringRef, uint64_t> ModuleIdMap;
525 BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
526 const ModuleSummaryIndex &Index,
529 : BitcodeWriterBase(Stream, StrtabBuilder),
Index(
Index),
530 DecSummaries(DecSummaries),
531 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
532 if (ModuleToSummariesForIndex) {
533 for (
const auto &[ModPath, Summaries] : *ModuleToSummariesForIndex)
544 auto RecordStackIdReference = [&](
unsigned StackIdIndex) {
549 StackIdIndicesToIndex.
insert({StackIdIndex, StackIds.size()});
551 StackIds.push_back(
Index.getStackIdAtIndex(StackIdIndex));
558 forEachSummary([&](GVInfo
I,
bool IsAliasee) {
559 GUIDToValueIdMap[
I.first] = ++GlobalValueId;
571 for (
auto &CI :
FS->callsites()) {
582 if (CI.StackIdIndices.empty()) {
583 GUIDToValueIdMap[CI.Callee.getGUID()] = ++GlobalValueId;
586 for (
auto Idx : CI.StackIdIndices)
587 RecordStackIdReference(Idx);
590 for (
auto &AI :
FS->allocs())
591 for (
auto &MIB : AI.MIBs)
592 for (
auto Idx : MIB.StackIdIndices)
593 RecordStackIdReference(Idx);
599 using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
604 template<
typename Functor>
605 void forEachSummary(Functor Callback) {
606 if (ModuleToSummariesForIndex) {
607 for (
auto &[GUID, GVS] : SortedSummariesForIndex) {
613 Callback({AS->getAliaseeGUID(), &AS->getAliasee()},
true);
617 for (
const auto &Summaries :
Index.sortedGlobalValueSummariesRange())
618 for (
auto &Summary : Summaries.second.getSummaryList())
627 template <
typename Functor>
void forEachModule(Functor Callback) {
628 if (ModuleToSummariesForIndex) {
629 for (
const auto &M : *ModuleToSummariesForIndex) {
630 const auto &MPI =
Index.modulePaths().find(
M.first);
631 if (MPI ==
Index.modulePaths().end()) {
635 assert(ModuleToSummariesForIndex->size() == 1);
645 std::vector<StringRef> ModulePaths;
646 for (
auto &[ModPath,
_] :
Index.modulePaths())
647 ModulePaths.push_back(ModPath);
649 for (
auto &ModPath : ModulePaths)
658 void writeModStrings();
659 void writeCombinedGlobalValueSummary();
662 auto VMI = GUIDToValueIdMap.find(ValGUID);
663 if (VMI == GUIDToValueIdMap.end())
668 std::map<GlobalValue::GUID, unsigned> &valueIds() {
return GUIDToValueIdMap; }
703 case Instruction::Add:
705 case Instruction::Sub:
707 case Instruction::Mul:
710 case Instruction::FDiv:
713 case Instruction::FRem:
725 unsigned Encoding = 0;
726 switch (
I.getOperation()) {
799 if (
I.isElementwise())
834 case Attribute::Alignment:
836 case Attribute::AllocAlign:
838 case Attribute::AllocSize:
840 case Attribute::AlwaysInline:
842 case Attribute::Builtin:
844 case Attribute::ByVal:
846 case Attribute::Convergent:
848 case Attribute::InAlloca:
850 case Attribute::Cold:
852 case Attribute::DisableSanitizerInstrumentation:
854 case Attribute::FnRetThunkExtern:
856 case Attribute::Flatten:
860 case Attribute::ElementType:
862 case Attribute::HybridPatchable:
864 case Attribute::InlineHint:
866 case Attribute::InReg:
868 case Attribute::JumpTable:
870 case Attribute::MinSize:
872 case Attribute::AllocatedPointer:
874 case Attribute::AllocKind:
876 case Attribute::Memory:
878 case Attribute::NoFPClass:
880 case Attribute::Naked:
882 case Attribute::Nest:
884 case Attribute::NoAlias:
886 case Attribute::NoBuiltin:
888 case Attribute::NoCallback:
890 case Attribute::NoDivergenceSource:
892 case Attribute::NoDuplicate:
894 case Attribute::NoFree:
896 case Attribute::NoFreeObj:
898 case Attribute::NoImplicitFloat:
900 case Attribute::NoInline:
902 case Attribute::NoRecurse:
904 case Attribute::NoMerge:
906 case Attribute::NonLazyBind:
908 case Attribute::NonNull:
910 case Attribute::Dereferenceable:
912 case Attribute::DereferenceableOrNull:
914 case Attribute::NoRedZone:
916 case Attribute::NoReturn:
918 case Attribute::NoSync:
920 case Attribute::NoCfCheck:
922 case Attribute::NoProfile:
924 case Attribute::SkipProfile:
926 case Attribute::NoUnwind:
928 case Attribute::NoSanitizeBounds:
930 case Attribute::NoSanitizeCoverage:
932 case Attribute::NullPointerIsValid:
934 case Attribute::OptimizeForDebugging:
936 case Attribute::OptForFuzzing:
938 case Attribute::OptimizeForSize:
940 case Attribute::OptimizeNone:
942 case Attribute::ReadNone:
944 case Attribute::ReadOnly:
946 case Attribute::Returned:
948 case Attribute::ReturnsTwice:
950 case Attribute::SExt:
952 case Attribute::Speculatable:
954 case Attribute::StackAlignment:
956 case Attribute::StackProtect:
958 case Attribute::StackProtectReq:
960 case Attribute::StackProtectStrong:
962 case Attribute::SafeStack:
964 case Attribute::ShadowCallStack:
966 case Attribute::StrictFP:
968 case Attribute::StructRet:
970 case Attribute::SanitizeAddress:
972 case Attribute::SanitizeAllocToken:
974 case Attribute::SanitizeHWAddress:
976 case Attribute::SanitizeThread:
978 case Attribute::SanitizeType:
980 case Attribute::SanitizeMemory:
982 case Attribute::SanitizeNumericalStability:
984 case Attribute::SanitizeRealtime:
986 case Attribute::SanitizeRealtimeBlocking:
988 case Attribute::SpeculativeLoadHardening:
990 case Attribute::SwiftError:
992 case Attribute::SwiftSelf:
994 case Attribute::SwiftAsync:
996 case Attribute::UWTable:
998 case Attribute::VScaleRange:
1000 case Attribute::WillReturn:
1002 case Attribute::WriteOnly:
1004 case Attribute::ZExt:
1006 case Attribute::ImmArg:
1008 case Attribute::SanitizeMemTag:
1010 case Attribute::Preallocated:
1012 case Attribute::NoUndef:
1014 case Attribute::ByRef:
1016 case Attribute::MustProgress:
1018 case Attribute::PresplitCoroutine:
1020 case Attribute::Writable:
1022 case Attribute::CoroDestroyOnlyWhenComplete:
1024 case Attribute::CoroElideSafe:
1026 case Attribute::DeadOnUnwind:
1028 case Attribute::Range:
1030 case Attribute::Initializes:
1032 case Attribute::NoExt:
1034 case Attribute::Captures:
1036 case Attribute::DeadOnReturn:
1038 case Attribute::NoCreateUndefOrPoison:
1040 case Attribute::DenormalFPEnv:
1042 case Attribute::NoOutline:
1044 case Attribute::NoIPA:
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::FNeg: {
3147 assert(
CE->getNumOperands() == 1 &&
"Unknown constant expr!");
3156 case Instruction::GetElementPtr: {
3161 if (std::optional<ConstantRange>
Range = GO->getInRange()) {
3165 for (
const Value *
Op :
CE->operands()) {
3171 case Instruction::ExtractElement:
3178 case Instruction::InsertElement:
3185 case Instruction::ShuffleVector:
3190 if (
C->getType() ==
C->getOperand(0)->getType()) {
3227 Stream.
EmitRecord(Code, Record, AbbrevToUse);
3234void ModuleBitcodeWriter::writeModuleConstants() {
3239 for (
unsigned i = 0, e = Vals.size(); i != e; ++i) {
3241 writeConstants(i, Vals.size(),
true);
3255bool ModuleBitcodeWriter::pushValueAndType(
const Value *V,
unsigned InstID,
3256 SmallVectorImpl<unsigned> &Vals) {
3260 if (ValID >= InstID) {
3267bool ModuleBitcodeWriter::pushValueOrMetadata(
const Value *V,
unsigned InstID,
3268 SmallVectorImpl<unsigned> &Vals) {
3269 bool IsMetadata =
V->getType()->isMetadataTy();
3277 return pushValueAndType(V, InstID, Vals);
3280void ModuleBitcodeWriter::writeOperandBundles(
const CallBase &CS,
3287 Record.push_back(
C.getOperandBundleTagID(Bundle.getTagName()));
3289 for (
auto &Input : Bundle.Inputs)
3290 pushValueOrMetadata(Input, InstID, Record);
3299void ModuleBitcodeWriter::pushValue(
const Value *V,
unsigned InstID,
3300 SmallVectorImpl<unsigned> &Vals) {
3305void ModuleBitcodeWriter::pushValueSigned(
const Value *V,
unsigned InstID,
3306 SmallVectorImpl<uint64_t> &Vals) {
3308 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
3313void ModuleBitcodeWriter::writeInstruction(
const Instruction &
I,
3315 SmallVectorImpl<unsigned> &Vals) {
3317 unsigned AbbrevToUse = 0;
3319 switch (
I.getOpcode()) {
3323 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3324 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
3329 if (AbbrevToUse == FUNCTION_INST_CAST_ABBREV)
3330 AbbrevToUse = FUNCTION_INST_CAST_FLAGS_ABBREV;
3336 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3337 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
3338 pushValue(
I.getOperand(1), InstID, Vals);
3342 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
3343 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
3348 case Instruction::FNeg: {
3350 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3351 AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
3355 if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
3356 AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
3361 case Instruction::GetElementPtr: {
3363 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
3367 for (
const Value *
Op :
I.operands())
3368 pushValueAndType(
Op, InstID, Vals);
3371 case Instruction::ExtractValue: {
3373 pushValueAndType(
I.getOperand(0), InstID, Vals);
3378 case Instruction::InsertValue: {
3380 pushValueAndType(
I.getOperand(0), InstID, Vals);
3381 pushValueAndType(
I.getOperand(1), InstID, Vals);
3386 case Instruction::Select: {
3388 pushValueAndType(
I.getOperand(1), InstID, Vals);
3389 pushValue(
I.getOperand(2), InstID, Vals);
3390 pushValueAndType(
I.getOperand(0), InstID, Vals);
3396 case Instruction::ExtractElement:
3398 pushValueAndType(
I.getOperand(0), InstID, Vals);
3399 pushValueAndType(
I.getOperand(1), InstID, Vals);
3401 case Instruction::InsertElement:
3403 pushValueAndType(
I.getOperand(0), InstID, Vals);
3404 pushValue(
I.getOperand(1), InstID, Vals);
3405 pushValueAndType(
I.getOperand(2), InstID, Vals);
3407 case Instruction::BitExtract:
3410 pushValueAndType(
I.getOperand(0), InstID, Vals);
3411 pushValueAndType(
I.getOperand(1), InstID, Vals);
3413 case Instruction::BitInsert:
3415 pushValueAndType(
I.getOperand(0), InstID, Vals);
3416 pushValueAndType(
I.getOperand(1), InstID, Vals);
3417 pushValueAndType(
I.getOperand(2), InstID, Vals);
3419 case Instruction::ShuffleVector:
3421 pushValueAndType(
I.getOperand(0), InstID, Vals);
3422 pushValue(
I.getOperand(1), InstID, Vals);
3426 case Instruction::ICmp:
3427 case Instruction::FCmp: {
3430 AbbrevToUse = FUNCTION_INST_CMP_ABBREV;
3431 if (pushValueAndType(
I.getOperand(0), InstID, Vals))
3433 pushValue(
I.getOperand(1), InstID, Vals);
3439 AbbrevToUse = FUNCTION_INST_CMP_FLAGS_ABBREV;
3444 case Instruction::Ret:
3447 unsigned NumOperands =
I.getNumOperands();
3448 if (NumOperands == 0)
3449 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
3450 else if (NumOperands == 1) {
3451 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3452 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
3454 for (
const Value *
Op :
I.operands())
3455 pushValueAndType(
Op, InstID, Vals);
3459 case Instruction::UncondBr: {
3461 AbbrevToUse = FUNCTION_INST_BR_UNCOND_ABBREV;
3465 case Instruction::CondBr: {
3467 AbbrevToUse = FUNCTION_INST_BR_COND_ABBREV;
3471 pushValue(
II.getCondition(), InstID, Vals);
3473 case Instruction::Switch:
3478 pushValue(
SI.getCondition(), InstID, Vals);
3480 for (
auto Case :
SI.cases()) {
3486 case Instruction::IndirectBr:
3490 pushValue(
I.getOperand(0), InstID, Vals);
3495 case Instruction::Invoke: {
3498 FunctionType *FTy =
II->getFunctionType();
3500 if (
II->hasOperandBundles())
3501 writeOperandBundles(*
II, InstID);
3510 pushValueAndType(Callee, InstID, Vals);
3513 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3514 pushValue(
I.getOperand(i), InstID, Vals);
3517 if (FTy->isVarArg()) {
3518 for (
unsigned i = FTy->getNumParams(), e =
II->arg_size(); i != e; ++i)
3519 pushValueAndType(
I.getOperand(i), InstID, Vals);
3523 case Instruction::Resume:
3525 pushValueAndType(
I.getOperand(0), InstID, Vals);
3527 case Instruction::CleanupRet: {
3530 pushValue(CRI.getCleanupPad(), InstID, Vals);
3531 if (CRI.hasUnwindDest())
3535 case Instruction::CatchRet: {
3538 pushValue(CRI.getCatchPad(), InstID, Vals);
3542 case Instruction::CleanupPad:
3543 case Instruction::CatchPad: {
3547 pushValue(FuncletPad.getParentPad(), InstID, Vals);
3549 unsigned NumArgOperands = FuncletPad.arg_size();
3551 for (
unsigned Op = 0;
Op != NumArgOperands; ++
Op)
3552 pushValueAndType(FuncletPad.getArgOperand(
Op), InstID, Vals);
3555 case Instruction::CatchSwitch: {
3559 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
3561 unsigned NumHandlers = CatchSwitch.getNumHandlers();
3563 for (
const BasicBlock *CatchPadBB : CatchSwitch.handlers())
3566 if (CatchSwitch.hasUnwindDest())
3570 case Instruction::CallBr: {
3576 writeOperandBundles(*CBI, InstID);
3591 pushValueAndType(Callee, InstID, Vals);
3594 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3595 pushValue(
I.getOperand(i), InstID, Vals);
3598 if (FTy->isVarArg()) {
3599 for (
unsigned i = FTy->getNumParams(), e = CBI->
arg_size(); i != e; ++i)
3600 pushValueAndType(
I.getOperand(i), InstID, Vals);
3604 case Instruction::Unreachable:
3606 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
3609 case Instruction::PHI: {
3627 Stream.
EmitRecord(Code, Vals64, AbbrevToUse);
3632 case Instruction::LandingPad: {
3643 pushValueAndType(LP.
getClause(
I), InstID, Vals);
3648 case Instruction::Alloca: {
3654 using APV = AllocaPackedValues;
3656 unsigned EncodedAlign = getEncodedAlign(AI.
getAlign());
3658 Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1));
3660 EncodedAlign >> APV::AlignLower::Bits);
3667 if (AS !=
M.getDataLayout().getAllocaAddrSpace())
3672 case Instruction::Load: {
3674 if (LI.isAtomic()) {
3676 pushValueAndType(LI.getOperand(0), InstID, Vals);
3679 if (!pushValueAndType(LI.getOperand(0), InstID, Vals))
3680 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
3683 Vals.
push_back(getEncodedAlign(LI.getAlign()));
3685 if (LI.isAtomic()) {
3687 Vals.
push_back(getEncodedSyncScopeID(LI.getSyncScopeID()));
3688 if (LI.isElementwise())
3694 case Instruction::Store: {
3696 if (
SI.isAtomic()) {
3700 AbbrevToUse = FUNCTION_INST_STORE_ABBREV;
3702 if (pushValueAndType(
I.getOperand(1), InstID, Vals))
3704 if (pushValueAndType(
I.getOperand(0), InstID, Vals))
3708 if (
SI.isAtomic()) {
3710 Vals.
push_back(getEncodedSyncScopeID(
SI.getSyncScopeID()));
3711 if (
SI.isElementwise())
3717 case Instruction::AtomicCmpXchg:
3719 pushValueAndType(
I.getOperand(0), InstID, Vals);
3720 pushValueAndType(
I.getOperand(1), InstID, Vals);
3721 pushValue(
I.getOperand(2), InstID, Vals);
3732 case Instruction::AtomicRMW:
3734 pushValueAndType(
I.getOperand(0), InstID, Vals);
3735 pushValueAndType(
I.getOperand(1), InstID, Vals);
3743 case Instruction::Fence:
3748 case Instruction::Call: {
3753 writeOperandBundles(CI, InstID);
3773 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3777 if (FTy->isVarArg()) {
3778 for (
unsigned i = FTy->getNumParams(), e = CI.
arg_size(); i != e; ++i)
3783 case Instruction::VAArg:
3786 pushValue(
I.getOperand(0), InstID, Vals);
3789 case Instruction::Freeze:
3791 pushValueAndType(
I.getOperand(0), InstID, Vals);
3801void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3802 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3807 VSTOffset -= bitcodeStartBit();
3808 assert((VSTOffset & 31) == 0 &&
"VST block not 32-bit aligned");
3812 Stream.
BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
3816 auto Abbv = std::make_shared<BitCodeAbbrev>();
3820 unsigned FnEntryAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
3825 if (
F.isDeclaration())
3832 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&
F] - bitcodeStartBit();
3833 assert((BitcodeIndex & 31) == 0 &&
"function block not 32-bit aligned");
3837 Record[1] = BitcodeIndex / 32 + 1;
3846void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3847 const ValueSymbolTable &VST) {
3855 SmallVector<uint64_t, 64> NameVals;
3861 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3870 AbbrevToUse = VST_BBENTRY_6_ABBREV;
3874 AbbrevToUse = VST_ENTRY_6_ABBREV;
3876 AbbrevToUse = VST_ENTRY_7_ABBREV;
3879 for (
const auto P :
Name.getKey())
3883 Stream.
EmitRecord(Code, NameVals, AbbrevToUse);
3890void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3891 assert(Order.Shuffle.size() >= 2 &&
"Shuffle too small");
3898 SmallVector<uint64_t, 64>
Record(Order.Shuffle.begin(), Order.Shuffle.end());
3903void ModuleBitcodeWriter::writeUseListBlock(
const Function *
F) {
3905 "Expected to be preserving use-list order");
3907 auto hasMore = [&]() {
3923void ModuleBitcodeWriter::writeFunction(
3925 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3942 unsigned CstStart, CstEnd;
3944 writeConstants(CstStart, CstEnd,
false);
3947 writeFunctionMetadata(
F);
3950 unsigned InstID = CstEnd;
3952 bool NeedsMetadataAttachment =
F.hasMetadata();
3954 DILocation *LastDL =
nullptr;
3955 SmallSetVector<Function *, 4> BlockAddressUsers;
3958 for (
const BasicBlock &BB :
F) {
3959 for (
const Instruction &
I : BB) {
3960 writeInstruction(
I, InstID, Vals);
3962 if (!
I.getType()->isVoidTy())
3966 NeedsMetadataAttachment |=
I.hasMetadataOtherThanDebugLoc();
3969 if (DILocation *
DL =
I.getDebugLoc()) {
3982 unsigned DLAbbrev = FUNCTION_DEBUG_LOC_ABBREV;
3983 if (DILayerLocList *IRLayers =
DL->getIRLayers()) {
3984 DLAbbrev = FUNCTION_DEBUG_LOC_LAYERS_ABBREV;
3998 if (
I.hasDbgRecords()) {
4002 auto PushValueOrMetadata = [&Vals, InstID,
4005 "RawLocation unexpectedly null in DbgVariableRecord");
4007 SmallVector<unsigned, 2> ValAndType;
4011 if (!pushValueAndType(VAM->getValue(), InstID, ValAndType)) {
4025 for (DbgRecord &DR :
I.getDbgMarker()->getDbgRecordRange()) {
4051 FUNCTION_DEBUG_RECORD_VALUE_ABBREV);
4075 SmallPtrSet<Value *, 8> Visited{BA};
4076 while (!Worklist.
empty()) {
4078 for (User *U :
V->users()) {
4084 Visited.
insert(U).second)
4091 if (!BlockAddressUsers.
empty()) {
4100 if (
auto *Symtab =
F.getValueSymbolTable())
4101 writeFunctionLevelValueSymbolTable(*Symtab);
4103 if (NeedsMetadataAttachment)
4104 writeFunctionMetadataAttachment(
F);
4106 writeUseListBlock(&
F);
4112void ModuleBitcodeWriter::writeBlockInfo() {
4125 auto Abbv = std::make_shared<BitCodeAbbrev>();
4136 auto Abbv = std::make_shared<BitCodeAbbrev>();
4146 auto Abbv = std::make_shared<BitCodeAbbrev>();
4156 auto Abbv = std::make_shared<BitCodeAbbrev>();
4162 VST_BBENTRY_6_ABBREV)
4167 auto Abbv = std::make_shared<BitCodeAbbrev>();
4169 Abbv->Add(TypeAbbrevOp);
4171 CONSTANTS_SETTYPE_ABBREV)
4176 auto Abbv = std::make_shared<BitCodeAbbrev>();
4180 CONSTANTS_INTEGER_ABBREV)
4185 auto Abbv = std::make_shared<BitCodeAbbrev>();
4189 CONSTANTS_BYTE_ABBREV)
4194 auto Abbv = std::make_shared<BitCodeAbbrev>();
4202 CONSTANTS_CE_CAST_Abbrev)
4206 auto Abbv = std::make_shared<BitCodeAbbrev>();
4209 CONSTANTS_NULL_Abbrev)
4216 auto Abbv = std::make_shared<BitCodeAbbrev>();
4218 Abbv->Add(ValAbbrevOp);
4219 Abbv->Add(TypeAbbrevOp);
4223 FUNCTION_INST_LOAD_ABBREV)
4227 auto Abbv = std::make_shared<BitCodeAbbrev>();
4229 Abbv->Add(ValAbbrevOp);
4230 Abbv->Add(ValAbbrevOp);
4234 FUNCTION_INST_STORE_ABBREV)
4238 auto Abbv = std::make_shared<BitCodeAbbrev>();
4240 Abbv->Add(ValAbbrevOp);
4243 FUNCTION_INST_UNOP_ABBREV)
4247 auto Abbv = std::make_shared<BitCodeAbbrev>();
4249 Abbv->Add(ValAbbrevOp);
4253 FUNCTION_INST_UNOP_FLAGS_ABBREV)
4257 auto Abbv = std::make_shared<BitCodeAbbrev>();
4259 Abbv->Add(ValAbbrevOp);
4260 Abbv->Add(ValAbbrevOp);
4263 FUNCTION_INST_BINOP_ABBREV)
4267 auto Abbv = std::make_shared<BitCodeAbbrev>();
4269 Abbv->Add(ValAbbrevOp);
4270 Abbv->Add(ValAbbrevOp);
4274 FUNCTION_INST_BINOP_FLAGS_ABBREV)
4278 auto Abbv = std::make_shared<BitCodeAbbrev>();
4280 Abbv->Add(ValAbbrevOp);
4281 Abbv->Add(TypeAbbrevOp);
4284 FUNCTION_INST_CAST_ABBREV)
4288 auto Abbv = std::make_shared<BitCodeAbbrev>();
4290 Abbv->Add(ValAbbrevOp);
4291 Abbv->Add(TypeAbbrevOp);
4295 FUNCTION_INST_CAST_FLAGS_ABBREV)
4300 auto Abbv = std::make_shared<BitCodeAbbrev>();
4303 FUNCTION_INST_RET_VOID_ABBREV)
4307 auto Abbv = std::make_shared<BitCodeAbbrev>();
4309 Abbv->Add(ValAbbrevOp);
4311 FUNCTION_INST_RET_VAL_ABBREV)
4315 auto Abbv = std::make_shared<BitCodeAbbrev>();
4318 Abbv->Add(ValAbbrevOp);
4320 FUNCTION_INST_BR_UNCOND_ABBREV)
4324 auto Abbv = std::make_shared<BitCodeAbbrev>();
4327 Abbv->Add(ValAbbrevOp);
4328 Abbv->Add(ValAbbrevOp);
4329 Abbv->Add(ValAbbrevOp);
4331 FUNCTION_INST_BR_COND_ABBREV)
4335 auto Abbv = std::make_shared<BitCodeAbbrev>();
4338 FUNCTION_INST_UNREACHABLE_ABBREV)
4342 auto Abbv = std::make_shared<BitCodeAbbrev>();
4345 Abbv->Add(TypeAbbrevOp);
4347 Abbv->Add(ValAbbrevOp);
4349 FUNCTION_INST_GEP_ABBREV)
4353 auto Abbv = std::make_shared<BitCodeAbbrev>();
4355 Abbv->Add(ValAbbrevOp);
4356 Abbv->Add(ValAbbrevOp);
4359 FUNCTION_INST_CMP_ABBREV)
4363 auto Abbv = std::make_shared<BitCodeAbbrev>();
4365 Abbv->Add(ValAbbrevOp);
4366 Abbv->Add(ValAbbrevOp);
4370 FUNCTION_INST_CMP_FLAGS_ABBREV)
4374 auto Abbv = std::make_shared<BitCodeAbbrev>();
4379 Abbv->Add(ValAbbrevOp);
4381 FUNCTION_DEBUG_RECORD_VALUE_ABBREV)
4385 auto Abbv = std::make_shared<BitCodeAbbrev>();
4396 FUNCTION_DEBUG_LOC_ABBREV)
4402 auto Abbv = std::make_shared<BitCodeAbbrev>();
4413 FUNCTION_DEBUG_LOC_LAYERS_ABBREV)
4421void IndexBitcodeWriter::writeModStrings() {
4427 auto Abbv = std::make_shared<BitCodeAbbrev>();
4432 unsigned Abbrev8Bit = Stream.
EmitAbbrev(std::move(Abbv));
4435 Abbv = std::make_shared<BitCodeAbbrev>();
4440 unsigned Abbrev7Bit = Stream.
EmitAbbrev(std::move(Abbv));
4443 Abbv = std::make_shared<BitCodeAbbrev>();
4448 unsigned Abbrev6Bit = Stream.
EmitAbbrev(std::move(Abbv));
4451 Abbv = std::make_shared<BitCodeAbbrev>();
4458 unsigned AbbrevHash = Stream.
EmitAbbrev(std::move(Abbv));
4461 forEachModule([&](
const StringMapEntry<ModuleHash> &MPSE) {
4463 const auto &Hash = MPSE.
getValue();
4465 unsigned AbbrevToUse = Abbrev8Bit;
4467 AbbrevToUse = Abbrev6Bit;
4469 AbbrevToUse = Abbrev7Bit;
4471 auto ModuleId = ModuleIdMap.
size();
4472 ModuleIdMap[
Key] = ModuleId;
4482 Vals.
assign(Hash.begin(), Hash.end());
4494template <
typename Fn>
4498 if (!FS->type_tests().empty())
4503 auto WriteVFuncIdVec = [&](
uint64_t Ty,
4508 for (
auto &VF : VFs) {
4509 Record.push_back(VF.GUID);
4510 Record.push_back(VF.Offset);
4516 FS->type_test_assume_vcalls());
4518 FS->type_checked_load_vcalls());
4520 auto WriteConstVCallVec = [&](
uint64_t Ty,
4522 for (
auto &VC : VCs) {
4524 Record.push_back(VC.VFunc.GUID);
4525 Record.push_back(VC.VFunc.Offset);
4532 FS->type_test_assume_const_vcalls());
4534 FS->type_checked_load_const_vcalls());
4544 if (!FS->paramAccesses().empty()) {
4546 for (
auto &Arg : FS->paramAccesses()) {
4547 size_t UndoSize =
Record.size();
4548 Record.push_back(Arg.ParamNo);
4549 WriteRange(Arg.Use);
4550 Record.push_back(Arg.Calls.size());
4551 for (
auto &
Call : Arg.Calls) {
4553 std::optional<unsigned> ValueID = GetValueID(
Call.Callee);
4560 Record.push_back(*ValueID);
4561 WriteRange(
Call.Offsets);
4572 std::set<GlobalValue::GUID> &ReferencedTypeIds) {
4573 if (!FS->type_tests().empty())
4574 for (
auto &TT : FS->type_tests())
4575 ReferencedTypeIds.insert(TT);
4577 auto GetReferencedTypesFromVFuncIdVec =
4579 for (
auto &VF : VFs)
4580 ReferencedTypeIds.insert(VF.GUID);
4583 GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
4584 GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
4586 auto GetReferencedTypesFromConstVCallVec =
4588 for (
auto &VC : VCs)
4589 ReferencedTypeIds.insert(VC.VFunc.GUID);
4592 GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
4593 GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
4629 NameVals.
push_back(Summary.TTRes.TheKind);
4630 NameVals.
push_back(Summary.TTRes.SizeM1BitWidth);
4631 NameVals.
push_back(Summary.TTRes.AlignLog2);
4632 NameVals.
push_back(Summary.TTRes.SizeM1);
4633 NameVals.
push_back(Summary.TTRes.BitMask);
4634 NameVals.
push_back(Summary.TTRes.InlineBits);
4636 for (
auto &W : Summary.WPDRes)
4648 for (
auto &
P : Summary) {
4650 NameVals.
push_back(
VE.getValueID(
P.VTableVI.getValue()));
4664 static_assert(std::is_same_v<LinearFrameId, unsigned>);
4665 for (
auto &AI : FS->allocs()) {
4666 for (
auto &MIB : AI.MIBs) {
4668 StackIdIndices.
reserve(MIB.StackIdIndices.size());
4669 for (
auto Id : MIB.StackIdIndices)
4670 StackIdIndices.
push_back(GetStackIndex(Id));
4672 CallStacks.insert({CallStacks.size(), StackIdIndices});
4685 assert(!CallStacks.empty());
4691 Builder.
build(std::move(CallStacks),
nullptr,
4695 return Builder.takeCallStackPos();
4700 unsigned AllocAbbrev,
unsigned ContextIdAbbvId,
bool PerModule,
4701 std::function<
unsigned(
const ValueInfo &VI)> GetValueID,
4702 std::function<
unsigned(
unsigned)> GetStackIndex,
4703 bool WriteContextSizeInfoIndex,
4708 for (
auto &CI : FS->callsites()) {
4712 assert(!PerModule || (CI.Clones.size() == 1 && CI.Clones[0] == 0));
4713 Record.push_back(GetValueID(CI.Callee));
4715 Record.push_back(CI.StackIdIndices.size());
4716 Record.push_back(CI.Clones.size());
4718 for (
auto Id : CI.StackIdIndices)
4719 Record.push_back(GetStackIndex(Id));
4727 for (
auto &AI : FS->allocs()) {
4731 assert(!PerModule || (AI.Versions.size() == 1 && AI.Versions[0] == 0));
4732 Record.push_back(AI.MIBs.size());
4734 Record.push_back(AI.Versions.size());
4735 for (
auto &MIB : AI.MIBs) {
4742 assert(CallStackCount <= CallStackPos.
size());
4743 Record.push_back(CallStackPos[CallStackCount++]);
4748 assert(AI.ContextSizeInfos.empty() ||
4749 AI.ContextSizeInfos.size() == AI.MIBs.size());
4751 if (WriteContextSizeInfoIndex && !AI.ContextSizeInfos.empty()) {
4759 ContextIds.
reserve(AI.ContextSizeInfos.size() * 2);
4760 for (
auto &Infos : AI.ContextSizeInfos) {
4761 Record.push_back(Infos.size());
4762 for (
auto [FullStackId, TotalSize] : Infos) {
4769 Record.push_back(TotalSize);
4787void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
4788 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
4789 unsigned ValueID,
unsigned FSCallsProfileAbbrev,
unsigned CallsiteAbbrev,
4790 unsigned AllocAbbrev,
unsigned ContextIdAbbvId,
const Function &
F,
4791 DenseMap<CallStackId, LinearCallStackId> &CallStackPos,
4798 Stream, FS, [&](
const ValueInfo &VI) -> std::optional<unsigned> {
4802 auto SpecialRefCnts =
FS->specialRefCounts();
4807 NameVals.
push_back(SpecialRefCnts.first);
4808 NameVals.
push_back(SpecialRefCnts.second);
4810 for (
auto &RI :
FS->refs())
4813 for (
auto &ECI :
FS->calls()) {
4814 NameVals.
push_back(getValueId(ECI.first));
4823 Stream, FS, CallsiteAbbrev, AllocAbbrev, ContextIdAbbvId,
4825 [&](
const ValueInfo &VI) {
return getValueId(VI); },
4826 [&](
unsigned I) {
return I; },
4827 true, CallStackPos, CallStackCount);
4832void ModuleBitcodeWriterBase::writeModuleLevelReferences(
4833 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
4834 unsigned FSModRefsAbbrev,
unsigned FSModVTableRefsAbbrev) {
4839 auto VI =
Index->getValueInfo(GUID);
4840 if (!VI ||
VI.getSummaryList().empty()) {
4846 auto *
Summary =
VI.getSummaryList()[0].get();
4852 auto VTableFuncs =
VS->vTableFuncs();
4853 if (!VTableFuncs.empty())
4856 unsigned SizeBeforeRefs = NameVals.
size();
4857 for (
auto &RI :
VS->refs())
4863 if (VTableFuncs.empty())
4868 for (
auto &
P : VTableFuncs) {
4874 FSModVTableRefsAbbrev);
4881void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
4884 bool IsThinLTO =
true;
4887 IsThinLTO = MD->getZExtValue();
4899 if (
Index->enableSplitLTOUnit())
4901 if (
Index->hasUnifiedLTO())
4911 auto Abbv = std::make_shared<BitCodeAbbrev>();
4917 unsigned ValueGuidAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4919 for (
const auto &GVI : valueIds()) {
4921 ArrayRef<uint32_t>{GVI.second,
4922 static_cast<uint32_t
>(GVI.first >> 32),
4923 static_cast<uint32_t
>(GVI.first)},
4927 if (!
Index->stackIds().empty()) {
4928 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4935 unsigned StackIdAbbvId = Stream.
EmitAbbrev(std::move(StackIdAbbv));
4936 SmallVector<uint32_t> Vals;
4938 for (
auto Id :
Index->stackIds()) {
4939 Vals.
push_back(
static_cast<uint32_t
>(Id >> 32));
4940 Vals.
push_back(
static_cast<uint32_t
>(Id));
4945 unsigned ContextIdAbbvId = 0;
4948 auto ContextIdAbbv = std::make_shared<BitCodeAbbrev>();
4960 ContextIdAbbvId = Stream.
EmitAbbrev(std::move(ContextIdAbbv));
4964 Abbv = std::make_shared<BitCodeAbbrev>();
4976 unsigned FSCallsProfileAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4979 Abbv = std::make_shared<BitCodeAbbrev>();
4985 unsigned FSModRefsAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4988 Abbv = std::make_shared<BitCodeAbbrev>();
4996 unsigned FSModVTableRefsAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4999 Abbv = std::make_shared<BitCodeAbbrev>();
5004 unsigned FSAliasAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5007 Abbv = std::make_shared<BitCodeAbbrev>();
5014 unsigned TypeIdCompatibleVtableAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5016 Abbv = std::make_shared<BitCodeAbbrev>();
5022 unsigned CallsiteAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5024 Abbv = std::make_shared<BitCodeAbbrev>();
5031 unsigned AllocAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5033 Abbv = std::make_shared<BitCodeAbbrev>();
5038 unsigned RadixAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5045 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks;
5056 ValueInfo
VI =
Index->getValueInfo(GUID);
5057 if (!VI ||
VI.getSummaryList().empty()) {
5060 if (!
F.isDeclaration())
5062 " to have an associated value info.");
5065 auto *
Summary =
VI.getSummaryList()[0].get();
5068 FS, [](
unsigned I) {
return I; }, CallStacks);
5072 DenseMap<CallStackId, LinearCallStackId> CallStackPos;
5073 if (!CallStacks.
empty()) {
5081 SmallVector<uint64_t, 64> NameVals;
5092 ValueInfo
VI =
Index->getValueInfo(GUID);
5093 if (!VI ||
VI.getSummaryList().empty()) {
5099 auto *
Summary =
VI.getSummaryList()[0].get();
5100 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.
getValueID(&
F),
5101 FSCallsProfileAbbrev, CallsiteAbbrev,
5102 AllocAbbrev, ContextIdAbbvId,
F,
5103 CallStackPos, CallStackCount);
5108 for (
const GlobalVariable &
G :
M.globals())
5109 writeModuleLevelReferences(
G, NameVals, FSModRefsAbbrev,
5110 FSModVTableRefsAbbrev);
5112 for (
const GlobalAlias &
A :
M.aliases()) {
5113 auto *Aliasee =
A.getAliaseeObject();
5129 for (
auto &S :
Index->typeIdCompatibleVtableMap()) {
5133 TypeIdCompatibleVtableAbbrev);
5137 if (
Index->getBlockCount())
5139 ArrayRef<uint64_t>{
Index->getBlockCount()});
5144void ModuleBitcodeWriterBase::writeGUIDList() {
5146 for (
const GlobalValue &GV :
M.global_values()) {
5147 auto MaybeGUID = GV.getGUIDIfAssigned();
5148 if (!MaybeGUID || *MaybeGUID == 0)
5151 if (ValueID >= GUIDs.
size())
5152 GUIDs.
resize(ValueID + 1);
5153 GUIDs[ValueID] = *MaybeGUID;
5156 auto Abbv = std::make_shared<BitCodeAbbrev>();
5160 unsigned GUIDListAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5162 SmallVector<uint32_t> RecordVals;
5164 for (
auto GUID : GUIDs) {
5165 RecordVals.
push_back(
static_cast<uint32_t
>(GUID >> 32));
5166 RecordVals.
push_back(
static_cast<uint32_t
>(GUID));
5173void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
5182 auto Abbv = std::make_shared<BitCodeAbbrev>();
5188 unsigned ValueGuidAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5190 for (
const auto &GVI : valueIds()) {
5192 ArrayRef<uint32_t>{GVI.second,
5193 static_cast<uint32_t
>(GVI.first >> 32),
5194 static_cast<uint32_t
>(GVI.first)},
5200 if (!StackIds.empty()) {
5201 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
5208 unsigned StackIdAbbvId = Stream.
EmitAbbrev(std::move(StackIdAbbv));
5209 SmallVector<uint32_t> Vals;
5210 Vals.
reserve(StackIds.size() * 2);
5211 for (
auto Id : StackIds) {
5212 Vals.
push_back(
static_cast<uint32_t
>(Id >> 32));
5213 Vals.
push_back(
static_cast<uint32_t
>(Id));
5219 Abbv = std::make_shared<BitCodeAbbrev>();
5233 unsigned FSCallsProfileAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5236 Abbv = std::make_shared<BitCodeAbbrev>();
5243 unsigned FSModRefsAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5246 Abbv = std::make_shared<BitCodeAbbrev>();
5252 unsigned FSAliasAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5254 Abbv = std::make_shared<BitCodeAbbrev>();
5262 unsigned CallsiteAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5264 Abbv = std::make_shared<BitCodeAbbrev>();
5275 unsigned AllocAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5277 auto shouldImportValueAsDecl = [&](GlobalValueSummary *GVS) ->
bool {
5278 if (DecSummaries ==
nullptr)
5280 return DecSummaries->
count(GVS);
5288 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
5290 SmallVector<uint64_t, 64> NameVals;
5294 std::set<GlobalValue::GUID> ReferencedTypeIds;
5298 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
5308 NameVals.
push_back(S.getOriginalName());
5313 DenseMap<CallStackId, LinearCallStackId> CallStackPos;
5315 Abbv = std::make_shared<BitCodeAbbrev>();
5320 unsigned RadixAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5327 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks;
5328 forEachSummary([&](GVInfo
I,
bool IsAliasee) {
5334 GlobalValueSummary *S =
I.second;
5347 return StackIdIndicesToIndex[
I];
5353 if (!CallStacks.
empty()) {
5363 DenseSet<GlobalValue::GUID> DefOrUseGUIDs;
5364 forEachSummary([&](GVInfo
I,
bool IsAliasee) {
5365 GlobalValueSummary *S =
I.second;
5367 DefOrUseGUIDs.
insert(
I.first);
5368 for (
const ValueInfo &VI : S->
refs())
5369 DefOrUseGUIDs.
insert(
VI.getGUID());
5371 auto ValueId = getValueId(
I.first);
5373 SummaryToValueIdMap[S] = *ValueId;
5391 NameVals.
push_back(ModuleIdMap[
VS->modulePath()]);
5395 for (
auto &RI :
VS->refs()) {
5396 auto RefValueId = getValueId(RI.getGUID());
5406 MaybeEmitOriginalName(*S);
5410 auto GetValueId = [&](
const ValueInfo &
VI) -> std::optional<unsigned> {
5412 return std::nullopt;
5413 return getValueId(
VI.getGUID());
5422 NameVals.
push_back(ModuleIdMap[
FS->modulePath()]);
5435 unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;
5436 for (
auto &RI :
FS->refs()) {
5437 auto RefValueId = getValueId(RI.getGUID());
5441 if (RI.isReadOnly())
5443 else if (RI.isWriteOnly())
5447 NameVals[6] =
Count;
5448 NameVals[7] = RORefCnt;
5449 NameVals[8] = WORefCnt;
5451 for (
auto &EI :
FS->calls()) {
5454 std::optional<unsigned> CallValueId = GetValueId(EI.first);
5463 FSCallsProfileAbbrev);
5467 Stream, FS, CallsiteAbbrev, AllocAbbrev, 0,
5470 [&](
const ValueInfo &VI) ->
unsigned {
5471 std::optional<unsigned> ValueID = GetValueId(VI);
5486 return StackIdIndicesToIndex[
I];
5488 false, CallStackPos, CallStackCount);
5490 MaybeEmitOriginalName(*S);
5493 for (
auto *AS : Aliases) {
5494 auto AliasValueId = SummaryToValueIdMap[AS];
5503 auto AliaseeValueId =
5510 MaybeEmitOriginalName(*AS);
5518 auto EmitCfiFunctions = [&](
const CfiFunctionIndex &CfiIndex,
5520 if (CfiIndex.
empty())
5524 for (StringRef Name : Names)
5527 if (Functions.
empty())
5530 for (
const auto &Record : Functions) {
5545 for (
auto &
T : ReferencedTypeIds) {
5546 auto TidIter =
Index.typeIds().equal_range(
T);
5547 for (
const auto &[GUID, TypeIdPair] :
make_range(TidIter)) {
5555 if (
Index.getBlockCount())
5557 ArrayRef<uint64_t>{
Index.getBlockCount()});
5568 auto Abbv = std::make_shared<BitCodeAbbrev>();
5572 auto StringAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5574 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
5577 Abbv = std::make_shared<BitCodeAbbrev>();
5580 auto EpochAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5586void ModuleBitcodeWriter::writeModuleHash(StringRef View) {
5591 Hasher.
update(ArrayRef<uint8_t>(
5592 reinterpret_cast<const uint8_t *
>(
View.data()),
View.size()));
5593 std::array<uint8_t, 20> Hash = Hasher.
result();
5594 for (
int Pos = 0; Pos < 20; Pos += 4) {
5607void ModuleBitcodeWriter::write() {
5615 writeModuleVersion();
5624 writeAttributeGroupTable();
5627 writeAttributeTable();
5636 writeModuleConstants();
5639 writeModuleMetadataKinds();
5642 writeModuleMetadata();
5646 writeUseListBlock(
nullptr);
5648 writeOperandBundleTags();
5649 writeSyncScopeNames();
5652 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
5654 if (!
F.isDeclaration())
5655 writeFunction(
F, FunctionToBitcodeIndex);
5660 writePerModuleGlobalValueSummary();
5662 writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
5690 unsigned CPUType = ~0U;
5697 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
5698 DARWIN_CPU_TYPE_X86 = 7,
5699 DARWIN_CPU_TYPE_ARM = 12,
5700 DARWIN_CPU_TYPE_POWERPC = 18
5705 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
5707 CPUType = DARWIN_CPU_TYPE_X86;
5709 CPUType = DARWIN_CPU_TYPE_POWERPC;
5711 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
5713 CPUType = DARWIN_CPU_TYPE_ARM;
5717 "Expected header size to be reserved");
5722 unsigned Position = 0;
5730 while (Buffer.
size() & 15)
5737 Stream.
Emit((
unsigned)
'B', 8);
5738 Stream.
Emit((
unsigned)
'C', 8);
5739 Stream.
Emit(0x0, 4);
5740 Stream.
Emit(0xC, 4);
5741 Stream.
Emit(0xE, 4);
5742 Stream.
Emit(0xD, 4);
5760 auto Abbv = std::make_shared<BitCodeAbbrev>();
5763 auto AbbrevNo = Stream->
EmitAbbrev(std::move(Abbv));
5771 assert(!WroteStrtab && !WroteSymtab);
5777 if (M->getModuleInlineAsm().empty())
5781 const Triple TT(M->getTargetTriple());
5783 if (!
T || !
T->hasMCAsmParser())
5805 std::vector<char> Strtab;
5806 StrtabBuilder.finalizeInOrder();
5807 Strtab.resize(StrtabBuilder.getSize());
5808 StrtabBuilder.write((
uint8_t *)Strtab.data());
5811 {Strtab.data(), Strtab.size()});
5822 bool ShouldPreserveUseListOrder,
5831 assert(M.isMaterialized());
5832 Mods.push_back(
const_cast<Module *
>(&M));
5834 ModuleBitcodeWriter ModuleWriter(M, StrtabBuilder, *Stream,
5835 ShouldPreserveUseListOrder, Index,
5836 GenerateHash, ModHash);
5837 ModuleWriter.write();
5844 IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index, DecSummaries,
5845 ModuleToSummariesForIndex);
5846 IndexWriter.write();
5851 bool ShouldPreserveUseListOrder,
5855 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
5857 Writer.writeSymtab();
5858 Writer.writeStrtab();
5860 Triple TT(M.getTargetTriple());
5861 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) {
5872 Out.write(Buffer.
data(), Buffer.
size());
5879void IndexBitcodeWriter::write() {
5882 writeModuleVersion();
5888 writeCombinedGlobalValueSummary();
5905 Writer.
writeIndex(&Index, ModuleToSummariesForIndex, DecSummaries);
5908 Out.write((
char *)&Buffer.
front(), Buffer.
size());
5914class ThinLinkBitcodeWriter :
public ModuleBitcodeWriterBase {
5924 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
5926 ModHash(&ModHash) {}
5931 void writeSimplifiedModuleInfo();
5941void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
5953 auto Abbv = std::make_shared<BitCodeAbbrev>();
5956 Abbv->Add(AbbrevOpToUse);
5957 unsigned FilenameAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5959 for (
const auto P :
M.getSourceFileName())
6025void ThinLinkBitcodeWriter::write() {
6028 writeModuleVersion();
6030 writeSimplifiedModuleInfo();
6032 writePerModuleGlobalValueSummary();
6049 assert(M.isMaterialized());
6050 Mods.push_back(
const_cast<Module *
>(&M));
6052 ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
6054 ThinLinkWriter.write();
6071 Out.write((
char *)&Buffer.
front(), Buffer.
size());
6075 switch (
T.getObjectFormat()) {
6077 return "__LLVM,__bitcode";
6102 switch (
T.getObjectFormat()) {
6104 return "__LLVM,__cmdline";
6130 const std::vector<uint8_t> &CmdArgs) {
6135 Type *UsedElementType = Used ? Used->getValueType()->getArrayElementType()
6137 for (
auto *GV : UsedGlobals) {
6138 if (GV->getName() !=
"llvm.embedded.module" &&
6139 GV->getName() !=
"llvm.cmdline")
6144 Used->eraseFromParent();
6149 Triple T(M.getTargetTriple());
6178 M.getGlobalVariable(
"llvm.embedded.module",
true)) {
6179 assert(Old->hasZeroLiveUses() &&
6180 "llvm.embedded.module can only be used once in llvm.compiler.used");
6182 Old->eraseFromParent();
6184 GV->
setName(
"llvm.embedded.module");
6202 assert(Old->hasZeroLiveUses() &&
6203 "llvm.cmdline can only be used once in llvm.compiler.used");
6205 Old->eraseFromParent();
6211 if (UsedArray.
empty())
6219 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.
ForceSummaryHotnessType
Types for -force-summary-edges-cold debugging option.
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_ALLOCATED_POINTER
@ ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION
@ ATTR_KIND_CORO_ELIDE_SAFE
@ ATTR_KIND_NON_LAZY_BIND
@ ATTR_KIND_DEREFERENCEABLE
@ 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.
FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold
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