34#include "llvm/Config/llvm-config.h"
119 VST_BBENTRY_6_ABBREV,
123 CONSTANTS_INTEGER_ABBREV,
124 CONSTANTS_BYTE_ABBREV,
125 CONSTANTS_CE_CAST_Abbrev,
126 CONSTANTS_NULL_Abbrev,
130 FUNCTION_INST_STORE_ABBREV,
131 FUNCTION_INST_UNOP_ABBREV,
132 FUNCTION_INST_UNOP_FLAGS_ABBREV,
133 FUNCTION_INST_BINOP_ABBREV,
134 FUNCTION_INST_BINOP_FLAGS_ABBREV,
135 FUNCTION_INST_CAST_ABBREV,
136 FUNCTION_INST_CAST_FLAGS_ABBREV,
137 FUNCTION_INST_RET_VOID_ABBREV,
138 FUNCTION_INST_RET_VAL_ABBREV,
139 FUNCTION_INST_BR_UNCOND_ABBREV,
140 FUNCTION_INST_BR_COND_ABBREV,
141 FUNCTION_INST_UNREACHABLE_ABBREV,
142 FUNCTION_INST_GEP_ABBREV,
143 FUNCTION_INST_CMP_ABBREV,
144 FUNCTION_INST_CMP_FLAGS_ABBREV,
145 FUNCTION_DEBUG_RECORD_VALUE_ABBREV,
146 FUNCTION_DEBUG_LOC_ABBREV,
147 FUNCTION_DEBUG_LOC_LAYERS_ABBREV,
152class BitcodeWriterBase {
155 BitstreamWriter &Stream;
157 StringTableBuilder &StrtabBuilder;
162 BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
163 : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
166 void writeModuleVersion();
169void BitcodeWriterBase::writeModuleVersion() {
176class ModuleBitcodeWriterBase :
public BitcodeWriterBase {
178 const BitWriterOptions &Opts;
187 const ModuleSummaryIndex *Index;
192 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
195 unsigned GlobalValueId;
204 ModuleBitcodeWriterBase(
const Module &M, StringTableBuilder &StrtabBuilder,
205 BitstreamWriter &Stream,
206 bool ShouldPreserveUseListOrder,
207 const ModuleSummaryIndex *Index)
208 : BitcodeWriterBase(Stream, StrtabBuilder),
211 valueOr(Opts.preserve_bc_uselistorder, ShouldPreserveUseListOrder)),
222 for (
const auto &GUIDSummaryLists :
223 Index->sortedGlobalValueSummariesRange())
225 for (
auto &Summary : GUIDSummaryLists.second.getSummaryList())
231 for (auto &CallEdge : FS->calls())
232 if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())
233 assignValueId(CallEdge.first.getGUID());
239 for (auto &RefEdge : FS->refs())
240 if (!RefEdge.haveGVs() || !RefEdge.getValue())
241 assignValueId(RefEdge.getGUID());
246 void writePerModuleGlobalValueSummary();
247 void writeGUIDList();
250 void writePerModuleFunctionSummaryRecord(
251 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
252 unsigned ValueID,
unsigned FSCallsProfileAbbrev,
unsigned CallsiteAbbrev,
253 unsigned AllocAbbrev,
unsigned ContextIdAbbvId,
const Function &
F,
254 DenseMap<CallStackId, LinearCallStackId> &CallStackPos,
256 void writeModuleLevelReferences(
const GlobalVariable &
V,
257 SmallVector<uint64_t, 64> &NameVals,
258 unsigned FSModRefsAbbrev,
259 unsigned FSModVTableRefsAbbrev);
262 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
266 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
269 assert(VMI != GUIDToValueIdMap.end() &&
270 "GUID does not have assigned value Id");
275 unsigned getValueId(ValueInfo VI) {
276 if (!
VI.haveGVs() || !
VI.getValue())
277 return getValueId(
VI.getGUID());
281 std::map<GlobalValue::GUID, unsigned> &valueIds() {
return GUIDToValueIdMap; }
285class ModuleBitcodeWriter :
public ModuleBitcodeWriterBase {
301 unsigned DILocationLayersAbbrev = 0;
306 ModuleBitcodeWriter(
const Module &M, StringTableBuilder &StrtabBuilder,
307 BitstreamWriter &Stream,
bool ShouldPreserveUseListOrder,
308 const ModuleSummaryIndex *Index,
bool GenerateHash,
310 : ModuleBitcodeWriterBase(
M, StrtabBuilder, Stream,
311 ShouldPreserveUseListOrder,
Index),
312 GenerateHash(GenerateHash), ModHash(ModHash),
313 BitcodeStartBit(Stream.GetCurrentBitNo()) {}
319 uint64_t bitcodeStartBit() {
return BitcodeStartBit; }
321 size_t addToStrtab(StringRef Str);
323 void writeAttributeGroupTable();
324 void writeAttributeTable();
325 void writeTypeTable();
327 void writeValueSymbolTableForwardDecl();
328 void writeModuleInfo();
329 void writeValueAsMetadata(
const ValueAsMetadata *MD,
330 SmallVectorImpl<uint64_t> &Record);
331 void writeMDTuple(
const MDTuple *
N, SmallVectorImpl<uint64_t> &Record,
333 unsigned createDILocationAbbrev(
bool WithIRLayers);
334 void writeDILocation(
const DILocation *
N, SmallVectorImpl<uint64_t> &Record,
336 void writeDILayerLoc(
const DILayerLoc *
N, SmallVectorImpl<uint64_t> &Record,
339 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
340 unsigned createGenericDINodeAbbrev();
342 SmallVectorImpl<uint64_t> &Record,
unsigned &Abbrev);
343 void writeDISubrange(
const DISubrange *
N, SmallVectorImpl<uint64_t> &Record,
346 SmallVectorImpl<uint64_t> &Record,
349 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
353 SmallVectorImpl<uint64_t> &Record,
356 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
358 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
360 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
362 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
364 SmallVectorImpl<uint64_t> &Record,
366 void writeDIFile(
const DIFile *
N, 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,
378 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
381 void writeDIMacro(
const DIMacro *
N, SmallVectorImpl<uint64_t> &Record,
385 void writeDIArgList(
const DIArgList *
N, SmallVectorImpl<uint64_t> &Record);
386 void writeDIModule(
const DIModule *
N, SmallVectorImpl<uint64_t> &Record,
388 void writeDIAssignID(
const DIAssignID *
N, SmallVectorImpl<uint64_t> &Record,
391 SmallVectorImpl<uint64_t> &Record,
394 SmallVectorImpl<uint64_t> &Record,
397 SmallVectorImpl<uint64_t> &Record,
400 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
402 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
404 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
406 SmallVectorImpl<uint64_t> &Record,
409 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
410 void writeDIProperty(
const DIProperty *
N, SmallVectorImpl<uint64_t> &Record,
413 SmallVectorImpl<uint64_t> &Record,
415 unsigned createNamedMetadataAbbrev();
416 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
417 unsigned createMetadataStringsAbbrev();
419 SmallVectorImpl<uint64_t> &Record);
421 SmallVectorImpl<uint64_t> &Record,
422 std::vector<unsigned> *MDAbbrevs =
nullptr,
423 std::vector<uint64_t> *IndexPos =
nullptr);
424 void writeModuleMetadata();
425 void writeFunctionMetadata(
const Function &
F);
426 void writeFunctionMetadataAttachment(
const Function &
F);
427 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
428 const GlobalObject &GO);
429 void writeModuleMetadataKinds();
430 void writeOperandBundleTags();
431 void writeSyncScopeNames();
432 void writeConstants(
unsigned FirstVal,
unsigned LastVal,
bool isGlobal);
433 void writeModuleConstants();
434 bool pushValueAndType(
const Value *
V,
unsigned InstID,
435 SmallVectorImpl<unsigned> &Vals);
436 bool pushValueOrMetadata(
const Value *
V,
unsigned InstID,
437 SmallVectorImpl<unsigned> &Vals);
438 void writeOperandBundles(
const CallBase &CB,
unsigned InstID);
439 void pushValue(
const Value *
V,
unsigned InstID,
440 SmallVectorImpl<unsigned> &Vals);
441 void pushValueSigned(
const Value *
V,
unsigned InstID,
442 SmallVectorImpl<uint64_t> &Vals);
443 void writeInstruction(
const Instruction &
I,
unsigned InstID,
444 SmallVectorImpl<unsigned> &Vals);
445 void writeFunctionLevelValueSymbolTable(
const ValueSymbolTable &VST);
446 void writeGlobalValueSymbolTable(
447 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
448 void writeUseList(UseListOrder &&Order);
449 void writeUseListBlock(
const Function *
F);
452 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
453 void writeBlockInfo();
454 void writeModuleHash(StringRef View);
457 return unsigned(SSID);
460 unsigned getEncodedAlign(MaybeAlign Alignment) {
return encode(Alignment); }
464class IndexBitcodeWriter :
public BitcodeWriterBase {
466 const ModuleSummaryIndex &
Index;
482 SortedSummariesForIndex;
486 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
490 std::vector<uint64_t> StackIds;
495 DenseMap<unsigned, unsigned> StackIdIndicesToIndex;
498 unsigned GlobalValueId = 0;
502 DenseMap<StringRef, uint64_t> ModuleIdMap;
512 BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
513 const ModuleSummaryIndex &Index,
516 : BitcodeWriterBase(Stream, StrtabBuilder),
Index(
Index),
517 DecSummaries(DecSummaries),
518 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
519 if (ModuleToSummariesForIndex) {
520 for (
const auto &[ModPath, Summaries] : *ModuleToSummariesForIndex)
531 auto RecordStackIdReference = [&](
unsigned StackIdIndex) {
536 StackIdIndicesToIndex.
insert({StackIdIndex, StackIds.size()});
538 StackIds.push_back(
Index.getStackIdAtIndex(StackIdIndex));
545 forEachSummary([&](GVInfo
I,
bool IsAliasee) {
546 GUIDToValueIdMap[
I.first] = ++GlobalValueId;
558 for (
auto &CI :
FS->callsites()) {
569 if (CI.StackIdIndices.empty()) {
570 GUIDToValueIdMap[CI.Callee.getGUID()] = ++GlobalValueId;
573 for (
auto Idx : CI.StackIdIndices)
574 RecordStackIdReference(Idx);
577 for (
auto &AI :
FS->allocs())
578 for (
auto &MIB : AI.MIBs)
579 for (
auto Idx : MIB.StackIdIndices)
580 RecordStackIdReference(Idx);
586 using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
591 template<
typename Functor>
592 void forEachSummary(Functor Callback) {
593 if (ModuleToSummariesForIndex) {
594 for (
auto &[GUID, GVS] : SortedSummariesForIndex) {
600 Callback({AS->getAliaseeGUID(), &AS->getAliasee()},
true);
604 for (
const auto &Summaries :
Index.sortedGlobalValueSummariesRange())
605 for (
auto &Summary : Summaries.second.getSummaryList())
614 template <
typename Functor>
void forEachModule(Functor Callback) {
615 if (ModuleToSummariesForIndex) {
616 for (
const auto &M : *ModuleToSummariesForIndex) {
617 const auto &MPI =
Index.modulePaths().find(
M.first);
618 if (MPI ==
Index.modulePaths().end()) {
622 assert(ModuleToSummariesForIndex->size() == 1);
632 std::vector<StringRef> ModulePaths;
633 for (
auto &[ModPath,
_] :
Index.modulePaths())
634 ModulePaths.push_back(ModPath);
636 for (
auto &ModPath : ModulePaths)
645 void writeModStrings();
646 void writeCombinedGlobalValueSummary();
649 auto VMI = GUIDToValueIdMap.find(ValGUID);
650 if (VMI == GUIDToValueIdMap.end())
655 std::map<GlobalValue::GUID, unsigned> &valueIds() {
return GUIDToValueIdMap; }
690 case Instruction::Add:
692 case Instruction::Sub:
694 case Instruction::Mul:
697 case Instruction::FDiv:
700 case Instruction::FRem:
712 unsigned Encoding = 0;
713 switch (
I.getOperation()) {
786 if (
I.isElementwise())
821 case Attribute::Alignment:
823 case Attribute::AllocAlign:
825 case Attribute::AllocSize:
827 case Attribute::AlwaysInline:
829 case Attribute::Builtin:
831 case Attribute::ByVal:
833 case Attribute::Convergent:
835 case Attribute::InAlloca:
837 case Attribute::Cold:
839 case Attribute::DisableSanitizerInstrumentation:
841 case Attribute::FnRetThunkExtern:
843 case Attribute::Flatten:
847 case Attribute::ElementType:
849 case Attribute::HybridPatchable:
851 case Attribute::InlineHint:
853 case Attribute::InReg:
855 case Attribute::JumpTable:
857 case Attribute::MinSize:
859 case Attribute::AllocatedPointer:
861 case Attribute::AllocKind:
863 case Attribute::Memory:
865 case Attribute::NoFPClass:
867 case Attribute::Naked:
869 case Attribute::Nest:
871 case Attribute::NoAlias:
873 case Attribute::NoBuiltin:
875 case Attribute::NoCallback:
877 case Attribute::NoDivergenceSource:
879 case Attribute::NoDuplicate:
881 case Attribute::NoFree:
883 case Attribute::NoFreeObj:
885 case Attribute::NoImplicitFloat:
887 case Attribute::NoInline:
889 case Attribute::NoRecurse:
891 case Attribute::NoMerge:
893 case Attribute::NonLazyBind:
895 case Attribute::NonNull:
897 case Attribute::Dereferenceable:
899 case Attribute::DereferenceableOrNull:
901 case Attribute::NoRedZone:
903 case Attribute::NoReturn:
905 case Attribute::NoSync:
907 case Attribute::NoCfCheck:
909 case Attribute::NoProfile:
911 case Attribute::SkipProfile:
913 case Attribute::NoUnwind:
915 case Attribute::NoSanitizeBounds:
917 case Attribute::NoSanitizeCoverage:
919 case Attribute::NullPointerIsValid:
921 case Attribute::OptimizeForDebugging:
923 case Attribute::OptForFuzzing:
925 case Attribute::OptimizeForSize:
927 case Attribute::OptimizeNone:
929 case Attribute::ReadNone:
931 case Attribute::ReadOnly:
933 case Attribute::Returned:
935 case Attribute::ReturnsTwice:
937 case Attribute::SExt:
939 case Attribute::Speculatable:
941 case Attribute::StackAlignment:
943 case Attribute::StackProtect:
945 case Attribute::StackProtectReq:
947 case Attribute::StackProtectStrong:
949 case Attribute::SafeStack:
951 case Attribute::ShadowCallStack:
953 case Attribute::StrictFP:
955 case Attribute::StructRet:
957 case Attribute::SanitizeAddress:
959 case Attribute::SanitizeAllocToken:
961 case Attribute::SanitizeHWAddress:
963 case Attribute::SanitizeThread:
965 case Attribute::SanitizeConcurrency:
967 case Attribute::SanitizeType:
969 case Attribute::SanitizeMemory:
971 case Attribute::SanitizeNumericalStability:
973 case Attribute::SanitizeRealtime:
975 case Attribute::SanitizeRealtimeBlocking:
977 case Attribute::SpeculativeLoadHardening:
979 case Attribute::SwiftError:
981 case Attribute::SwiftSelf:
983 case Attribute::SwiftAsync:
985 case Attribute::UWTable:
987 case Attribute::VScaleRange:
989 case Attribute::WillReturn:
991 case Attribute::WriteOnly:
993 case Attribute::ZExt:
995 case Attribute::ImmArg:
997 case Attribute::SanitizeMemTag:
999 case Attribute::Preallocated:
1001 case Attribute::NoUndef:
1003 case Attribute::ByRef:
1005 case Attribute::MustProgress:
1007 case Attribute::PresplitCoroutine:
1009 case Attribute::Writable:
1011 case Attribute::CoroDestroyOnlyWhenComplete:
1013 case Attribute::CoroElideSafe:
1015 case Attribute::DeadOnUnwind:
1017 case Attribute::Range:
1019 case Attribute::Initializes:
1021 case Attribute::NoExt:
1023 case Attribute::Captures:
1025 case Attribute::DeadOnReturn:
1027 case Attribute::NoCreateUndefOrPoison:
1029 case Attribute::DenormalFPEnv:
1031 case Attribute::NoOutline:
1033 case Attribute::NoIPA:
1035 case Attribute::LikelyModuleLocal:
1050 if ((int64_t)
V >= 0)
1061 unsigned NumWords =
A.getActiveWords();
1062 const uint64_t *RawData =
A.getRawData();
1063 for (
unsigned i = 0; i < NumWords; i++)
1083void ModuleBitcodeWriter::writeAttributeGroupTable() {
1084 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
1086 if (AttrGrps.empty())
return;
1090 SmallVector<uint64_t, 64>
Record;
1092 unsigned AttrListIndex = Pair.first;
1093 AttributeSet AS = Pair.second;
1095 Record.push_back(AttrListIndex);
1098 if (Attr.isEnumAttribute()) {
1101 }
else if (Attr.isIntAttribute()) {
1103 Attribute::AttrKind
Kind = Attr.getKindAsEnum();
1105 if (Kind == Attribute::Memory) {
1110 Record.push_back(Attr.getValueAsInt());
1112 }
else if (Attr.isStringAttribute()) {
1113 StringRef
Kind = Attr.getKindAsString();
1114 StringRef Val = Attr.getValueAsString();
1123 }
else if (Attr.isTypeAttribute()) {
1124 Type *Ty = Attr.getValueAsType();
1125 Record.push_back(Ty ? 6 : 5);
1129 }
else if (Attr.isConstantRangeAttribute()) {
1135 assert(Attr.isConstantRangeListAttribute());
1141 for (
auto &CR : Val)
1153void ModuleBitcodeWriter::writeAttributeTable() {
1155 if (
Attrs.empty())
return;
1159 SmallVector<uint64_t, 64>
Record;
1160 for (
const AttributeList &AL : Attrs) {
1161 for (
unsigned i :
AL.indexes()) {
1162 AttributeSet AS =
AL.getAttributes(i);
1175void ModuleBitcodeWriter::writeTypeTable() {
1179 SmallVector<uint64_t, 64> TypeVals;
1184 auto Abbv = std::make_shared<BitCodeAbbrev>();
1186 Abbv->Add(BitCodeAbbrevOp(0));
1187 unsigned OpaquePtrAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1190 Abbv = std::make_shared<BitCodeAbbrev>();
1195 unsigned FunctionAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1198 Abbv = std::make_shared<BitCodeAbbrev>();
1203 unsigned StructAnonAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1206 Abbv = std::make_shared<BitCodeAbbrev>();
1210 unsigned StructNameAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1213 Abbv = std::make_shared<BitCodeAbbrev>();
1218 unsigned StructNamedAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1221 Abbv = std::make_shared<BitCodeAbbrev>();
1225 unsigned ArrayAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1233 for (
Type *
T : TypeList) {
1234 int AbbrevToUse = 0;
1237 switch (
T->getTypeID()) {
1247 case Type::MetadataTyID:
1252 case Type::ByteTyID:
1257 case Type::IntegerTyID:
1262 case Type::PointerTyID: {
1269 AbbrevToUse = OpaquePtrAbbrev;
1272 case Type::FunctionTyID: {
1278 for (
unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
1280 AbbrevToUse = FunctionAbbrev;
1283 case Type::StructTyID: {
1288 for (
Type *ET :
ST->elements())
1291 if (
ST->isLiteral()) {
1293 AbbrevToUse = StructAnonAbbrev;
1295 if (
ST->isOpaque()) {
1299 AbbrevToUse = StructNamedAbbrev;
1303 if (!
ST->getName().empty())
1309 case Type::ArrayTyID: {
1313 TypeVals.
push_back(AT->getNumElements());
1315 AbbrevToUse = ArrayAbbrev;
1318 case Type::FixedVectorTyID:
1319 case Type::ScalableVectorTyID: {
1324 TypeVals.
push_back(VT->getElementCount().getKnownMinValue());
1330 case Type::TargetExtTyID: {
1336 for (
Type *InnerTy :
TET->type_params())
1341 case Type::TypedPointerTyID:
1346 Stream.
EmitRecord(Code, TypeVals, AbbrevToUse);
1387 RawFlags |= Flags.ReadNone;
1388 RawFlags |= (Flags.ReadOnly << 1);
1389 RawFlags |= (Flags.NoRecurse << 2);
1390 RawFlags |= (Flags.ReturnDoesNotAlias << 3);
1391 RawFlags |= (Flags.NoInline << 4);
1392 RawFlags |= (Flags.AlwaysInline << 5);
1393 RawFlags |= (Flags.NoUnwind << 6);
1394 RawFlags |= (Flags.MayThrow << 7);
1395 RawFlags |= (Flags.HasUnknownCall << 8);
1396 RawFlags |= (Flags.MustBeUnreachable << 9);
1403 bool ImportAsDecl =
false) {
1406 RawFlags |= Flags.NotEligibleToImport;
1407 RawFlags |= (Flags.Live << 1);
1408 RawFlags |= (Flags.DSOLocal << 2);
1409 RawFlags |= (Flags.CanAutoHide << 3);
1414 RawFlags = (RawFlags << 4) | Flags.Linkage;
1416 RawFlags |= (Flags.Visibility << 8);
1418 unsigned ImportType = Flags.ImportType | ImportAsDecl;
1419 RawFlags |= (ImportType << 10);
1421 RawFlags |= (Flags.NoRenameOnPromotion << 11);
1427 uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) |
1428 (Flags.Constant << 2) | Flags.VCallVisibility << 3;
1472 switch (
C.getSelectionKind()) {
1496size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1499 return StrtabBuilder.
add(Str);
1502void ModuleBitcodeWriter::writeComdats() {
1517void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
1522 auto Abbv = std::make_shared<BitCodeAbbrev>();
1528 unsigned VSTOffsetAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1544 bool isChar6 =
true;
1545 for (
char C : Str) {
1548 if ((
unsigned char)
C & 128)
1557static_assert(
sizeof(GlobalValue::SanitizerMetadata) <=
sizeof(unsigned),
1558 "Sanitizer Metadata is too large for naive serialization.");
1561 return Meta.NoAddress | (
Meta.NoHWAddress << 1) |
1562 (
Meta.Memtag << 2) | (
Meta.IsDynInit << 3);
1568void ModuleBitcodeWriter::writeModuleInfo() {
1570 if (!
M.getTargetTriple().empty())
1572 M.getTargetTriple().str(), 0 );
1573 const std::string &
DL =
M.getDataLayoutStr();
1577 for (
const Module::GlobalAsmFragment &Frag :
M.getModuleInlineAsm()) {
1579 Frag.Props.getAsStrings();
1592 std::map<std::string, unsigned> SectionMap;
1593 std::map<std::string, unsigned> GCMap;
1594 MaybeAlign MaxGVarAlignment;
1595 unsigned MaxGlobalType = 0;
1596 for (
const GlobalVariable &GV :
M.globals()) {
1597 if (MaybeAlign
A = GV.getAlign())
1598 MaxGVarAlignment = !MaxGVarAlignment ? *
A : std::max(*MaxGVarAlignment, *
A);
1599 MaxGlobalType = std::max(MaxGlobalType, VE.
getTypeID(GV.getValueType()));
1600 if (GV.hasSection()) {
1602 unsigned &
Entry = SectionMap[std::string(GV.getSection())];
1606 Entry = SectionMap.size();
1611 if (
F.hasSection()) {
1613 unsigned &
Entry = SectionMap[std::string(
F.getSection())];
1617 Entry = SectionMap.size();
1622 unsigned &
Entry = GCMap[
F.getGC()];
1626 Entry = GCMap.size();
1632 unsigned SimpleGVarAbbrev = 0;
1633 if (!
M.global_empty()) {
1635 auto Abbv = std::make_shared<BitCodeAbbrev>();
1646 if (!MaxGVarAlignment)
1647 Abbv->Add(BitCodeAbbrevOp(0));
1649 unsigned MaxEncAlignment = getEncodedAlign(MaxGVarAlignment);
1653 if (SectionMap.empty())
1654 Abbv->Add(BitCodeAbbrevOp(0));
1659 SimpleGVarAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1673 auto Abbv = std::make_shared<BitCodeAbbrev>();
1676 Abbv->Add(AbbrevOpToUse);
1677 unsigned FilenameAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1679 for (
const auto P :
M.getSourceFileName())
1690 for (
const GlobalVariable &GV :
M.globals()) {
1691 unsigned AbbrevToUse = 0;
1697 Vals.
push_back(addToStrtab(GV.getName()));
1700 Vals.
push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1704 Vals.
push_back(getEncodedAlign(GV.getAlign()));
1705 Vals.
push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]
1707 if (GV.isThreadLocal() ||
1709 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1710 GV.isExternallyInitialized() ||
1712 GV.hasComdat() || GV.hasAttributes() || GV.isDSOLocal() ||
1713 GV.hasPartition() || GV.hasSanitizerMetadata() || GV.getCodeModel()) {
1717 Vals.
push_back(GV.isExternallyInitialized());
1721 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1725 Vals.
push_back(addToStrtab(GV.getPartition()));
1726 Vals.
push_back(GV.getPartition().size());
1729 GV.getSanitizerMetadata())
1733 AbbrevToUse = SimpleGVarAbbrev;
1754 Vals.
push_back(getEncodedAlign(
F.getAlign()));
1755 Vals.
push_back(
F.hasSection() ? SectionMap[std::string(
F.getSection())]
1767 F.hasPersonalityFn() ? (VE.
getValueID(
F.getPersonalityFn()) + 1) : 0);
1771 Vals.
push_back(addToStrtab(
F.getPartition()));
1773 Vals.
push_back(getEncodedAlign(
F.getPreferredAlignment()));
1775 unsigned AbbrevToUse = 0;
1781 for (
const GlobalAlias &
A :
M.aliases()) {
1788 Vals.
push_back(
A.getType()->getAddressSpace());
1796 Vals.
push_back(addToStrtab(
A.getPartition()));
1799 unsigned AbbrevToUse = 0;
1805 for (
const GlobalIFunc &
I :
M.ifuncs()) {
1811 Vals.
push_back(
I.getType()->getAddressSpace());
1816 Vals.
push_back(addToStrtab(
I.getPartition()));
1822 writeValueSymbolTableForwardDecl();
1829 if (OBO->hasNoSignedWrap())
1831 if (OBO->hasNoUnsignedWrap())
1837 if (PDI->isDisjoint())
1840 if (FPMO->hasAllowReassoc())
1842 if (FPMO->hasNoNaNs())
1844 if (FPMO->hasNoInfs())
1846 if (FPMO->hasNoSignedZeros())
1848 if (FPMO->hasAllowReciprocal())
1850 if (FPMO->hasAllowContract())
1852 if (FPMO->hasApproxFunc())
1858 if (NNI->hasNonNeg())
1862 if (NNI->hasNonNeg())
1865 if (TI->hasNoSignedWrap())
1867 if (TI->hasNoUnsignedWrap())
1870 if (
GEP->isInBounds())
1872 if (
GEP->hasNoUnsignedSignedWrap())
1874 if (
GEP->hasNoUnsignedWrap())
1877 if (ICmp->hasSameSign())
1880 if (ASC->hasNonNull())
1887void ModuleBitcodeWriter::writeValueAsMetadata(
1888 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
1897void ModuleBitcodeWriter::writeMDTuple(
const MDTuple *
N,
1898 SmallVectorImpl<uint64_t> &Record,
1900 for (
const MDOperand &MDO :
N->operands()) {
1903 "Unexpected function-local metadata");
1912unsigned ModuleBitcodeWriter::createDILocationAbbrev(
bool WithIRLayers) {
1918 auto Abbv = std::make_shared<BitCodeAbbrev>();
1933void ModuleBitcodeWriter::writeDILocation(
const DILocation *
N,
1934 SmallVectorImpl<uint64_t> &Record,
1937 Abbrev = createDILocationAbbrev(
false);
1939 Record.push_back(
N->isDistinct());
1940 Record.push_back(
N->getLine());
1941 Record.push_back(
N->getColumn());
1944 Record.push_back(
N->isImplicitCode());
1945 Record.push_back(
N->getAtomGroup());
1946 Record.push_back(
N->getAtomRank());
1948 unsigned AbbrevToUse = Abbrev;
1949 if (DILayerLocList *IRLayers =
N->getIRLayers()) {
1950 if (!DILocationLayersAbbrev)
1951 DILocationLayersAbbrev = createDILocationAbbrev(
true);
1952 AbbrevToUse = DILocationLayersAbbrev;
1960void ModuleBitcodeWriter::writeDILayerLoc(
const DILayerLoc *
N,
1961 SmallVectorImpl<uint64_t> &Record,
1963 Record.push_back(
N->isDistinct());
1964 Record.push_back(
N->getLine());
1965 Record.push_back(
N->getColumn());
1972void ModuleBitcodeWriter::writeDILayerLocList(
const DILayerLocList *
N,
1973 SmallVectorImpl<uint64_t> &Record,
1975 Record.push_back(
N->isDistinct());
1976 for (
const MDOperand &
Op :
N->layers())
1982unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1985 auto Abbv = std::make_shared<BitCodeAbbrev>();
1996void ModuleBitcodeWriter::writeGenericDINode(
const GenericDINode *
N,
1997 SmallVectorImpl<uint64_t> &Record,
2000 Abbrev = createGenericDINodeAbbrev();
2002 Record.push_back(
N->isDistinct());
2003 Record.push_back(
N->getTag());
2006 for (
auto &
I :
N->operands())
2013void ModuleBitcodeWriter::writeDISubrange(
const DISubrange *
N,
2014 SmallVectorImpl<uint64_t> &Record,
2027void ModuleBitcodeWriter::writeDIGenericSubrange(
2028 const DIGenericSubrange *
N, SmallVectorImpl<uint64_t> &Record,
2040void ModuleBitcodeWriter::writeDIEnumerator(
const DIEnumerator *
N,
2041 SmallVectorImpl<uint64_t> &Record,
2044 Record.push_back(IsBigInt | (
N->isUnsigned() << 1) |
N->isDistinct());
2045 Record.push_back(
N->getValue().getBitWidth());
2053void ModuleBitcodeWriter::writeDIBasicType(
const DIBasicType *
N,
2054 SmallVectorImpl<uint64_t> &Record,
2056 const unsigned SizeIsMetadata = 0x2;
2057 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2058 Record.push_back(
N->getTag());
2061 Record.push_back(
N->getAlignInBits());
2062 Record.push_back(
N->getEncoding());
2063 Record.push_back(
N->getFlags());
2064 Record.push_back(
N->getNumExtraInhabitants());
2065 Record.push_back(
N->getDataSizeInBits());
2067 Record.push_back(
N->getLine());
2074void ModuleBitcodeWriter::writeDIFixedPointType(
2075 const DIFixedPointType *
N, SmallVectorImpl<uint64_t> &Record,
2077 const unsigned SizeIsMetadata = 0x2;
2078 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2079 Record.push_back(
N->getTag());
2082 Record.push_back(
N->getAlignInBits());
2083 Record.push_back(
N->getEncoding());
2084 Record.push_back(
N->getFlags());
2085 Record.push_back(
N->getKind());
2086 Record.push_back(
N->getFactorRaw());
2088 auto WriteWideInt = [&](
const APInt &
Value) {
2093 Record.push_back(Encoded);
2097 WriteWideInt(
N->getNumeratorRaw());
2098 WriteWideInt(
N->getDenominatorRaw());
2101 Record.push_back(
N->getLine());
2108void ModuleBitcodeWriter::writeDIStringType(
const DIStringType *
N,
2109 SmallVectorImpl<uint64_t> &Record,
2111 const unsigned SizeIsMetadata = 0x2;
2112 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2113 Record.push_back(
N->getTag());
2119 Record.push_back(
N->getAlignInBits());
2120 Record.push_back(
N->getEncoding());
2127void ModuleBitcodeWriter::writeDIDerivedType(
const DIDerivedType *
N,
2128 SmallVectorImpl<uint64_t> &Record,
2130 const unsigned SizeIsMetadata = 0x2;
2131 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2132 Record.push_back(
N->getTag());
2135 Record.push_back(
N->getLine());
2139 Record.push_back(
N->getAlignInBits());
2141 Record.push_back(
N->getFlags());
2146 if (
const auto &DWARFAddressSpace =
N->getDWARFAddressSpace())
2147 Record.push_back(*DWARFAddressSpace + 1);
2153 if (
auto PtrAuthData =
N->getPtrAuthData())
2154 Record.push_back(PtrAuthData->RawData);
2162void ModuleBitcodeWriter::writeDISubrangeType(
const DISubrangeType *
N,
2163 SmallVectorImpl<uint64_t> &Record,
2165 const unsigned SizeIsMetadata = 0x2;
2166 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2169 Record.push_back(
N->getLine());
2172 Record.push_back(
N->getAlignInBits());
2173 Record.push_back(
N->getFlags());
2184void ModuleBitcodeWriter::writeDICompositeType(
2185 const DICompositeType *
N, SmallVectorImpl<uint64_t> &Record,
2187 const unsigned IsNotUsedInOldTypeRef = 0x2;
2188 const unsigned SizeIsMetadata = 0x4;
2189 Record.push_back(SizeIsMetadata | IsNotUsedInOldTypeRef |
2190 (
unsigned)
N->isDistinct());
2191 Record.push_back(
N->getTag());
2194 Record.push_back(
N->getLine());
2198 Record.push_back(
N->getAlignInBits());
2200 Record.push_back(
N->getFlags());
2202 Record.push_back(
N->getRuntimeLang());
2212 Record.push_back(
N->getNumExtraInhabitants());
2222void ModuleBitcodeWriter::writeDISubroutineType(
2223 const DISubroutineType *
N, SmallVectorImpl<uint64_t> &Record,
2225 const unsigned HasNoOldTypeRefs = 0x2;
2226 Record.push_back(HasNoOldTypeRefs | (
unsigned)
N->isDistinct());
2227 Record.push_back(
N->getFlags());
2235void ModuleBitcodeWriter::writeDIFile(
const DIFile *
N,
2236 SmallVectorImpl<uint64_t> &Record,
2238 Record.push_back(
N->isDistinct());
2241 if (
N->getRawChecksum()) {
2242 Record.push_back(
N->getRawChecksum()->Kind);
2250 auto Source =
N->getRawSource();
2258void ModuleBitcodeWriter::writeDICompileUnit(
const DICompileUnit *
N,
2259 SmallVectorImpl<uint64_t> &Record,
2261 assert(
N->isDistinct() &&
"Expected distinct compile units");
2264 auto Lang =
N->getSourceLanguage();
2265 Record.push_back(Lang.getName());
2268 if (Lang.hasVersionedName())
2273 Record.push_back(
N->isOptimized());
2275 Record.push_back(
N->getRuntimeVersion());
2277 Record.push_back(
N->getEmissionKind());
2283 Record.push_back(
N->getDWOId());
2285 Record.push_back(
N->getSplitDebugInlining());
2286 Record.push_back(
N->getDebugInfoForProfiling());
2287 Record.push_back((
unsigned)
N->getNameTableKind());
2288 Record.push_back(
N->getRangesBaseAddress());
2291 Record.push_back(Lang.hasVersionedName() ? Lang.getVersion() : 0);
2292 Record.push_back(Lang.getDialect());
2298void ModuleBitcodeWriter::writeDISubprogram(
const DISubprogram *
N,
2299 SmallVectorImpl<uint64_t> &Record,
2301 const uint64_t HasUnitFlag = 1 << 1;
2302 const uint64_t HasSPFlagsFlag = 1 << 2;
2303 Record.push_back(
uint64_t(
N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
2308 Record.push_back(
N->getLine());
2310 Record.push_back(
N->getScopeLine());
2312 Record.push_back(
N->getSPFlags());
2313 Record.push_back(
N->getVirtualIndex());
2314 Record.push_back(
N->getFlags());
2319 Record.push_back(
N->getThisAdjustment());
2323 Record.push_back(
N->getKeyInstructionsEnabled());
2329void ModuleBitcodeWriter::writeDILexicalBlock(
const DILexicalBlock *
N,
2330 SmallVectorImpl<uint64_t> &Record,
2332 Record.push_back(
N->isDistinct());
2335 Record.push_back(
N->getLine());
2336 Record.push_back(
N->getColumn());
2342void ModuleBitcodeWriter::writeDILexicalBlockFile(
2343 const DILexicalBlockFile *
N, SmallVectorImpl<uint64_t> &Record,
2345 Record.push_back(
N->isDistinct());
2348 Record.push_back(
N->getDiscriminator());
2354void ModuleBitcodeWriter::writeDICommonBlock(
const DICommonBlock *
N,
2355 SmallVectorImpl<uint64_t> &Record,
2357 Record.push_back(
N->isDistinct());
2362 Record.push_back(
N->getLineNo());
2368void ModuleBitcodeWriter::writeDINamespace(
const DINamespace *
N,
2369 SmallVectorImpl<uint64_t> &Record,
2371 Record.push_back(
N->isDistinct() |
N->getExportSymbols() << 1);
2379void ModuleBitcodeWriter::writeDIMacro(
const DIMacro *
N,
2380 SmallVectorImpl<uint64_t> &Record,
2382 Record.push_back(
N->isDistinct());
2383 Record.push_back(
N->getMacinfoType());
2384 Record.push_back(
N->getLine());
2392void ModuleBitcodeWriter::writeDIMacroFile(
const DIMacroFile *
N,
2393 SmallVectorImpl<uint64_t> &Record,
2395 Record.push_back(
N->isDistinct());
2396 Record.push_back(
N->getMacinfoType());
2397 Record.push_back(
N->getLine());
2405void ModuleBitcodeWriter::writeDIArgList(
const DIArgList *
N,
2406 SmallVectorImpl<uint64_t> &Record) {
2407 Record.reserve(
N->getArgs().size());
2408 for (ValueAsMetadata *MD :
N->getArgs())
2415void ModuleBitcodeWriter::writeDIModule(
const DIModule *
N,
2416 SmallVectorImpl<uint64_t> &Record,
2418 Record.push_back(
N->isDistinct());
2419 for (
auto &
I :
N->operands())
2421 Record.push_back(
N->getLineNo());
2422 Record.push_back(
N->getIsDecl());
2428void ModuleBitcodeWriter::writeDIAssignID(
const DIAssignID *
N,
2429 SmallVectorImpl<uint64_t> &Record,
2432 Record.push_back(
N->isDistinct());
2437void ModuleBitcodeWriter::writeDITemplateTypeParameter(
2438 const DITemplateTypeParameter *
N, SmallVectorImpl<uint64_t> &Record,
2440 Record.push_back(
N->isDistinct());
2443 Record.push_back(
N->isDefault());
2449void ModuleBitcodeWriter::writeDITemplateValueParameter(
2450 const DITemplateValueParameter *
N, SmallVectorImpl<uint64_t> &Record,
2452 Record.push_back(
N->isDistinct());
2453 Record.push_back(
N->getTag());
2456 Record.push_back(
N->isDefault());
2463void ModuleBitcodeWriter::writeDIGlobalVariable(
2464 const DIGlobalVariable *
N, SmallVectorImpl<uint64_t> &Record,
2472 Record.push_back(
N->getLine());
2474 Record.push_back(
N->isLocalToUnit());
2475 Record.push_back(
N->isDefinition());
2478 Record.push_back(
N->getAlignInBits());
2485void ModuleBitcodeWriter::writeDILocalVariable(
2486 const DILocalVariable *
N, SmallVectorImpl<uint64_t> &Record,
2501 const uint64_t HasAlignmentFlag = 1 << 1;
2506 Record.push_back(
N->getLine());
2508 Record.push_back(
N->getArg());
2509 Record.push_back(
N->getFlags());
2510 Record.push_back(
N->getAlignInBits());
2517void ModuleBitcodeWriter::writeDILabel(
2518 const DILabel *
N, SmallVectorImpl<uint64_t> &Record,
2525 Record.push_back(
N->getLine());
2526 Record.push_back(
N->getColumn());
2527 Record.push_back(
N->getCoroSuspendIdx().has_value()
2528 ? (
uint64_t)
N->getCoroSuspendIdx().value()
2529 : std::numeric_limits<uint64_t>::max());
2535void ModuleBitcodeWriter::writeDIExpression(
const DIExpression *
N,
2536 SmallVectorImpl<uint64_t> &Record,
2538 Record.reserve(
N->getElements().size() + 1);
2541 Record.append(
N->elements_begin(),
N->elements_end());
2547void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
2548 const DIGlobalVariableExpression *
N, SmallVectorImpl<uint64_t> &Record,
2550 Record.push_back(
N->isDistinct());
2558void ModuleBitcodeWriter::writeDIObjCProperty(
const DIObjCProperty *
N,
2559 SmallVectorImpl<uint64_t> &Record,
2561 Record.push_back(
N->isDistinct());
2564 Record.push_back(
N->getLine());
2567 Record.push_back(
N->getAttributes());
2574void ModuleBitcodeWriter::writeDIProperty(
const DIProperty *
N,
2575 SmallVectorImpl<uint64_t> &Record,
2577 Record.push_back(
N->isDistinct());
2580 Record.push_back(
N->getLine());
2588void ModuleBitcodeWriter::writeDIImportedEntity(
2589 const DIImportedEntity *
N, SmallVectorImpl<uint64_t> &Record,
2591 Record.push_back(
N->isDistinct());
2592 Record.push_back(
N->getTag());
2595 Record.push_back(
N->getLine());
2604unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
2605 auto Abbv = std::make_shared<BitCodeAbbrev>();
2612void ModuleBitcodeWriter::writeNamedMetadata(
2613 SmallVectorImpl<uint64_t> &Record) {
2614 if (
M.named_metadata_empty())
2617 unsigned Abbrev = createNamedMetadataAbbrev();
2618 for (
const NamedMDNode &NMD :
M.named_metadata()) {
2620 StringRef Str = NMD.getName();
2621 Record.append(Str.bytes_begin(), Str.bytes_end());
2626 for (
const MDNode *
N : NMD.operands())
2633unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
2634 auto Abbv = std::make_shared<BitCodeAbbrev>();
2646void ModuleBitcodeWriter::writeMetadataStrings(
2648 if (Strings.
empty())
2656 SmallString<256> Blob;
2658 BitstreamWriter
W(Blob);
2678#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
2679#include "llvm/IR/Metadata.def"
2683void ModuleBitcodeWriter::writeMetadataRecords(
2685 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
2690#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
2691#include "llvm/IR/Metadata.def"
2697 assert(
N->isResolved() &&
"Expected forward references to be resolved");
2699 switch (
N->getMetadataID()) {
2702#define HANDLE_MDNODE_LEAF(CLASS) \
2703 case Metadata::CLASS##Kind: \
2705 write##CLASS(cast<CLASS>(N), Record, \
2706 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
2708 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
2710#include "llvm/IR/Metadata.def"
2721void ModuleBitcodeWriter::writeModuleMetadata() {
2722 if (!VE.
hasMDs() &&
M.named_metadata_empty())
2726 SmallVector<uint64_t, 64>
Record;
2730 std::vector<unsigned> MDAbbrevs;
2733 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] =
2734 createDILocationAbbrev(
false);
2735 DILocationLayersAbbrev = createDILocationAbbrev(
true);
2736 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
2737 createGenericDINodeAbbrev();
2739 auto Abbv = std::make_shared<BitCodeAbbrev>();
2743 unsigned OffsetAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
2745 Abbv = std::make_shared<BitCodeAbbrev>();
2749 unsigned IndexAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
2771 std::vector<uint64_t> IndexPos;
2775 writeMetadataRecords(VE.
getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2786 uint64_t PreviousValue = IndexOffsetRecordBitPos;
2787 for (
auto &Elt : IndexPos) {
2788 auto EltDelta = Elt - PreviousValue;
2789 PreviousValue = Elt;
2798 writeNamedMetadata(Record);
2800 auto AddDeclAttachedMetadata = [&](
const GlobalObject &GO) {
2801 SmallVector<uint64_t, 4>
Record;
2803 pushGlobalMetadataAttachment(Record, GO);
2807 if (
F.isDeclaration() &&
F.hasMetadata())
2808 AddDeclAttachedMetadata(
F);
2809 for (
const GlobalIFunc &GI :
M.ifuncs())
2810 if (GI.hasMetadata())
2811 AddDeclAttachedMetadata(GI);
2814 for (
const GlobalVariable &GV :
M.globals())
2815 if (GV.hasMetadata())
2816 AddDeclAttachedMetadata(GV);
2821void ModuleBitcodeWriter::writeFunctionMetadata(
const Function &
F) {
2828 DILocationLayersAbbrev = 0;
2829 SmallVector<uint64_t, 64>
Record;
2835void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2836 SmallVectorImpl<uint64_t> &Record,
const GlobalObject &GO) {
2840 for (
const auto &
I : MDs) {
2846void ModuleBitcodeWriter::writeFunctionMetadataAttachment(
const Function &
F) {
2849 SmallVector<uint64_t, 64>
Record;
2851 if (
F.hasMetadata()) {
2852 pushGlobalMetadataAttachment(Record,
F);
2860 for (
const BasicBlock &BB :
F)
2861 for (
const Instruction &
I : BB) {
2863 I.getAllMetadataOtherThanDebugLoc(MDs);
2866 if (MDs.
empty())
continue;
2870 for (
const auto &[ID, MD] : MDs) {
2881void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2882 SmallVector<uint64_t, 64>
Record;
2887 M.getMDKindNames(Names);
2889 if (Names.
empty())
return;
2893 for (
unsigned MDKindID = 0, e = Names.
size(); MDKindID != e; ++MDKindID) {
2894 Record.push_back(MDKindID);
2895 StringRef KName = Names[MDKindID];
2905void ModuleBitcodeWriter::writeOperandBundleTags() {
2913 M.getOperandBundleTags(Tags);
2920 SmallVector<uint64_t, 64>
Record;
2922 for (
auto Tag : Tags) {
2932void ModuleBitcodeWriter::writeSyncScopeNames() {
2934 M.getContext().getSyncScopeNames(SSNs);
2940 SmallVector<uint64_t, 64>
Record;
2941 for (
auto SSN : SSNs) {
2942 Record.append(SSN.begin(), SSN.end());
2950void ModuleBitcodeWriter::writeConstants(
unsigned FirstVal,
unsigned LastVal,
2952 if (FirstVal == LastVal)
return;
2956 unsigned AggregateAbbrev = 0;
2957 unsigned String8Abbrev = 0;
2958 unsigned CString7Abbrev = 0;
2959 unsigned CString6Abbrev = 0;
2963 auto Abbv = std::make_shared<BitCodeAbbrev>();
2967 AggregateAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
2970 Abbv = std::make_shared<BitCodeAbbrev>();
2974 String8Abbrev = Stream.
EmitAbbrev(std::move(Abbv));
2976 Abbv = std::make_shared<BitCodeAbbrev>();
2980 CString7Abbrev = Stream.
EmitAbbrev(std::move(Abbv));
2982 Abbv = std::make_shared<BitCodeAbbrev>();
2986 CString6Abbrev = Stream.
EmitAbbrev(std::move(Abbv));
2989 SmallVector<uint64_t, 64>
Record;
2992 Type *LastTy =
nullptr;
2993 for (
unsigned i = FirstVal; i != LastVal; ++i) {
2994 const Value *
V = Vals[i].first;
2996 if (
V->getType() != LastTy) {
2997 LastTy =
V->getType();
3000 CONSTANTS_SETTYPE_ABBREV);
3007 unsigned(
IA->hasSideEffects()) |
unsigned(
IA->isAlignStack()) << 1 |
3008 unsigned(
IA->getDialect() & 1) << 2 |
unsigned(
IA->canThrow()) << 3);
3011 StringRef AsmStr =
IA->getAsmString();
3016 StringRef ConstraintStr =
IA->getConstraintString();
3024 unsigned Code = -1U;
3025 unsigned AbbrevToUse = 0;
3026 if (
C->isNullValue()) {
3033 if (
IV->getBitWidth() <= 64) {
3037 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
3043 if (BV->getBitWidth() <= 64) {
3047 AbbrevToUse = CONSTANTS_BYTE_ABBREV;
3057 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
3061 APInt api = CFP->getValueAPF().bitcastToAPInt();
3063 Record.push_back((p[1] << 48) | (p[0] >> 16));
3064 Record.push_back(p[0] & 0xffffLL);
3066 APInt api = CFP->getValueAPF().bitcastToAPInt();
3071 assert(0 &&
"Unknown FP type!");
3077 uint64_t NumElts = Str->getNumElements();
3079 if (Str->isCString()) {
3084 AbbrevToUse = String8Abbrev;
3088 for (
uint64_t i = 0; i != NumElts; ++i) {
3089 unsigned char V = Str->getElementAsInteger(i);
3091 isCStr7 &= (
V & 128) == 0;
3097 AbbrevToUse = CString6Abbrev;
3099 AbbrevToUse = CString7Abbrev;
3100 }
else if (
const ConstantDataSequential *CDS =
3103 Type *EltTy = CDS->getElementType();
3105 for (
uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i)
3106 Record.push_back(CDS->getElementAsInteger(i));
3108 for (
uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i)
3110 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
3114 for (
const Value *
Op :
C->operands())
3116 AbbrevToUse = AggregateAbbrev;
3118 switch (
CE->getOpcode()) {
3125 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
3127 assert(
CE->getNumOperands() == 2 &&
"Unknown constant expr!");
3137 case Instruction::GetElementPtr: {
3142 if (std::optional<ConstantRange>
Range = GO->getInRange()) {
3146 for (
const Value *
Op :
CE->operands()) {
3152 case Instruction::ExtractElement:
3159 case Instruction::InsertElement:
3166 case Instruction::ShuffleVector:
3171 if (
C->getType() ==
C->getOperand(0)->getType()) {
3208 Stream.
EmitRecord(Code, Record, AbbrevToUse);
3215void ModuleBitcodeWriter::writeModuleConstants() {
3220 for (
unsigned i = 0, e = Vals.size(); i != e; ++i) {
3222 writeConstants(i, Vals.size(),
true);
3236bool ModuleBitcodeWriter::pushValueAndType(
const Value *
V,
unsigned InstID,
3237 SmallVectorImpl<unsigned> &Vals) {
3241 if (ValID >= InstID) {
3248bool ModuleBitcodeWriter::pushValueOrMetadata(
const Value *
V,
unsigned InstID,
3249 SmallVectorImpl<unsigned> &Vals) {
3250 bool IsMetadata =
V->getType()->isMetadataTy();
3258 return pushValueAndType(
V, InstID, Vals);
3261void ModuleBitcodeWriter::writeOperandBundles(
const CallBase &CS,
3268 Record.push_back(
C.getOperandBundleTagID(Bundle.getTagName()));
3270 for (
auto &Input : Bundle.Inputs)
3271 pushValueOrMetadata(Input, InstID, Record);
3280void ModuleBitcodeWriter::pushValue(
const Value *
V,
unsigned InstID,
3281 SmallVectorImpl<unsigned> &Vals) {
3286void ModuleBitcodeWriter::pushValueSigned(
const Value *
V,
unsigned InstID,
3287 SmallVectorImpl<uint64_t> &Vals) {
3289 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
3294void ModuleBitcodeWriter::writeInstruction(
const Instruction &
I,
3296 SmallVectorImpl<unsigned> &Vals) {
3298 unsigned AbbrevToUse = 0;
3300 switch (
I.getOpcode()) {
3304 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3305 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
3310 if (AbbrevToUse == FUNCTION_INST_CAST_ABBREV)
3311 AbbrevToUse = FUNCTION_INST_CAST_FLAGS_ABBREV;
3317 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3318 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
3319 pushValue(
I.getOperand(1), InstID, Vals);
3323 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
3324 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
3329 case Instruction::FNeg: {
3331 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3332 AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
3336 if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
3337 AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
3342 case Instruction::GetElementPtr: {
3344 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
3348 for (
const Value *
Op :
I.operands())
3349 pushValueAndType(
Op, InstID, Vals);
3352 case Instruction::ExtractValue: {
3354 pushValueAndType(
I.getOperand(0), InstID, Vals);
3359 case Instruction::InsertValue: {
3361 pushValueAndType(
I.getOperand(0), InstID, Vals);
3362 pushValueAndType(
I.getOperand(1), InstID, Vals);
3367 case Instruction::Select: {
3369 pushValueAndType(
I.getOperand(1), InstID, Vals);
3370 pushValue(
I.getOperand(2), InstID, Vals);
3371 pushValueAndType(
I.getOperand(0), InstID, Vals);
3377 case Instruction::ExtractElement:
3379 pushValueAndType(
I.getOperand(0), InstID, Vals);
3380 pushValueAndType(
I.getOperand(1), InstID, Vals);
3382 case Instruction::InsertElement:
3384 pushValueAndType(
I.getOperand(0), InstID, Vals);
3385 pushValue(
I.getOperand(1), InstID, Vals);
3386 pushValueAndType(
I.getOperand(2), InstID, Vals);
3388 case Instruction::BitExtract:
3391 pushValueAndType(
I.getOperand(0), InstID, Vals);
3392 pushValueAndType(
I.getOperand(1), InstID, Vals);
3394 case Instruction::BitInsert:
3396 pushValueAndType(
I.getOperand(0), InstID, Vals);
3397 pushValueAndType(
I.getOperand(1), InstID, Vals);
3398 pushValueAndType(
I.getOperand(2), InstID, Vals);
3400 case Instruction::ShuffleVector:
3402 pushValueAndType(
I.getOperand(0), InstID, Vals);
3403 pushValue(
I.getOperand(1), InstID, Vals);
3407 case Instruction::ICmp:
3408 case Instruction::FCmp: {
3411 AbbrevToUse = FUNCTION_INST_CMP_ABBREV;
3412 if (pushValueAndType(
I.getOperand(0), InstID, Vals))
3414 pushValue(
I.getOperand(1), InstID, Vals);
3420 AbbrevToUse = FUNCTION_INST_CMP_FLAGS_ABBREV;
3425 case Instruction::Ret:
3428 unsigned NumOperands =
I.getNumOperands();
3429 if (NumOperands == 0)
3430 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
3431 else if (NumOperands == 1) {
3432 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3433 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
3435 for (
const Value *
Op :
I.operands())
3436 pushValueAndType(
Op, InstID, Vals);
3440 case Instruction::UncondBr: {
3442 AbbrevToUse = FUNCTION_INST_BR_UNCOND_ABBREV;
3446 case Instruction::CondBr: {
3448 AbbrevToUse = FUNCTION_INST_BR_COND_ABBREV;
3452 pushValue(
II.getCondition(), InstID, Vals);
3454 case Instruction::Switch:
3459 pushValue(
SI.getCondition(), InstID, Vals);
3461 for (
auto Case :
SI.cases()) {
3467 case Instruction::IndirectBr:
3471 pushValue(
I.getOperand(0), InstID, Vals);
3476 case Instruction::Invoke: {
3479 FunctionType *FTy =
II->getFunctionType();
3481 if (
II->hasOperandBundles())
3482 writeOperandBundles(*
II, InstID);
3491 pushValueAndType(Callee, InstID, Vals);
3494 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3495 pushValue(
I.getOperand(i), InstID, Vals);
3498 if (FTy->isVarArg()) {
3499 for (
unsigned i = FTy->getNumParams(), e =
II->arg_size(); i != e; ++i)
3500 pushValueAndType(
I.getOperand(i), InstID, Vals);
3504 case Instruction::Resume:
3506 pushValueAndType(
I.getOperand(0), InstID, Vals);
3508 case Instruction::CleanupRet: {
3511 pushValue(CRI.getCleanupPad(), InstID, Vals);
3512 if (CRI.hasUnwindDest())
3516 case Instruction::CatchRet: {
3519 pushValue(CRI.getCatchPad(), InstID, Vals);
3523 case Instruction::CleanupPad:
3524 case Instruction::CatchPad: {
3528 pushValue(FuncletPad.getParentPad(), InstID, Vals);
3530 unsigned NumArgOperands = FuncletPad.arg_size();
3532 for (
unsigned Op = 0;
Op != NumArgOperands; ++
Op)
3533 pushValueAndType(FuncletPad.getArgOperand(
Op), InstID, Vals);
3536 case Instruction::CatchSwitch: {
3540 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
3542 unsigned NumHandlers = CatchSwitch.getNumHandlers();
3544 for (
const BasicBlock *CatchPadBB : CatchSwitch.handlers())
3547 if (CatchSwitch.hasUnwindDest())
3551 case Instruction::CallBr: {
3557 writeOperandBundles(*CBI, InstID);
3572 pushValueAndType(Callee, InstID, Vals);
3575 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3576 pushValue(
I.getOperand(i), InstID, Vals);
3579 if (FTy->isVarArg()) {
3580 for (
unsigned i = FTy->getNumParams(), e = CBI->
arg_size(); i != e; ++i)
3581 pushValueAndType(
I.getOperand(i), InstID, Vals);
3585 case Instruction::Unreachable:
3587 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
3590 case Instruction::PHI: {
3608 Stream.
EmitRecord(Code, Vals64, AbbrevToUse);
3613 case Instruction::LandingPad: {
3624 pushValueAndType(LP.
getClause(
I), InstID, Vals);
3629 case Instruction::Alloca: {
3635 using APV = AllocaPackedValues;
3637 unsigned EncodedAlign = getEncodedAlign(AI.
getAlign());
3639 Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1));
3641 EncodedAlign >> APV::AlignLower::Bits);
3648 if (AS !=
M.getDataLayout().getAllocaAddrSpace())
3653 case Instruction::Load: {
3655 if (LI.isAtomic()) {
3657 pushValueAndType(LI.getOperand(0), InstID, Vals);
3660 if (!pushValueAndType(LI.getOperand(0), InstID, Vals))
3661 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
3664 Vals.
push_back(getEncodedAlign(LI.getAlign()));
3666 if (LI.isAtomic()) {
3668 Vals.
push_back(getEncodedSyncScopeID(LI.getSyncScopeID()));
3669 if (LI.isElementwise())
3675 case Instruction::Store: {
3677 if (
SI.isAtomic()) {
3681 AbbrevToUse = FUNCTION_INST_STORE_ABBREV;
3683 if (pushValueAndType(
I.getOperand(1), InstID, Vals))
3685 if (pushValueAndType(
I.getOperand(0), InstID, Vals))
3689 if (
SI.isAtomic()) {
3691 Vals.
push_back(getEncodedSyncScopeID(
SI.getSyncScopeID()));
3692 if (
SI.isElementwise())
3698 case Instruction::AtomicCmpXchg:
3700 pushValueAndType(
I.getOperand(0), InstID, Vals);
3701 pushValueAndType(
I.getOperand(1), InstID, Vals);
3702 pushValue(
I.getOperand(2), InstID, Vals);
3713 case Instruction::AtomicRMW:
3715 pushValueAndType(
I.getOperand(0), InstID, Vals);
3716 pushValueAndType(
I.getOperand(1), InstID, Vals);
3724 case Instruction::Fence:
3729 case Instruction::Call: {
3734 writeOperandBundles(CI, InstID);
3754 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3758 if (FTy->isVarArg()) {
3759 for (
unsigned i = FTy->getNumParams(), e = CI.
arg_size(); i != e; ++i)
3764 case Instruction::VAArg:
3767 pushValue(
I.getOperand(0), InstID, Vals);
3770 case Instruction::Freeze:
3772 pushValueAndType(
I.getOperand(0), InstID, Vals);
3782void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3783 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3788 VSTOffset -= bitcodeStartBit();
3789 assert((VSTOffset & 31) == 0 &&
"VST block not 32-bit aligned");
3793 Stream.
BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
3797 auto Abbv = std::make_shared<BitCodeAbbrev>();
3801 unsigned FnEntryAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
3806 if (
F.isDeclaration())
3813 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&
F] - bitcodeStartBit();
3814 assert((BitcodeIndex & 31) == 0 &&
"function block not 32-bit aligned");
3818 Record[1] = BitcodeIndex / 32 + 1;
3827void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3828 const ValueSymbolTable &VST) {
3836 SmallVector<uint64_t, 64> NameVals;
3842 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3851 AbbrevToUse = VST_BBENTRY_6_ABBREV;
3855 AbbrevToUse = VST_ENTRY_6_ABBREV;
3857 AbbrevToUse = VST_ENTRY_7_ABBREV;
3860 for (
const auto P :
Name.getKey())
3864 Stream.
EmitRecord(Code, NameVals, AbbrevToUse);
3871void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3872 assert(Order.Shuffle.size() >= 2 &&
"Shuffle too small");
3879 SmallVector<uint64_t, 64>
Record(Order.Shuffle.begin(), Order.Shuffle.end());
3884void ModuleBitcodeWriter::writeUseListBlock(
const Function *
F) {
3886 "Expected to be preserving use-list order");
3888 auto hasMore = [&]() {
3904void ModuleBitcodeWriter::writeFunction(
3906 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3923 unsigned CstStart, CstEnd;
3925 writeConstants(CstStart, CstEnd,
false);
3928 writeFunctionMetadata(
F);
3931 unsigned InstID = CstEnd;
3933 bool NeedsMetadataAttachment =
F.hasMetadata();
3935 DILocation *LastDL =
nullptr;
3936 SmallSetVector<Function *, 4> BlockAddressUsers;
3939 for (
const BasicBlock &BB :
F) {
3940 for (
const Instruction &
I : BB) {
3941 writeInstruction(
I, InstID, Vals);
3943 if (!
I.getType()->isVoidTy())
3947 NeedsMetadataAttachment |=
I.hasMetadataOtherThanDebugLoc();
3950 if (DILocation *
DL =
I.getDebugLoc()) {
3963 unsigned DLAbbrev = FUNCTION_DEBUG_LOC_ABBREV;
3964 if (DILayerLocList *IRLayers =
DL->getIRLayers()) {
3965 DLAbbrev = FUNCTION_DEBUG_LOC_LAYERS_ABBREV;
3979 if (
I.hasDbgRecords()) {
3983 auto PushValueOrMetadata = [&Vals, InstID,
3986 "RawLocation unexpectedly null in DbgVariableRecord");
3988 SmallVector<unsigned, 2> ValAndType;
3992 if (!pushValueAndType(VAM->getValue(), InstID, ValAndType)) {
4006 for (DbgRecord &DR :
I.getDbgMarker()->getDbgRecordRange()) {
4032 FUNCTION_DEBUG_RECORD_VALUE_ABBREV);
4056 SmallPtrSet<Value *, 8> Visited{BA};
4057 while (!Worklist.
empty()) {
4059 for (User *U :
V->users()) {
4065 Visited.
insert(U).second)
4072 if (!BlockAddressUsers.
empty()) {
4081 if (
auto *Symtab =
F.getValueSymbolTable())
4082 writeFunctionLevelValueSymbolTable(*Symtab);
4084 if (NeedsMetadataAttachment)
4085 writeFunctionMetadataAttachment(
F);
4087 writeUseListBlock(&
F);
4093void ModuleBitcodeWriter::writeBlockInfo() {
4106 auto Abbv = std::make_shared<BitCodeAbbrev>();
4117 auto Abbv = std::make_shared<BitCodeAbbrev>();
4127 auto Abbv = std::make_shared<BitCodeAbbrev>();
4137 auto Abbv = std::make_shared<BitCodeAbbrev>();
4143 VST_BBENTRY_6_ABBREV)
4148 auto Abbv = std::make_shared<BitCodeAbbrev>();
4150 Abbv->Add(TypeAbbrevOp);
4152 CONSTANTS_SETTYPE_ABBREV)
4157 auto Abbv = std::make_shared<BitCodeAbbrev>();
4161 CONSTANTS_INTEGER_ABBREV)
4166 auto Abbv = std::make_shared<BitCodeAbbrev>();
4170 CONSTANTS_BYTE_ABBREV)
4175 auto Abbv = std::make_shared<BitCodeAbbrev>();
4183 CONSTANTS_CE_CAST_Abbrev)
4187 auto Abbv = std::make_shared<BitCodeAbbrev>();
4190 CONSTANTS_NULL_Abbrev)
4197 auto Abbv = std::make_shared<BitCodeAbbrev>();
4199 Abbv->Add(ValAbbrevOp);
4200 Abbv->Add(TypeAbbrevOp);
4204 FUNCTION_INST_LOAD_ABBREV)
4208 auto Abbv = std::make_shared<BitCodeAbbrev>();
4210 Abbv->Add(ValAbbrevOp);
4211 Abbv->Add(ValAbbrevOp);
4215 FUNCTION_INST_STORE_ABBREV)
4219 auto Abbv = std::make_shared<BitCodeAbbrev>();
4221 Abbv->Add(ValAbbrevOp);
4224 FUNCTION_INST_UNOP_ABBREV)
4228 auto Abbv = std::make_shared<BitCodeAbbrev>();
4230 Abbv->Add(ValAbbrevOp);
4234 FUNCTION_INST_UNOP_FLAGS_ABBREV)
4238 auto Abbv = std::make_shared<BitCodeAbbrev>();
4240 Abbv->Add(ValAbbrevOp);
4241 Abbv->Add(ValAbbrevOp);
4244 FUNCTION_INST_BINOP_ABBREV)
4248 auto Abbv = std::make_shared<BitCodeAbbrev>();
4250 Abbv->Add(ValAbbrevOp);
4251 Abbv->Add(ValAbbrevOp);
4255 FUNCTION_INST_BINOP_FLAGS_ABBREV)
4259 auto Abbv = std::make_shared<BitCodeAbbrev>();
4261 Abbv->Add(ValAbbrevOp);
4262 Abbv->Add(TypeAbbrevOp);
4265 FUNCTION_INST_CAST_ABBREV)
4269 auto Abbv = std::make_shared<BitCodeAbbrev>();
4271 Abbv->Add(ValAbbrevOp);
4272 Abbv->Add(TypeAbbrevOp);
4276 FUNCTION_INST_CAST_FLAGS_ABBREV)
4281 auto Abbv = std::make_shared<BitCodeAbbrev>();
4284 FUNCTION_INST_RET_VOID_ABBREV)
4288 auto Abbv = std::make_shared<BitCodeAbbrev>();
4290 Abbv->Add(ValAbbrevOp);
4292 FUNCTION_INST_RET_VAL_ABBREV)
4296 auto Abbv = std::make_shared<BitCodeAbbrev>();
4299 Abbv->Add(ValAbbrevOp);
4301 FUNCTION_INST_BR_UNCOND_ABBREV)
4305 auto Abbv = std::make_shared<BitCodeAbbrev>();
4308 Abbv->Add(ValAbbrevOp);
4309 Abbv->Add(ValAbbrevOp);
4310 Abbv->Add(ValAbbrevOp);
4312 FUNCTION_INST_BR_COND_ABBREV)
4316 auto Abbv = std::make_shared<BitCodeAbbrev>();
4319 FUNCTION_INST_UNREACHABLE_ABBREV)
4323 auto Abbv = std::make_shared<BitCodeAbbrev>();
4326 Abbv->Add(TypeAbbrevOp);
4328 Abbv->Add(ValAbbrevOp);
4330 FUNCTION_INST_GEP_ABBREV)
4334 auto Abbv = std::make_shared<BitCodeAbbrev>();
4336 Abbv->Add(ValAbbrevOp);
4337 Abbv->Add(ValAbbrevOp);
4340 FUNCTION_INST_CMP_ABBREV)
4344 auto Abbv = std::make_shared<BitCodeAbbrev>();
4346 Abbv->Add(ValAbbrevOp);
4347 Abbv->Add(ValAbbrevOp);
4351 FUNCTION_INST_CMP_FLAGS_ABBREV)
4355 auto Abbv = std::make_shared<BitCodeAbbrev>();
4360 Abbv->Add(ValAbbrevOp);
4362 FUNCTION_DEBUG_RECORD_VALUE_ABBREV)
4366 auto Abbv = std::make_shared<BitCodeAbbrev>();
4377 FUNCTION_DEBUG_LOC_ABBREV)
4383 auto Abbv = std::make_shared<BitCodeAbbrev>();
4394 FUNCTION_DEBUG_LOC_LAYERS_ABBREV)
4402void IndexBitcodeWriter::writeModStrings() {
4408 auto Abbv = std::make_shared<BitCodeAbbrev>();
4413 unsigned Abbrev8Bit = Stream.
EmitAbbrev(std::move(Abbv));
4416 Abbv = std::make_shared<BitCodeAbbrev>();
4421 unsigned Abbrev7Bit = Stream.
EmitAbbrev(std::move(Abbv));
4424 Abbv = std::make_shared<BitCodeAbbrev>();
4429 unsigned Abbrev6Bit = Stream.
EmitAbbrev(std::move(Abbv));
4432 Abbv = std::make_shared<BitCodeAbbrev>();
4439 unsigned AbbrevHash = Stream.
EmitAbbrev(std::move(Abbv));
4442 forEachModule([&](
const StringMapEntry<ModuleHash> &MPSE) {
4444 const auto &Hash = MPSE.
getValue();
4446 unsigned AbbrevToUse = Abbrev8Bit;
4448 AbbrevToUse = Abbrev6Bit;
4450 AbbrevToUse = Abbrev7Bit;
4452 auto ModuleId = ModuleIdMap.
size();
4453 ModuleIdMap[
Key] = ModuleId;
4463 Vals.
assign(Hash.begin(), Hash.end());
4475template <
typename Fn>
4479 if (!FS->type_tests().empty())
4484 auto WriteVFuncIdVec = [&](
uint64_t Ty,
4489 for (
auto &VF : VFs) {
4490 Record.push_back(VF.GUID);
4491 Record.push_back(VF.Offset);
4497 FS->type_test_assume_vcalls());
4499 FS->type_checked_load_vcalls());
4501 auto WriteConstVCallVec = [&](
uint64_t Ty,
4503 for (
auto &VC : VCs) {
4505 Record.push_back(VC.VFunc.GUID);
4506 Record.push_back(VC.VFunc.Offset);
4513 FS->type_test_assume_const_vcalls());
4515 FS->type_checked_load_const_vcalls());
4525 if (!FS->paramAccesses().empty()) {
4527 for (
auto &Arg : FS->paramAccesses()) {
4528 size_t UndoSize =
Record.size();
4529 Record.push_back(Arg.ParamNo);
4530 WriteRange(Arg.Use);
4531 Record.push_back(Arg.Calls.size());
4532 for (
auto &
Call : Arg.Calls) {
4534 std::optional<unsigned> ValueID = GetValueID(
Call.Callee);
4541 Record.push_back(*ValueID);
4542 WriteRange(
Call.Offsets);
4553 std::set<GlobalValue::GUID> &ReferencedTypeIds) {
4554 if (!FS->type_tests().empty())
4555 for (
auto &TT : FS->type_tests())
4556 ReferencedTypeIds.insert(TT);
4558 auto GetReferencedTypesFromVFuncIdVec =
4560 for (
auto &VF : VFs)
4561 ReferencedTypeIds.insert(VF.GUID);
4564 GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
4565 GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
4567 auto GetReferencedTypesFromConstVCallVec =
4569 for (
auto &VC : VCs)
4570 ReferencedTypeIds.insert(VC.VFunc.GUID);
4573 GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
4574 GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
4610 NameVals.
push_back(Summary.TTRes.TheKind);
4611 NameVals.
push_back(Summary.TTRes.SizeM1BitWidth);
4612 NameVals.
push_back(Summary.TTRes.AlignLog2);
4613 NameVals.
push_back(Summary.TTRes.SizeM1);
4614 NameVals.
push_back(Summary.TTRes.BitMask);
4615 NameVals.
push_back(Summary.TTRes.InlineBits);
4617 for (
auto &W : Summary.WPDRes)
4629 for (
auto &
P : Summary) {
4631 NameVals.
push_back(
VE.getValueID(
P.VTableVI.getValue()));
4645 static_assert(std::is_same_v<LinearFrameId, unsigned>);
4646 for (
auto &AI : FS->allocs()) {
4647 for (
auto &MIB : AI.MIBs) {
4649 StackIdIndices.
reserve(MIB.StackIdIndices.size());
4650 for (
auto Id : MIB.StackIdIndices)
4651 StackIdIndices.
push_back(GetStackIndex(Id));
4653 CallStacks.insert({CallStacks.size(), StackIdIndices});
4666 assert(!CallStacks.empty());
4672 Builder.
build(std::move(CallStacks),
nullptr,
4676 return Builder.takeCallStackPos();
4681 unsigned AllocAbbrev,
unsigned ContextIdAbbvId,
bool PerModule,
4682 std::function<
unsigned(
const ValueInfo &VI)> GetValueID,
4683 std::function<
unsigned(
unsigned)> GetStackIndex,
4684 bool WriteContextSizeInfoIndex,
4689 for (
auto &CI : FS->callsites()) {
4693 assert(!PerModule || (CI.Clones.size() == 1 && CI.Clones[0] == 0));
4694 Record.push_back(GetValueID(CI.Callee));
4696 Record.push_back(CI.StackIdIndices.size());
4697 Record.push_back(CI.Clones.size());
4699 for (
auto Id : CI.StackIdIndices)
4700 Record.push_back(GetStackIndex(Id));
4708 for (
auto &AI : FS->allocs()) {
4712 assert(!PerModule || (AI.Versions.size() == 1 && AI.Versions[0] == 0));
4713 Record.push_back(AI.MIBs.size());
4715 Record.push_back(AI.Versions.size());
4716 for (
auto &MIB : AI.MIBs) {
4723 assert(CallStackCount <= CallStackPos.
size());
4724 Record.push_back(CallStackPos[CallStackCount++]);
4729 assert(AI.ContextSizeInfos.empty() ||
4730 AI.ContextSizeInfos.size() == AI.MIBs.size());
4732 if (WriteContextSizeInfoIndex && !AI.ContextSizeInfos.empty()) {
4740 ContextIds.
reserve(AI.ContextSizeInfos.size() * 2);
4741 for (
auto &Infos : AI.ContextSizeInfos) {
4742 Record.push_back(Infos.size());
4743 for (
auto [FullStackId, TotalSize] : Infos) {
4750 Record.push_back(TotalSize);
4768void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
4769 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
4770 unsigned ValueID,
unsigned FSCallsProfileAbbrev,
unsigned CallsiteAbbrev,
4771 unsigned AllocAbbrev,
unsigned ContextIdAbbvId,
const Function &
F,
4772 DenseMap<CallStackId, LinearCallStackId> &CallStackPos,
4779 Stream, FS, [&](
const ValueInfo &VI) -> std::optional<unsigned> {
4783 auto SpecialRefCnts =
FS->specialRefCounts();
4788 NameVals.
push_back(SpecialRefCnts.first);
4789 NameVals.
push_back(SpecialRefCnts.second);
4791 for (
auto &RI :
FS->refs())
4794 for (
auto &ECI :
FS->calls()) {
4795 NameVals.
push_back(getValueId(ECI.first));
4804 Stream, FS, CallsiteAbbrev, AllocAbbrev, ContextIdAbbvId,
4806 [&](
const ValueInfo &VI) {
return getValueId(VI); },
4807 [&](
unsigned I) {
return I; },
4808 true, CallStackPos, CallStackCount);
4813void ModuleBitcodeWriterBase::writeModuleLevelReferences(
4814 const GlobalVariable &
V, SmallVector<uint64_t, 64> &NameVals,
4815 unsigned FSModRefsAbbrev,
unsigned FSModVTableRefsAbbrev) {
4820 auto VI =
Index->getValueInfo(GUID);
4821 if (!VI ||
VI.getSummaryList().empty()) {
4827 auto *
Summary =
VI.getSummaryList()[0].get();
4833 auto VTableFuncs =
VS->vTableFuncs();
4834 if (!VTableFuncs.empty())
4837 unsigned SizeBeforeRefs = NameVals.
size();
4838 for (
auto &RI :
VS->refs())
4844 if (VTableFuncs.empty())
4849 for (
auto &
P : VTableFuncs) {
4855 FSModVTableRefsAbbrev);
4862void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
4865 bool IsThinLTO =
true;
4868 IsThinLTO = MD->getZExtValue();
4880 if (
Index->enableSplitLTOUnit())
4882 if (
Index->hasUnifiedLTO())
4892 auto Abbv = std::make_shared<BitCodeAbbrev>();
4898 unsigned ValueGuidAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4900 for (
const auto &GVI : valueIds()) {
4902 ArrayRef<uint32_t>{GVI.second,
4903 static_cast<uint32_t
>(GVI.first >> 32),
4904 static_cast<uint32_t
>(GVI.first)},
4908 if (!
Index->stackIds().empty()) {
4909 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4916 unsigned StackIdAbbvId = Stream.
EmitAbbrev(std::move(StackIdAbbv));
4917 SmallVector<uint32_t> Vals;
4919 for (
auto Id :
Index->stackIds()) {
4920 Vals.
push_back(
static_cast<uint32_t
>(Id >> 32));
4921 Vals.
push_back(
static_cast<uint32_t
>(Id));
4926 unsigned ContextIdAbbvId = 0;
4929 auto ContextIdAbbv = std::make_shared<BitCodeAbbrev>();
4941 ContextIdAbbvId = Stream.
EmitAbbrev(std::move(ContextIdAbbv));
4945 Abbv = std::make_shared<BitCodeAbbrev>();
4957 unsigned FSCallsProfileAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4960 Abbv = std::make_shared<BitCodeAbbrev>();
4966 unsigned FSModRefsAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4969 Abbv = std::make_shared<BitCodeAbbrev>();
4977 unsigned FSModVTableRefsAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4980 Abbv = std::make_shared<BitCodeAbbrev>();
4985 unsigned FSAliasAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4988 Abbv = std::make_shared<BitCodeAbbrev>();
4995 unsigned TypeIdCompatibleVtableAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4997 Abbv = std::make_shared<BitCodeAbbrev>();
5003 unsigned CallsiteAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5005 Abbv = std::make_shared<BitCodeAbbrev>();
5012 unsigned AllocAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5014 Abbv = std::make_shared<BitCodeAbbrev>();
5019 unsigned RadixAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5026 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks;
5037 ValueInfo
VI =
Index->getValueInfo(GUID);
5038 if (!VI ||
VI.getSummaryList().empty()) {
5041 if (!
F.isDeclaration())
5043 " to have an associated value info.");
5046 auto *
Summary =
VI.getSummaryList()[0].get();
5049 FS, [](
unsigned I) {
return I; }, CallStacks);
5053 DenseMap<CallStackId, LinearCallStackId> CallStackPos;
5054 if (!CallStacks.
empty()) {
5062 SmallVector<uint64_t, 64> NameVals;
5073 ValueInfo
VI =
Index->getValueInfo(GUID);
5074 if (!VI ||
VI.getSummaryList().empty()) {
5080 auto *
Summary =
VI.getSummaryList()[0].get();
5081 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.
getValueID(&
F),
5082 FSCallsProfileAbbrev, CallsiteAbbrev,
5083 AllocAbbrev, ContextIdAbbvId,
F,
5084 CallStackPos, CallStackCount);
5089 for (
const GlobalVariable &
G :
M.globals())
5090 writeModuleLevelReferences(
G, NameVals, FSModRefsAbbrev,
5091 FSModVTableRefsAbbrev);
5093 for (
const GlobalAlias &
A :
M.aliases()) {
5094 auto *Aliasee =
A.getAliaseeObject();
5110 for (
auto &S :
Index->typeIdCompatibleVtableMap()) {
5114 TypeIdCompatibleVtableAbbrev);
5118 if (
Index->getBlockCount())
5120 ArrayRef<uint64_t>{
Index->getBlockCount()});
5125void ModuleBitcodeWriterBase::writeGUIDList() {
5127 for (
const GlobalValue &GV :
M.global_values()) {
5128 auto MaybeGUID = GV.getGUIDIfAssigned();
5129 if (!MaybeGUID || *MaybeGUID == 0)
5132 if (ValueID >= GUIDs.
size())
5133 GUIDs.
resize(ValueID + 1);
5134 GUIDs[ValueID] = *MaybeGUID;
5137 auto Abbv = std::make_shared<BitCodeAbbrev>();
5141 unsigned GUIDListAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5143 SmallVector<uint32_t> RecordVals;
5145 for (
auto GUID : GUIDs) {
5146 RecordVals.
push_back(
static_cast<uint32_t
>(GUID >> 32));
5147 RecordVals.
push_back(
static_cast<uint32_t
>(GUID));
5154void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
5163 auto Abbv = std::make_shared<BitCodeAbbrev>();
5169 unsigned ValueGuidAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5171 for (
const auto &GVI : valueIds()) {
5173 ArrayRef<uint32_t>{GVI.second,
5174 static_cast<uint32_t
>(GVI.first >> 32),
5175 static_cast<uint32_t
>(GVI.first)},
5181 if (!StackIds.empty()) {
5182 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
5189 unsigned StackIdAbbvId = Stream.
EmitAbbrev(std::move(StackIdAbbv));
5190 SmallVector<uint32_t> Vals;
5191 Vals.
reserve(StackIds.size() * 2);
5192 for (
auto Id : StackIds) {
5193 Vals.
push_back(
static_cast<uint32_t
>(Id >> 32));
5194 Vals.
push_back(
static_cast<uint32_t
>(Id));
5200 Abbv = std::make_shared<BitCodeAbbrev>();
5214 unsigned FSCallsProfileAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5217 Abbv = std::make_shared<BitCodeAbbrev>();
5224 unsigned FSModRefsAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5227 Abbv = std::make_shared<BitCodeAbbrev>();
5233 unsigned FSAliasAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5235 Abbv = std::make_shared<BitCodeAbbrev>();
5243 unsigned CallsiteAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5245 Abbv = std::make_shared<BitCodeAbbrev>();
5256 unsigned AllocAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5258 auto shouldImportValueAsDecl = [&](GlobalValueSummary *GVS) ->
bool {
5259 if (DecSummaries ==
nullptr)
5261 return DecSummaries->
count(GVS);
5269 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
5271 SmallVector<uint64_t, 64> NameVals;
5275 std::set<GlobalValue::GUID> ReferencedTypeIds;
5279 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
5289 NameVals.
push_back(S.getOriginalName());
5294 DenseMap<CallStackId, LinearCallStackId> CallStackPos;
5296 Abbv = std::make_shared<BitCodeAbbrev>();
5301 unsigned RadixAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5308 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks;
5309 forEachSummary([&](GVInfo
I,
bool IsAliasee) {
5315 GlobalValueSummary *S =
I.second;
5328 return StackIdIndicesToIndex[
I];
5334 if (!CallStacks.
empty()) {
5344 DenseSet<GlobalValue::GUID> DefOrUseGUIDs;
5345 forEachSummary([&](GVInfo
I,
bool IsAliasee) {
5346 GlobalValueSummary *S =
I.second;
5348 DefOrUseGUIDs.
insert(
I.first);
5349 for (
const ValueInfo &VI : S->
refs())
5350 DefOrUseGUIDs.
insert(
VI.getGUID());
5352 auto ValueId = getValueId(
I.first);
5354 SummaryToValueIdMap[S] = *ValueId;
5372 NameVals.
push_back(ModuleIdMap[
VS->modulePath()]);
5376 for (
auto &RI :
VS->refs()) {
5377 auto RefValueId = getValueId(RI.getGUID());
5387 MaybeEmitOriginalName(*S);
5391 auto GetValueId = [&](
const ValueInfo &
VI) -> std::optional<unsigned> {
5393 return std::nullopt;
5394 return getValueId(
VI.getGUID());
5403 NameVals.
push_back(ModuleIdMap[
FS->modulePath()]);
5416 unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;
5417 for (
auto &RI :
FS->refs()) {
5418 auto RefValueId = getValueId(RI.getGUID());
5422 if (RI.isReadOnly())
5424 else if (RI.isWriteOnly())
5428 NameVals[6] =
Count;
5429 NameVals[7] = RORefCnt;
5430 NameVals[8] = WORefCnt;
5432 for (
auto &EI :
FS->calls()) {
5435 std::optional<unsigned> CallValueId = GetValueId(EI.first);
5444 FSCallsProfileAbbrev);
5448 Stream, FS, CallsiteAbbrev, AllocAbbrev, 0,
5451 [&](
const ValueInfo &VI) ->
unsigned {
5452 std::optional<unsigned> ValueID = GetValueId(VI);
5467 return StackIdIndicesToIndex[
I];
5469 false, CallStackPos, CallStackCount);
5471 MaybeEmitOriginalName(*S);
5474 for (
auto *AS : Aliases) {
5475 auto AliasValueId = SummaryToValueIdMap[AS];
5484 auto AliaseeValueId =
5491 MaybeEmitOriginalName(*AS);
5499 auto EmitCfiFunctions = [&](
const CfiFunctionIndex &CfiIndex,
5501 if (CfiIndex.
empty())
5505 for (StringRef Name : Names)
5508 if (Functions.
empty())
5511 for (
const auto &Record : Functions) {
5526 for (
auto &
T : ReferencedTypeIds) {
5527 auto TidIter =
Index.typeIds().equal_range(
T);
5528 for (
const auto &[GUID, TypeIdPair] :
make_range(TidIter)) {
5536 if (
Index.getBlockCount())
5538 ArrayRef<uint64_t>{
Index.getBlockCount()});
5549 auto Abbv = std::make_shared<BitCodeAbbrev>();
5553 auto StringAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5555 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
5558 Abbv = std::make_shared<BitCodeAbbrev>();
5561 auto EpochAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5567void ModuleBitcodeWriter::writeModuleHash(StringRef View) {
5572 Hasher.
update(ArrayRef<uint8_t>(
5573 reinterpret_cast<const uint8_t *
>(
View.data()),
View.size()));
5574 std::array<uint8_t, 20> Hash = Hasher.
result();
5575 for (
int Pos = 0; Pos < 20; Pos += 4) {
5588void ModuleBitcodeWriter::write() {
5596 writeModuleVersion();
5605 writeAttributeGroupTable();
5608 writeAttributeTable();
5617 writeModuleConstants();
5620 writeModuleMetadataKinds();
5623 writeModuleMetadata();
5627 writeUseListBlock(
nullptr);
5629 writeOperandBundleTags();
5630 writeSyncScopeNames();
5633 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
5635 if (!
F.isDeclaration())
5636 writeFunction(
F, FunctionToBitcodeIndex);
5641 writePerModuleGlobalValueSummary();
5643 writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
5671 unsigned CPUType = ~0U;
5678 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
5679 DARWIN_CPU_TYPE_X86 = 7,
5680 DARWIN_CPU_TYPE_ARM = 12,
5681 DARWIN_CPU_TYPE_POWERPC = 18
5686 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
5688 CPUType = DARWIN_CPU_TYPE_X86;
5690 CPUType = DARWIN_CPU_TYPE_POWERPC;
5692 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
5694 CPUType = DARWIN_CPU_TYPE_ARM;
5698 "Expected header size to be reserved");
5703 unsigned Position = 0;
5711 while (Buffer.
size() & 15)
5718 Stream.
Emit((
unsigned)
'B', 8);
5719 Stream.
Emit((
unsigned)
'C', 8);
5720 Stream.
Emit(0x0, 4);
5721 Stream.
Emit(0xC, 4);
5722 Stream.
Emit(0xE, 4);
5723 Stream.
Emit(0xD, 4);
5741 auto Abbv = std::make_shared<BitCodeAbbrev>();
5744 auto AbbrevNo = Stream->
EmitAbbrev(std::move(Abbv));
5752 assert(!WroteStrtab && !WroteSymtab);
5758 if (M->getModuleInlineAsm().empty())
5762 const Triple TT(M->getTargetTriple());
5764 if (!
T || !
T->hasMCAsmParser())
5786 std::vector<char> Strtab;
5787 StrtabBuilder.finalizeInOrder();
5788 Strtab.resize(StrtabBuilder.getSize());
5789 StrtabBuilder.write((
uint8_t *)Strtab.data());
5792 {Strtab.data(), Strtab.size()});
5803 bool ShouldPreserveUseListOrder,
5812 assert(M.isMaterialized());
5813 Mods.push_back(
const_cast<Module *
>(&M));
5815 ModuleBitcodeWriter ModuleWriter(M, StrtabBuilder, *Stream,
5816 ShouldPreserveUseListOrder, Index,
5817 GenerateHash, ModHash);
5818 ModuleWriter.write();
5825 IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index, DecSummaries,
5826 ModuleToSummariesForIndex);
5827 IndexWriter.write();
5832 bool ShouldPreserveUseListOrder,
5836 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
5838 Writer.writeSymtab();
5839 Writer.writeStrtab();
5841 Triple TT(M.getTargetTriple());
5842 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) {
5853 Out.write(Buffer.
data(), Buffer.
size());
5861void IndexBitcodeWriter::write() {
5864 writeModuleVersion();
5870 writeCombinedGlobalValueSummary();
5887 Writer.
writeIndex(&Index, ModuleToSummariesForIndex, DecSummaries);
5890 Out.write((
char *)&Buffer.
front(), Buffer.
size());
5896class ThinLinkBitcodeWriter :
public ModuleBitcodeWriterBase {
5906 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
5908 ModHash(&ModHash) {}
5913 void writeSimplifiedModuleInfo();
5923void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
5935 auto Abbv = std::make_shared<BitCodeAbbrev>();
5938 Abbv->Add(AbbrevOpToUse);
5939 unsigned FilenameAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5941 for (
const auto P :
M.getSourceFileName())
6007void ThinLinkBitcodeWriter::write() {
6010 writeModuleVersion();
6012 writeSimplifiedModuleInfo();
6014 writePerModuleGlobalValueSummary();
6031 assert(M.isMaterialized());
6032 Mods.push_back(
const_cast<Module *
>(&M));
6034 ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
6036 ThinLinkWriter.write();
6053 Out.write((
char *)&Buffer.
front(), Buffer.
size());
6057 switch (
T.getObjectFormat()) {
6059 return "__LLVM,__bitcode";
6084 switch (
T.getObjectFormat()) {
6086 return "__LLVM,__cmdline";
6112 const std::vector<uint8_t> &CmdArgs) {
6117 Type *UsedElementType = Used ? Used->getValueType()->getArrayElementType()
6119 for (
auto *GV : UsedGlobals) {
6120 if (GV->getName() !=
"llvm.embedded.module" &&
6121 GV->getName() !=
"llvm.cmdline")
6126 Used->eraseFromParent();
6131 Triple T(M.getTargetTriple());
6160 M.getGlobalVariable(
"llvm.embedded.module",
true)) {
6161 assert(Old->hasZeroLiveUses() &&
6162 "llvm.embedded.module can only be used once in llvm.compiler.used");
6164 Old->eraseFromParent();
6166 GV->
setName(
"llvm.embedded.module");
6184 assert(Old->hasZeroLiveUses() &&
6185 "llvm.cmdline can only be used once in llvm.compiler.used");
6187 Old->eraseFromParent();
6193 if (UsedArray.
empty())
6201 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 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 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 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
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallString class.
This file defines the SmallVector class.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static const uint32_t IV[8]
Class for arbitrary precision integers.
unsigned getActiveWords() const
Compute the number of active words in the value of this APInt.
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
int64_t getSExtValue() const
Get sign extended value.
const GlobalValueSummary & getAliasee() const
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
bool isUsedWithInAlloca() const
Return true if this alloca is used as an inalloca argument to a call.
unsigned getAddressSpace() const
Return the address space for the allocation.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
bool empty() const
Check if the array is empty.
Class to represent array types.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
an instruction that atomically reads a memory location, combines it with another value,...
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
bool hasAttributes() const
Return true if attributes exists in this set.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
@ TombstoneKey
Use as Tombstone key for DenseMap of AttrKind.
@ None
No attributes have been set.
@ EmptyKey
Use as Empty key for DenseMap of AttrKind.
@ EndAttrKinds
Sentinel value useful for loops.
BitCodeAbbrevOp - This describes one or more operands in an abbreviation.
static bool isChar6(char C)
isChar6 - Return true if this character is legal in the Char6 encoding.
LLVM_ABI void writeThinLinkBitcode(const Module &M, const ModuleSummaryIndex &Index, const ModuleHash &ModHash)
Write the specified thin link bitcode file (i.e., the minimized bitcode file) to the buffer specified...
LLVM_ABI void writeIndex(const ModuleSummaryIndex *Index, const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex, const GVSummaryPtrSet *DecSummaries)
LLVM_ABI void copyStrtab(StringRef Strtab)
Copy the string table for another module into this bitcode file.
LLVM_ABI void writeStrtab()
Write the bitcode file's string table.
LLVM_ABI ~BitcodeWriter()
LLVM_ABI void writeSymtab()
Attempt to write a symbol table to the bitcode file.
LLVM_ABI void writeModule(const Module &M, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false, ModuleHash *ModHash=nullptr)
Write the specified module to the buffer specified at construction time.
LLVM_ABI BitcodeWriter(SmallVectorImpl< char > &Buffer)
Create a BitcodeWriter that writes to Buffer.
unsigned EmitAbbrev(std::shared_ptr< BitCodeAbbrev > Abbv)
Emits the abbreviation Abbv to the stream.
void markAndBlockFlushing()
For scenarios where the user wants to access a section of the stream to (for example) compute some ch...
StringRef getMarkedBufferAndResumeFlushing()
resumes flushing, but does not flush, and returns the section in the internal buffer starting from th...
void EmitRecord(unsigned Code, const Container &Vals, unsigned Abbrev=0)
EmitRecord - Emit the specified record to the stream, using an abbrev if we have one to compress the ...
void Emit(uint32_t Val, unsigned NumBits)
void EmitRecordWithBlob(unsigned Abbrev, const Container &Vals, StringRef Blob)
EmitRecordWithBlob - Emit the specified record to the stream, using an abbrev that includes a blob at...
unsigned EmitBlockInfoAbbrev(unsigned BlockID, std::shared_ptr< BitCodeAbbrev > Abbv)
EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified BlockID.
void EnterBlockInfoBlock()
EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
void BackpatchWord(uint64_t BitNo, unsigned Val)
void BackpatchWord64(uint64_t BitNo, uint64_t Val)
void EnterSubblock(unsigned BlockID, unsigned CodeLen)
uint64_t GetCurrentBitNo() const
Retrieve the current position in the stream, in bits.
void EmitRecordWithAbbrev(unsigned Abbrev, const Container &Vals)
EmitRecordWithAbbrev - Emit a record with the specified abbreviation.
static LLVM_ABI BlockAddress * lookup(const BasicBlock *BB)
Lookup an existing BlockAddress constant for the given BasicBlock.
OperandBundleUse getOperandBundleAt(unsigned Index) const
Return the operand bundle at a specific index.
unsigned getNumOperandBundles() const
Return the number of operand bundles associated with this User.
CallingConv::ID getCallingConv() const
Value * getCalledOperand() const
Value * getArgOperand(unsigned i) const
FunctionType * getFunctionType() const
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
bool hasOperandBundles() const
Return true if this User has any operand bundles.
BasicBlock * getIndirectDest(unsigned i) const
BasicBlock * getDefaultDest() const
unsigned getNumIndirectDests() const
Return the number of callbr indirect dest labels.
bool isNoTailCall() const
bool isMustTailCall() const
auto getNamesForGUID(GlobalValue::GUID GUID) const
get the name(s) associated with a given ThinLTO GUID.
@ Largest
The linker will choose the largest COMDAT.
@ SameSize
The data referenced by the COMDAT must be the same size.
@ Any
The linker may choose any COMDAT.
@ NoDeduplicate
No deduplication is performed.
@ ExactMatch
The data referenced by the COMDAT must be the same.
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
This class represents a range of values.
const APInt & getLower() const
Return the lower value for this range.
const APInt & getUpper() const
Return the upper value for this range.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
This is an important base class in LLVM.
DebugLoc getDebugLoc() const
LLVM_ABI DIAssignID * getAssignID() const
DIExpression * getExpression() const
DILocalVariable * getVariable() const
bool isDbgDeclareValue() const
Metadata * getRawLocation() const
Returns the metadata operand for the first location description.
bool isDbgDeclare() const
Metadata * getRawAddress() const
DIExpression * getAddressExpression() const
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Lightweight error class with error context and mandatory checking.
Function summary information to aid decisions and implementation of importing.
LLVM_ABI void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
Appends all metadata attached to this value to MDs, sorting by KindID.
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
GVFlags flags() const
Get the flags for this GlobalValue (see struct GVFlags).
StringRef modulePath() const
Get the path to the module containing this function.
ArrayRef< ValueInfo > refs() const
Return the list of values referenced by this global value definition.
VisibilityTypes getVisibility() const
static bool isLocalLinkage(LinkageTypes Linkage)
LinkageTypes getLinkage() const
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
ThreadLocalMode getThreadLocalMode() const
@ DLLExportStorageClass
Function to be accessible from DLL.
@ DLLImportStorageClass
Function to be imported from DLL.
@ DefaultVisibility
The GV is visible.
@ HiddenVisibility
The GV is hidden.
@ ProtectedVisibility
The GV is protected.
UnnamedAddr getUnnamedAddr() const
LinkageTypes
An enumeration for the kinds of linkage for global values.
@ PrivateLinkage
Like Internal, but omit from symbol table.
@ CommonLinkage
Tentative definitions.
@ InternalLinkage
Rename collisions when linking (static functions).
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
@ WeakODRLinkage
Same, but only replaced by something equivalent.
@ ExternalLinkage
Externally visible function.
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
@ AppendingLinkage
Special purpose, only applies to global arrays.
@ AvailableExternallyLinkage
Available for inspection, not emission.
@ ExternalWeakLinkage
ExternalWeak linkage description.
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
DLLStorageClassTypes getDLLStorageClass() const
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
idx_iterator idx_end() const
idx_iterator idx_begin() const
bool isCleanup() const
Return 'true' if this landingpad instruction is a cleanup.
unsigned getNumClauses() const
Get the number of clauses for this landing pad.
bool isCatch(unsigned Idx) const
Return 'true' if the clause and index Idx is a catch clause.
Constant * getClause(unsigned Idx) const
Get the value of the clause at index Idx.
This class implements a map that also provides access to all stored values in a deterministic order.
size_t getBufferSize() const
const char * getBufferStart() const
const char * getBufferEnd() const
Class to hold module path string table and global value map, and encapsulate methods for operating on...
static constexpr uint64_t BitcodeSummaryVersion
A Module instance is used to store all the information related to an LLVM module.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Digest more data.
LLVM_ABI std::array< uint8_t, 20 > result()
Return the current raw 160-bits SHA1 for the digested data since the last call to init().
size_type size() const
Determine the number of elements in the SetVector.
bool empty() const
Determine if the SetVector is empty or not.
bool insert(const value_type &X)
Insert a new element into the SetVector.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void append(StringRef RHS)
Append from a StringRef.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
const ValueTy & getValue() const
Represent a constant reference to a string, i.e.
constexpr bool empty() const
Check if the string is empty.
constexpr size_t size() const
Get the string size.
Utility for building string tables with deduplicated suffixes.
LLVM_ABI size_t add(CachedHashStringRef S, uint8_t Priority=0)
Add a string to the builder.
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
The instances of the Type class are immutable: once they are created, they are never changed.
bool isX86_FP80Ty() const
Return true if this is x86 long double.
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
bool isFP128Ty() const
Return true if this is 'fp128'.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
std::vector< std::pair< const Value *, unsigned > > ValueList
unsigned getTypeID(Type *T) const
unsigned getMetadataID(const Metadata *MD) const
UseListOrderStack UseListOrders
ArrayRef< const Metadata * > getNonMDStrings() const
Get the non-MDString metadata for this block.
unsigned getInstructionID(const Instruction *I) const
unsigned getAttributeListID(AttributeList PAL) const
void incorporateFunction(const Function &F)
incorporateFunction/purgeFunction - If you'd like to deal with a function, use these two methods to g...
void getFunctionConstantRange(unsigned &Start, unsigned &End) const
getFunctionConstantRange - Return the range of values that corresponds to function-local constants.
unsigned getAttributeGroupID(IndexAndAttrSet Group) const
bool hasMDs() const
Check whether the current block has any metadata to emit.
unsigned getComdatID(const Comdat *C) const
uint64_t computeBitsRequiredForTypeIndices() const
unsigned getValueID(const Value *V) const
unsigned getMetadataOrNullID(const Metadata *MD) const
const std::vector< IndexAndAttrSet > & getAttributeGroups() const
const ValueList & getValues() const
unsigned getGlobalBasicBlockID(const BasicBlock *BB) const
getGlobalBasicBlockID - This returns the function-specific ID for the specified basic block.
void setInstructionID(const Instruction *I)
const std::vector< const BasicBlock * > & getBasicBlocks() const
const std::vector< AttributeList > & getAttributeLists() const
bool shouldPreserveUseListOrder() const
const ComdatSetType & getComdats() const
std::vector< Type * > TypeList
ArrayRef< const Metadata * > getMDStrings() const
Get the MDString metadata for this block.
std::pair< unsigned, AttributeSet > IndexAndAttrSet
Attribute groups as encoded in bitcode are almost AttributeSets, but they include the AttributeList i...
const TypeList & getTypes() const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
LLVMContext & getContext() const
All values hold a context through their type.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
std::pair< iterator, bool > insert(const ValueT &V)
void build(llvm::MapVector< CallStackId, llvm::SmallVector< FrameIdTy > > &&MemProfCallStackData, const llvm::DenseMap< FrameIdTy, LinearFrameId > *MemProfFrameIndexes, llvm::DenseMap< FrameIdTy, FrameStat > &FrameHistogram)
This class implements an extremely fast bulk output stream that can only output to a stream.
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
Predicate getPredicate(unsigned Condition, unsigned Hint)
Return predicate consisting of specified condition and hint bits.
@ CE
Windows NT (Windows on ARM)
@ TYPE_CODE_OPAQUE_POINTER
@ METADATA_TEMPLATE_VALUE
@ METADATA_LEXICAL_BLOCK_FILE
@ METADATA_SUBROUTINE_TYPE
@ METADATA_GLOBAL_DECL_ATTACHMENT
@ METADATA_IMPORTED_ENTITY
@ METADATA_GENERIC_SUBRANGE
@ METADATA_COMPOSITE_TYPE
@ METADATA_FIXED_POINT_TYPE
@ METADATA_GLOBAL_VAR_EXPR
GlobalValueSummarySymtabCodes
@ FS_CONTEXT_RADIX_TREE_ARRAY
@ FS_COMBINED_GLOBALVAR_INIT_REFS
@ FS_TYPE_CHECKED_LOAD_VCALLS
@ FS_COMBINED_ORIGINAL_NAME
@ FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_CONST_VCALL
@ FS_PERMODULE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_VCALLS
@ FS_COMBINED_ALLOC_INFO_NO_CONTEXT
@ FS_COMBINED_CALLSITE_INFO
@ FS_PERMODULE_CALLSITE_INFO
@ FS_PERMODULE_ALLOC_INFO
@ FS_TYPE_CHECKED_LOAD_CONST_VCALL
@ IDENTIFICATION_CODE_EPOCH
@ IDENTIFICATION_CODE_STRING
@ CST_CODE_DSO_LOCAL_EQUIVALENT
@ CST_CODE_CE_GEP_WITH_INRANGE
@ COMDAT_SELECTION_KIND_LARGEST
@ COMDAT_SELECTION_KIND_ANY
@ COMDAT_SELECTION_KIND_SAME_SIZE
@ COMDAT_SELECTION_KIND_EXACT_MATCH
@ COMDAT_SELECTION_KIND_NO_DUPLICATES
@ ATTR_KIND_STACK_PROTECT
@ ATTR_KIND_STACK_PROTECT_STRONG
@ ATTR_KIND_SANITIZE_MEMORY
@ ATTR_KIND_OPTIMIZE_FOR_SIZE
@ ATTR_KIND_FNRETTHUNK_EXTERN
@ ATTR_KIND_NO_DIVERGENCE_SOURCE
@ ATTR_KIND_SANITIZE_ADDRESS
@ ATTR_KIND_NO_IMPLICIT_FLOAT
@ ATTR_KIND_DEAD_ON_UNWIND
@ ATTR_KIND_STACK_ALIGNMENT
@ ATTR_KIND_STACK_PROTECT_REQ
@ ATTR_KIND_NULL_POINTER_IS_VALID
@ ATTR_KIND_SANITIZE_HWADDRESS
@ ATTR_KIND_RETURNS_TWICE
@ ATTR_KIND_SHADOWCALLSTACK
@ ATTR_KIND_OPT_FOR_FUZZING
@ ATTR_KIND_DENORMAL_FPENV
@ ATTR_KIND_SANITIZE_NUMERICAL_STABILITY
@ ATTR_KIND_SANITIZE_CONCURRENCY
@ ATTR_KIND_ALLOCATED_POINTER
@ ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION
@ ATTR_KIND_CORO_ELIDE_SAFE
@ ATTR_KIND_NON_LAZY_BIND
@ ATTR_KIND_DEREFERENCEABLE
@ ATTR_KIND_LIKELY_MODULE_LOCAL
@ ATTR_KIND_OPTIMIZE_NONE
@ ATTR_KIND_HYBRID_PATCHABLE
@ ATTR_KIND_DEREFERENCEABLE_OR_NULL
@ ATTR_KIND_SANITIZE_REALTIME
@ ATTR_KIND_SPECULATIVE_LOAD_HARDENING
@ ATTR_KIND_ALWAYS_INLINE
@ ATTR_KIND_SANITIZE_TYPE
@ ATTR_KIND_PRESPLIT_COROUTINE
@ ATTR_KIND_SANITIZE_ALLOC_TOKEN
@ ATTR_KIND_NO_SANITIZE_COVERAGE
@ ATTR_KIND_NO_CREATE_UNDEF_OR_POISON
@ ATTR_KIND_DEAD_ON_RETURN
@ ATTR_KIND_SANITIZE_REALTIME_BLOCKING
@ ATTR_KIND_NO_SANITIZE_BOUNDS
@ ATTR_KIND_SANITIZE_MEMTAG
@ ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE
@ ATTR_KIND_SANITIZE_THREAD
@ ATTR_KIND_OPTIMIZE_FOR_DEBUGGING
@ SYNC_SCOPE_NAMES_BLOCK_ID
@ PARAMATTR_GROUP_BLOCK_ID
@ IDENTIFICATION_BLOCK_ID
@ GLOBALVAL_SUMMARY_BLOCK_ID
@ FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID
@ OPERAND_BUNDLE_TAGS_BLOCK_ID
@ MODULE_CODE_SOURCE_FILENAME
@ MODULE_CODE_SECTIONNAME
@ MODULE_CODE_ASM_PROPERTY
@ FUNC_CODE_INST_CATCHRET
@ FUNC_CODE_INST_LANDINGPAD
@ FUNC_CODE_INST_EXTRACTVAL
@ FUNC_CODE_INST_CATCHPAD
@ FUNC_CODE_INST_CATCHSWITCH
@ FUNC_CODE_INST_CLEANUPRET
@ FUNC_CODE_DEBUG_RECORD_VALUE
@ FUNC_CODE_INST_LOADATOMIC
@ FUNC_CODE_DEBUG_RECORD_ASSIGN
@ FUNC_CODE_INST_STOREATOMIC
@ FUNC_CODE_INST_BITEXTRACT
@ FUNC_CODE_INST_ATOMICRMW
@ FUNC_CODE_DEBUG_RECORD_DECLARE_VALUE
@ FUNC_CODE_DEBUG_LOC_AGAIN
@ FUNC_CODE_INST_EXTRACTELT
@ FUNC_CODE_INST_INDIRECTBR
@ FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE
@ FUNC_CODE_INST_INSERTVAL
@ FUNC_CODE_DECLAREBLOCKS
@ FUNC_CODE_DEBUG_RECORD_LABEL
@ FUNC_CODE_INST_INSERTELT
@ FUNC_CODE_BLOCKADDR_USERS
@ FUNC_CODE_INST_CLEANUPPAD
@ FUNC_CODE_INST_SHUFFLEVEC
@ FUNC_CODE_INST_UNREACHABLE
@ FUNC_CODE_INST_BITINSERT
@ FUNC_CODE_DEBUG_RECORD_DECLARE
@ FUNC_CODE_OPERAND_BUNDLE
@ FIRST_APPLICATION_ABBREV
@ PARAMATTR_GRP_CODE_ENTRY
initializer< Ty > init(const Ty &Val)
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
LLVM_ABI Error build(ArrayRef< Module * > Mods, SmallVector< char, 0 > &Symtab, StringTableBuilder &StrtabBuilder, BumpPtrAllocator &Alloc)
Fills in Symtab and StrtabBuilder with a valid symbol and string table for Mods.
llvm::unique_function< void(llvm::Expected< T >)> Callback
A Callback<T> is a void function that accepts Expected<T>.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract_or_null(Y &&MD)
Extract a Value from Metadata, allowing null.
LLVM_ABI bool metadataIncludesAllContextSizeInfo()
Whether the alloc memeprof metadata will include context size info for all MIBs.
template LLVM_ABI llvm::DenseMap< LinearFrameId, FrameStat > computeFrameHistogram< LinearFrameId >(llvm::MapVector< CallStackId, llvm::SmallVector< LinearFrameId > > &MemProfCallStackData)
LLVM_ABI bool metadataMayIncludeContextSizeInfo()
Whether the alloc memprof metadata may include context size info for some MIBs (but possibly not all)...
NodeAddr< CodeNode * > Code
void write32le(void *P, uint32_t V)
uint32_t read32be(const void *P)
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
void stable_sort(R &&Range)
StringMapEntry< Value * > ValueName
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
unsigned encode(MaybeAlign A)
Returns a representation of the alignment that encodes undefined as 0.
LLVM_ABI void WriteBitcodeToFile(const Module &M, raw_ostream &Out, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false, ModuleHash *ModHash=nullptr)
Write the specified module to the specified raw output stream.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
LLVM_ABI void writeThinLinkBitcodeToFile(const Module &M, raw_ostream &Out, const ModuleSummaryIndex &Index, const ModuleHash &ModHash)
Write the specified thin link bitcode file (i.e., the minimized bitcode file) to the given raw output...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI void writeIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out, const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex=nullptr, const GVSummaryPtrSet *DecSummaries=nullptr)
Write the specified module summary index to the given raw output stream, where it will be written in ...
LLVM_ABI void embedBitcodeInModule(Module &M, MemoryBufferRef Buf, bool EmbedBitcode, bool EmbedCmdline, const std::vector< uint8_t > &CmdArgs)
If EmbedBitcode is set, save a copy of the llvm IR as data in the __LLVM,__bitcode section (....
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
const BitWriterOptions & getBitWriterOptions(const LLVMContext &C)
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.
constexpr bool valueOr(BoolOrDefault X, bool Default)
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