33#include "llvm/Config/llvm-config.h"
95 cl::desc(
"Number of metadatas above which we emit an index "
96 "to enable lazy-loading"));
99 cl::desc(
"The threshold (unit M) for flushing LLVM bitcode."));
119 cl::desc(
"Preserve use-list order when writing LLVM bitcode."));
134 VST_BBENTRY_6_ABBREV,
138 CONSTANTS_INTEGER_ABBREV,
139 CONSTANTS_BYTE_ABBREV,
140 CONSTANTS_CE_CAST_Abbrev,
141 CONSTANTS_NULL_Abbrev,
145 FUNCTION_INST_STORE_ABBREV,
146 FUNCTION_INST_UNOP_ABBREV,
147 FUNCTION_INST_UNOP_FLAGS_ABBREV,
148 FUNCTION_INST_BINOP_ABBREV,
149 FUNCTION_INST_BINOP_FLAGS_ABBREV,
150 FUNCTION_INST_CAST_ABBREV,
151 FUNCTION_INST_CAST_FLAGS_ABBREV,
152 FUNCTION_INST_RET_VOID_ABBREV,
153 FUNCTION_INST_RET_VAL_ABBREV,
154 FUNCTION_INST_BR_UNCOND_ABBREV,
155 FUNCTION_INST_BR_COND_ABBREV,
156 FUNCTION_INST_UNREACHABLE_ABBREV,
157 FUNCTION_INST_GEP_ABBREV,
158 FUNCTION_INST_CMP_ABBREV,
159 FUNCTION_INST_CMP_FLAGS_ABBREV,
160 FUNCTION_DEBUG_RECORD_VALUE_ABBREV,
161 FUNCTION_DEBUG_LOC_ABBREV,
162 FUNCTION_DEBUG_LOC_LAYERS_ABBREV,
167class BitcodeWriterBase {
170 BitstreamWriter &Stream;
172 StringTableBuilder &StrtabBuilder;
177 BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
178 : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
181 void writeModuleVersion();
184void BitcodeWriterBase::writeModuleVersion() {
191class ModuleBitcodeWriterBase :
public BitcodeWriterBase {
200 const ModuleSummaryIndex *Index;
205 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
208 unsigned GlobalValueId;
217 ModuleBitcodeWriterBase(
const Module &M, StringTableBuilder &StrtabBuilder,
218 BitstreamWriter &Stream,
219 bool ShouldPreserveUseListOrder,
220 const ModuleSummaryIndex *Index)
221 : BitcodeWriterBase(Stream, StrtabBuilder),
M(
M),
224 : ShouldPreserveUseListOrder),
235 for (
const auto &GUIDSummaryLists :
236 Index->sortedGlobalValueSummariesRange())
238 for (
auto &Summary : GUIDSummaryLists.second.getSummaryList())
244 for (auto &CallEdge : FS->calls())
245 if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())
246 assignValueId(CallEdge.first.getGUID());
252 for (auto &RefEdge : FS->refs())
253 if (!RefEdge.haveGVs() || !RefEdge.getValue())
254 assignValueId(RefEdge.getGUID());
259 void writePerModuleGlobalValueSummary();
260 void writeGUIDList();
263 void writePerModuleFunctionSummaryRecord(
264 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
265 unsigned ValueID,
unsigned FSCallsProfileAbbrev,
unsigned CallsiteAbbrev,
266 unsigned AllocAbbrev,
unsigned ContextIdAbbvId,
const Function &
F,
267 DenseMap<CallStackId, LinearCallStackId> &CallStackPos,
269 void writeModuleLevelReferences(
const GlobalVariable &V,
270 SmallVector<uint64_t, 64> &NameVals,
271 unsigned FSModRefsAbbrev,
272 unsigned FSModVTableRefsAbbrev);
275 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
279 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
282 assert(VMI != GUIDToValueIdMap.end() &&
283 "GUID does not have assigned value Id");
288 unsigned getValueId(ValueInfo VI) {
289 if (!
VI.haveGVs() || !
VI.getValue())
290 return getValueId(
VI.getGUID());
294 std::map<GlobalValue::GUID, unsigned> &valueIds() {
return GUIDToValueIdMap; }
298class ModuleBitcodeWriter :
public ModuleBitcodeWriterBase {
314 unsigned DILocationLayersAbbrev = 0;
319 ModuleBitcodeWriter(
const Module &M, StringTableBuilder &StrtabBuilder,
320 BitstreamWriter &Stream,
bool ShouldPreserveUseListOrder,
321 const ModuleSummaryIndex *Index,
bool GenerateHash,
323 : ModuleBitcodeWriterBase(
M, StrtabBuilder, Stream,
324 ShouldPreserveUseListOrder,
Index),
325 GenerateHash(GenerateHash), ModHash(ModHash),
326 BitcodeStartBit(Stream.GetCurrentBitNo()) {}
332 uint64_t bitcodeStartBit() {
return BitcodeStartBit; }
334 size_t addToStrtab(StringRef Str);
336 void writeAttributeGroupTable();
337 void writeAttributeTable();
338 void writeTypeTable();
340 void writeValueSymbolTableForwardDecl();
341 void writeModuleInfo();
342 void writeValueAsMetadata(
const ValueAsMetadata *MD,
343 SmallVectorImpl<uint64_t> &Record);
344 void writeMDTuple(
const MDTuple *
N, SmallVectorImpl<uint64_t> &Record,
346 unsigned createDILocationAbbrev(
bool WithIRLayers);
347 void writeDILocation(
const DILocation *
N, SmallVectorImpl<uint64_t> &Record,
349 void writeDILayerLoc(
const DILayerLoc *
N, SmallVectorImpl<uint64_t> &Record,
352 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
353 unsigned createGenericDINodeAbbrev();
355 SmallVectorImpl<uint64_t> &Record,
unsigned &Abbrev);
356 void writeDISubrange(
const DISubrange *
N, SmallVectorImpl<uint64_t> &Record,
359 SmallVectorImpl<uint64_t> &Record,
362 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
366 SmallVectorImpl<uint64_t> &Record,
369 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
371 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
373 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
375 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
377 SmallVectorImpl<uint64_t> &Record,
379 void writeDIFile(
const DIFile *
N, SmallVectorImpl<uint64_t> &Record,
382 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
384 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
386 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
388 SmallVectorImpl<uint64_t> &Record,
391 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
394 void writeDIMacro(
const DIMacro *
N, SmallVectorImpl<uint64_t> &Record,
398 void writeDIArgList(
const DIArgList *
N, SmallVectorImpl<uint64_t> &Record);
399 void writeDIModule(
const DIModule *
N, SmallVectorImpl<uint64_t> &Record,
401 void writeDIAssignID(
const DIAssignID *
N, SmallVectorImpl<uint64_t> &Record,
404 SmallVectorImpl<uint64_t> &Record,
407 SmallVectorImpl<uint64_t> &Record,
410 SmallVectorImpl<uint64_t> &Record,
413 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
415 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
417 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
419 SmallVectorImpl<uint64_t> &Record,
422 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
423 void writeDIProperty(
const DIProperty *
N, SmallVectorImpl<uint64_t> &Record,
426 SmallVectorImpl<uint64_t> &Record,
428 unsigned createNamedMetadataAbbrev();
429 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
430 unsigned createMetadataStringsAbbrev();
432 SmallVectorImpl<uint64_t> &Record);
434 SmallVectorImpl<uint64_t> &Record,
435 std::vector<unsigned> *MDAbbrevs =
nullptr,
436 std::vector<uint64_t> *IndexPos =
nullptr);
437 void writeModuleMetadata();
438 void writeFunctionMetadata(
const Function &
F);
439 void writeFunctionMetadataAttachment(
const Function &
F);
440 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
441 const GlobalObject &GO);
442 void writeModuleMetadataKinds();
443 void writeOperandBundleTags();
444 void writeSyncScopeNames();
445 void writeConstants(
unsigned FirstVal,
unsigned LastVal,
bool isGlobal);
446 void writeModuleConstants();
447 bool pushValueAndType(
const Value *V,
unsigned InstID,
448 SmallVectorImpl<unsigned> &Vals);
449 bool pushValueOrMetadata(
const Value *V,
unsigned InstID,
450 SmallVectorImpl<unsigned> &Vals);
451 void writeOperandBundles(
const CallBase &CB,
unsigned InstID);
452 void pushValue(
const Value *V,
unsigned InstID,
453 SmallVectorImpl<unsigned> &Vals);
454 void pushValueSigned(
const Value *V,
unsigned InstID,
455 SmallVectorImpl<uint64_t> &Vals);
456 void writeInstruction(
const Instruction &
I,
unsigned InstID,
457 SmallVectorImpl<unsigned> &Vals);
458 void writeFunctionLevelValueSymbolTable(
const ValueSymbolTable &VST);
459 void writeGlobalValueSymbolTable(
460 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
461 void writeUseList(UseListOrder &&Order);
462 void writeUseListBlock(
const Function *
F);
465 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
466 void writeBlockInfo();
467 void writeModuleHash(StringRef View);
470 return unsigned(SSID);
473 unsigned getEncodedAlign(MaybeAlign Alignment) {
return encode(Alignment); }
477class IndexBitcodeWriter :
public BitcodeWriterBase {
479 const ModuleSummaryIndex &
Index;
492 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
496 std::vector<uint64_t> StackIds;
501 DenseMap<unsigned, unsigned> StackIdIndicesToIndex;
504 unsigned GlobalValueId = 0;
508 DenseMap<StringRef, uint64_t> ModuleIdMap;
518 BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
519 const ModuleSummaryIndex &Index,
522 : BitcodeWriterBase(Stream, StrtabBuilder),
Index(
Index),
523 DecSummaries(DecSummaries),
524 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
528 auto RecordStackIdReference = [&](
unsigned StackIdIndex) {
533 StackIdIndicesToIndex.
insert({StackIdIndex, StackIds.size()});
535 StackIds.push_back(
Index.getStackIdAtIndex(StackIdIndex));
542 forEachSummary([&](GVInfo
I,
bool IsAliasee) {
543 GUIDToValueIdMap[
I.first] = ++GlobalValueId;
555 for (
auto &CI :
FS->callsites()) {
566 if (CI.StackIdIndices.empty()) {
567 GUIDToValueIdMap[CI.Callee.getGUID()] = ++GlobalValueId;
570 for (
auto Idx : CI.StackIdIndices)
571 RecordStackIdReference(Idx);
574 for (
auto &AI :
FS->allocs())
575 for (
auto &MIB : AI.MIBs)
576 for (
auto Idx : MIB.StackIdIndices)
577 RecordStackIdReference(Idx);
583 using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
588 template<
typename Functor>
589 void forEachSummary(Functor Callback) {
590 if (ModuleToSummariesForIndex) {
591 for (
auto &M : *ModuleToSummariesForIndex)
592 for (
auto &[GUID, GVS] :
M.second) {
598 Callback({AS->getAliaseeGUID(), &AS->getAliasee()},
true);
602 for (
const auto &Summaries :
Index.sortedGlobalValueSummariesRange())
603 for (
auto &Summary : Summaries.second.getSummaryList())
612 template <
typename Functor>
void forEachModule(Functor Callback) {
613 if (ModuleToSummariesForIndex) {
614 for (
const auto &M : *ModuleToSummariesForIndex) {
615 const auto &MPI =
Index.modulePaths().find(
M.first);
616 if (MPI ==
Index.modulePaths().end()) {
620 assert(ModuleToSummariesForIndex->size() == 1);
630 std::vector<StringRef> ModulePaths;
631 for (
auto &[ModPath,
_] :
Index.modulePaths())
632 ModulePaths.push_back(ModPath);
634 for (
auto &ModPath : ModulePaths)
643 void writeModStrings();
644 void writeCombinedGlobalValueSummary();
647 auto VMI = GUIDToValueIdMap.find(ValGUID);
648 if (VMI == GUIDToValueIdMap.end())
653 std::map<GlobalValue::GUID, unsigned> &valueIds() {
return GUIDToValueIdMap; }
688 case Instruction::Add:
690 case Instruction::Sub:
692 case Instruction::Mul:
695 case Instruction::FDiv:
698 case Instruction::FRem:
710 unsigned Encoding = 0;
711 switch (
I.getOperation()) {
784 if (
I.isElementwise())
819 case Attribute::Alignment:
821 case Attribute::AllocAlign:
823 case Attribute::AllocSize:
825 case Attribute::AlwaysInline:
827 case Attribute::Builtin:
829 case Attribute::ByVal:
831 case Attribute::Convergent:
833 case Attribute::InAlloca:
835 case Attribute::Cold:
837 case Attribute::DisableSanitizerInstrumentation:
839 case Attribute::FnRetThunkExtern:
841 case Attribute::Flatten:
845 case Attribute::ElementType:
847 case Attribute::HybridPatchable:
849 case Attribute::InlineHint:
851 case Attribute::InReg:
853 case Attribute::JumpTable:
855 case Attribute::MinSize:
857 case Attribute::AllocatedPointer:
859 case Attribute::AllocKind:
861 case Attribute::Memory:
863 case Attribute::NoFPClass:
865 case Attribute::Naked:
867 case Attribute::Nest:
869 case Attribute::NoAlias:
871 case Attribute::NoBuiltin:
873 case Attribute::NoCallback:
875 case Attribute::NoDivergenceSource:
877 case Attribute::NoDuplicate:
879 case Attribute::NoFree:
881 case Attribute::NoFreeObj:
883 case Attribute::NoImplicitFloat:
885 case Attribute::NoInline:
887 case Attribute::NoRecurse:
889 case Attribute::NoMerge:
891 case Attribute::NonLazyBind:
893 case Attribute::NonNull:
895 case Attribute::Dereferenceable:
897 case Attribute::DereferenceableOrNull:
899 case Attribute::NoRedZone:
901 case Attribute::NoReturn:
903 case Attribute::NoSync:
905 case Attribute::NoCfCheck:
907 case Attribute::NoProfile:
909 case Attribute::SkipProfile:
911 case Attribute::NoUnwind:
913 case Attribute::NoSanitizeBounds:
915 case Attribute::NoSanitizeCoverage:
917 case Attribute::NullPointerIsValid:
919 case Attribute::OptimizeForDebugging:
921 case Attribute::OptForFuzzing:
923 case Attribute::OptimizeForSize:
925 case Attribute::OptimizeNone:
927 case Attribute::ReadNone:
929 case Attribute::ReadOnly:
931 case Attribute::Returned:
933 case Attribute::ReturnsTwice:
935 case Attribute::SExt:
937 case Attribute::Speculatable:
939 case Attribute::StackAlignment:
941 case Attribute::StackProtect:
943 case Attribute::StackProtectReq:
945 case Attribute::StackProtectStrong:
947 case Attribute::SafeStack:
949 case Attribute::ShadowCallStack:
951 case Attribute::StrictFP:
953 case Attribute::StructRet:
955 case Attribute::SanitizeAddress:
957 case Attribute::SanitizeAllocToken:
959 case Attribute::SanitizeHWAddress:
961 case Attribute::SanitizeThread:
963 case Attribute::SanitizeType:
965 case Attribute::SanitizeMemory:
967 case Attribute::SanitizeNumericalStability:
969 case Attribute::SanitizeRealtime:
971 case Attribute::SanitizeRealtimeBlocking:
973 case Attribute::SpeculativeLoadHardening:
975 case Attribute::SwiftError:
977 case Attribute::SwiftSelf:
979 case Attribute::SwiftAsync:
981 case Attribute::UWTable:
983 case Attribute::VScaleRange:
985 case Attribute::WillReturn:
987 case Attribute::WriteOnly:
989 case Attribute::ZExt:
991 case Attribute::ImmArg:
993 case Attribute::SanitizeMemTag:
995 case Attribute::Preallocated:
997 case Attribute::NoUndef:
999 case Attribute::ByRef:
1001 case Attribute::MustProgress:
1003 case Attribute::PresplitCoroutine:
1005 case Attribute::Writable:
1007 case Attribute::CoroDestroyOnlyWhenComplete:
1009 case Attribute::CoroElideSafe:
1011 case Attribute::DeadOnUnwind:
1013 case Attribute::Range:
1015 case Attribute::Initializes:
1017 case Attribute::NoExt:
1019 case Attribute::Captures:
1021 case Attribute::DeadOnReturn:
1023 case Attribute::NoCreateUndefOrPoison:
1025 case Attribute::DenormalFPEnv:
1027 case Attribute::NoOutline:
1029 case Attribute::NoIPA:
1044 if ((int64_t)V >= 0)
1055 unsigned NumWords =
A.getActiveWords();
1056 const uint64_t *RawData =
A.getRawData();
1057 for (
unsigned i = 0; i < NumWords; i++)
1077void ModuleBitcodeWriter::writeAttributeGroupTable() {
1078 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
1080 if (AttrGrps.empty())
return;
1084 SmallVector<uint64_t, 64>
Record;
1086 unsigned AttrListIndex = Pair.first;
1087 AttributeSet AS = Pair.second;
1089 Record.push_back(AttrListIndex);
1092 if (Attr.isEnumAttribute()) {
1095 }
else if (Attr.isIntAttribute()) {
1097 Attribute::AttrKind
Kind = Attr.getKindAsEnum();
1099 if (Kind == Attribute::Memory) {
1104 Record.push_back(Attr.getValueAsInt());
1106 }
else if (Attr.isStringAttribute()) {
1107 StringRef
Kind = Attr.getKindAsString();
1108 StringRef Val = Attr.getValueAsString();
1117 }
else if (Attr.isTypeAttribute()) {
1118 Type *Ty = Attr.getValueAsType();
1119 Record.push_back(Ty ? 6 : 5);
1123 }
else if (Attr.isConstantRangeAttribute()) {
1129 assert(Attr.isConstantRangeListAttribute());
1135 for (
auto &CR : Val)
1147void ModuleBitcodeWriter::writeAttributeTable() {
1149 if (
Attrs.empty())
return;
1153 SmallVector<uint64_t, 64>
Record;
1154 for (
const AttributeList &AL : Attrs) {
1155 for (
unsigned i :
AL.indexes()) {
1156 AttributeSet AS =
AL.getAttributes(i);
1169void ModuleBitcodeWriter::writeTypeTable() {
1173 SmallVector<uint64_t, 64> TypeVals;
1178 auto Abbv = std::make_shared<BitCodeAbbrev>();
1180 Abbv->Add(BitCodeAbbrevOp(0));
1181 unsigned OpaquePtrAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1184 Abbv = std::make_shared<BitCodeAbbrev>();
1189 unsigned FunctionAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1192 Abbv = std::make_shared<BitCodeAbbrev>();
1197 unsigned StructAnonAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1200 Abbv = std::make_shared<BitCodeAbbrev>();
1204 unsigned StructNameAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1207 Abbv = std::make_shared<BitCodeAbbrev>();
1212 unsigned StructNamedAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1215 Abbv = std::make_shared<BitCodeAbbrev>();
1219 unsigned ArrayAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1227 for (
Type *
T : TypeList) {
1228 int AbbrevToUse = 0;
1231 switch (
T->getTypeID()) {
1241 case Type::MetadataTyID:
1246 case Type::ByteTyID:
1251 case Type::IntegerTyID:
1256 case Type::PointerTyID: {
1263 AbbrevToUse = OpaquePtrAbbrev;
1266 case Type::FunctionTyID: {
1272 for (
unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
1274 AbbrevToUse = FunctionAbbrev;
1277 case Type::StructTyID: {
1282 for (
Type *ET :
ST->elements())
1285 if (
ST->isLiteral()) {
1287 AbbrevToUse = StructAnonAbbrev;
1289 if (
ST->isOpaque()) {
1293 AbbrevToUse = StructNamedAbbrev;
1297 if (!
ST->getName().empty())
1303 case Type::ArrayTyID: {
1307 TypeVals.
push_back(AT->getNumElements());
1309 AbbrevToUse = ArrayAbbrev;
1312 case Type::FixedVectorTyID:
1313 case Type::ScalableVectorTyID: {
1318 TypeVals.
push_back(VT->getElementCount().getKnownMinValue());
1324 case Type::TargetExtTyID: {
1330 for (
Type *InnerTy :
TET->type_params())
1335 case Type::TypedPointerTyID:
1340 Stream.
EmitRecord(Code, TypeVals, AbbrevToUse);
1381 RawFlags |= Flags.ReadNone;
1382 RawFlags |= (Flags.ReadOnly << 1);
1383 RawFlags |= (Flags.NoRecurse << 2);
1384 RawFlags |= (Flags.ReturnDoesNotAlias << 3);
1385 RawFlags |= (Flags.NoInline << 4);
1386 RawFlags |= (Flags.AlwaysInline << 5);
1387 RawFlags |= (Flags.NoUnwind << 6);
1388 RawFlags |= (Flags.MayThrow << 7);
1389 RawFlags |= (Flags.HasUnknownCall << 8);
1390 RawFlags |= (Flags.MustBeUnreachable << 9);
1397 bool ImportAsDecl =
false) {
1400 RawFlags |= Flags.NotEligibleToImport;
1401 RawFlags |= (Flags.Live << 1);
1402 RawFlags |= (Flags.DSOLocal << 2);
1403 RawFlags |= (Flags.CanAutoHide << 3);
1408 RawFlags = (RawFlags << 4) | Flags.Linkage;
1410 RawFlags |= (Flags.Visibility << 8);
1412 unsigned ImportType = Flags.ImportType | ImportAsDecl;
1413 RawFlags |= (ImportType << 10);
1415 RawFlags |= (Flags.NoRenameOnPromotion << 11);
1421 uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) |
1422 (Flags.Constant << 2) | Flags.VCallVisibility << 3;
1465 switch (
C.getSelectionKind()) {
1489size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1492 return StrtabBuilder.
add(Str);
1495void ModuleBitcodeWriter::writeComdats() {
1510void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
1515 auto Abbv = std::make_shared<BitCodeAbbrev>();
1521 unsigned VSTOffsetAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1537 bool isChar6 =
true;
1538 for (
char C : Str) {
1541 if ((
unsigned char)
C & 128)
1550static_assert(
sizeof(GlobalValue::SanitizerMetadata) <=
sizeof(unsigned),
1551 "Sanitizer Metadata is too large for naive serialization.");
1554 return Meta.NoAddress | (
Meta.NoHWAddress << 1) |
1555 (
Meta.Memtag << 2) | (
Meta.IsDynInit << 3);
1561void ModuleBitcodeWriter::writeModuleInfo() {
1563 if (!
M.getTargetTriple().empty())
1565 M.getTargetTriple().str(), 0 );
1566 const std::string &
DL =
M.getDataLayoutStr();
1570 for (
const Module::GlobalAsmFragment &Frag :
M.getModuleInlineAsm()) {
1572 Frag.Props.getAsStrings();
1585 std::map<std::string, unsigned> SectionMap;
1586 std::map<std::string, unsigned> GCMap;
1587 MaybeAlign MaxGVarAlignment;
1588 unsigned MaxGlobalType = 0;
1589 for (
const GlobalVariable &GV :
M.globals()) {
1590 if (MaybeAlign
A = GV.getAlign())
1591 MaxGVarAlignment = !MaxGVarAlignment ? *
A : std::max(*MaxGVarAlignment, *
A);
1592 MaxGlobalType = std::max(MaxGlobalType, VE.
getTypeID(GV.getValueType()));
1593 if (GV.hasSection()) {
1595 unsigned &
Entry = SectionMap[std::string(GV.getSection())];
1599 Entry = SectionMap.size();
1604 if (
F.hasSection()) {
1606 unsigned &
Entry = SectionMap[std::string(
F.getSection())];
1610 Entry = SectionMap.size();
1615 unsigned &
Entry = GCMap[
F.getGC()];
1619 Entry = GCMap.size();
1625 unsigned SimpleGVarAbbrev = 0;
1626 if (!
M.global_empty()) {
1628 auto Abbv = std::make_shared<BitCodeAbbrev>();
1639 if (!MaxGVarAlignment)
1640 Abbv->Add(BitCodeAbbrevOp(0));
1642 unsigned MaxEncAlignment = getEncodedAlign(MaxGVarAlignment);
1646 if (SectionMap.empty())
1647 Abbv->Add(BitCodeAbbrevOp(0));
1652 SimpleGVarAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1666 auto Abbv = std::make_shared<BitCodeAbbrev>();
1669 Abbv->Add(AbbrevOpToUse);
1670 unsigned FilenameAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1672 for (
const auto P :
M.getSourceFileName())
1683 for (
const GlobalVariable &GV :
M.globals()) {
1684 unsigned AbbrevToUse = 0;
1690 Vals.
push_back(addToStrtab(GV.getName()));
1693 Vals.
push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1697 Vals.
push_back(getEncodedAlign(GV.getAlign()));
1698 Vals.
push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]
1700 if (GV.isThreadLocal() ||
1702 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1703 GV.isExternallyInitialized() ||
1705 GV.hasComdat() || GV.hasAttributes() || GV.isDSOLocal() ||
1706 GV.hasPartition() || GV.hasSanitizerMetadata() || GV.getCodeModel()) {
1710 Vals.
push_back(GV.isExternallyInitialized());
1714 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1718 Vals.
push_back(addToStrtab(GV.getPartition()));
1719 Vals.
push_back(GV.getPartition().size());
1722 GV.getSanitizerMetadata())
1726 AbbrevToUse = SimpleGVarAbbrev;
1747 Vals.
push_back(getEncodedAlign(
F.getAlign()));
1748 Vals.
push_back(
F.hasSection() ? SectionMap[std::string(
F.getSection())]
1760 F.hasPersonalityFn() ? (VE.
getValueID(
F.getPersonalityFn()) + 1) : 0);
1764 Vals.
push_back(addToStrtab(
F.getPartition()));
1766 Vals.
push_back(getEncodedAlign(
F.getPreferredAlignment()));
1768 unsigned AbbrevToUse = 0;
1774 for (
const GlobalAlias &
A :
M.aliases()) {
1781 Vals.
push_back(
A.getType()->getAddressSpace());
1789 Vals.
push_back(addToStrtab(
A.getPartition()));
1792 unsigned AbbrevToUse = 0;
1798 for (
const GlobalIFunc &
I :
M.ifuncs()) {
1804 Vals.
push_back(
I.getType()->getAddressSpace());
1809 Vals.
push_back(addToStrtab(
I.getPartition()));
1815 writeValueSymbolTableForwardDecl();
1822 if (OBO->hasNoSignedWrap())
1824 if (OBO->hasNoUnsignedWrap())
1830 if (PDI->isDisjoint())
1833 if (FPMO->hasAllowReassoc())
1835 if (FPMO->hasNoNaNs())
1837 if (FPMO->hasNoInfs())
1839 if (FPMO->hasNoSignedZeros())
1841 if (FPMO->hasAllowReciprocal())
1843 if (FPMO->hasAllowContract())
1845 if (FPMO->hasApproxFunc())
1851 if (NNI->hasNonNeg())
1855 if (NNI->hasNonNeg())
1858 if (TI->hasNoSignedWrap())
1860 if (TI->hasNoUnsignedWrap())
1863 if (
GEP->isInBounds())
1865 if (
GEP->hasNoUnsignedSignedWrap())
1867 if (
GEP->hasNoUnsignedWrap())
1870 if (ICmp->hasSameSign())
1873 if (ASC->hasNonNull())
1880void ModuleBitcodeWriter::writeValueAsMetadata(
1881 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
1890void ModuleBitcodeWriter::writeMDTuple(
const MDTuple *
N,
1891 SmallVectorImpl<uint64_t> &Record,
1893 for (
const MDOperand &MDO :
N->operands()) {
1896 "Unexpected function-local metadata");
1905unsigned ModuleBitcodeWriter::createDILocationAbbrev(
bool WithIRLayers) {
1911 auto Abbv = std::make_shared<BitCodeAbbrev>();
1926void ModuleBitcodeWriter::writeDILocation(
const DILocation *
N,
1927 SmallVectorImpl<uint64_t> &Record,
1930 Abbrev = createDILocationAbbrev(
false);
1932 Record.push_back(
N->isDistinct());
1933 Record.push_back(
N->getLine());
1934 Record.push_back(
N->getColumn());
1937 Record.push_back(
N->isImplicitCode());
1938 Record.push_back(
N->getAtomGroup());
1939 Record.push_back(
N->getAtomRank());
1941 unsigned AbbrevToUse = Abbrev;
1942 if (DILayerLocList *IRLayers =
N->getIRLayers()) {
1943 if (!DILocationLayersAbbrev)
1944 DILocationLayersAbbrev = createDILocationAbbrev(
true);
1945 AbbrevToUse = DILocationLayersAbbrev;
1953void ModuleBitcodeWriter::writeDILayerLoc(
const DILayerLoc *
N,
1954 SmallVectorImpl<uint64_t> &Record,
1956 Record.push_back(
N->isDistinct());
1957 Record.push_back(
N->getLine());
1958 Record.push_back(
N->getColumn());
1965void ModuleBitcodeWriter::writeDILayerLocList(
const DILayerLocList *
N,
1966 SmallVectorImpl<uint64_t> &Record,
1968 Record.push_back(
N->isDistinct());
1969 for (
const MDOperand &
Op :
N->layers())
1975unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1978 auto Abbv = std::make_shared<BitCodeAbbrev>();
1989void ModuleBitcodeWriter::writeGenericDINode(
const GenericDINode *
N,
1990 SmallVectorImpl<uint64_t> &Record,
1993 Abbrev = createGenericDINodeAbbrev();
1995 Record.push_back(
N->isDistinct());
1996 Record.push_back(
N->getTag());
1999 for (
auto &
I :
N->operands())
2006void ModuleBitcodeWriter::writeDISubrange(
const DISubrange *
N,
2007 SmallVectorImpl<uint64_t> &Record,
2020void ModuleBitcodeWriter::writeDIGenericSubrange(
2021 const DIGenericSubrange *
N, SmallVectorImpl<uint64_t> &Record,
2033void ModuleBitcodeWriter::writeDIEnumerator(
const DIEnumerator *
N,
2034 SmallVectorImpl<uint64_t> &Record,
2037 Record.push_back(IsBigInt | (
N->isUnsigned() << 1) |
N->isDistinct());
2038 Record.push_back(
N->getValue().getBitWidth());
2046void ModuleBitcodeWriter::writeDIBasicType(
const DIBasicType *
N,
2047 SmallVectorImpl<uint64_t> &Record,
2049 const unsigned SizeIsMetadata = 0x2;
2050 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2051 Record.push_back(
N->getTag());
2054 Record.push_back(
N->getAlignInBits());
2055 Record.push_back(
N->getEncoding());
2056 Record.push_back(
N->getFlags());
2057 Record.push_back(
N->getNumExtraInhabitants());
2058 Record.push_back(
N->getDataSizeInBits());
2060 Record.push_back(
N->getLine());
2067void ModuleBitcodeWriter::writeDIFixedPointType(
2068 const DIFixedPointType *
N, SmallVectorImpl<uint64_t> &Record,
2070 const unsigned SizeIsMetadata = 0x2;
2071 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2072 Record.push_back(
N->getTag());
2075 Record.push_back(
N->getAlignInBits());
2076 Record.push_back(
N->getEncoding());
2077 Record.push_back(
N->getFlags());
2078 Record.push_back(
N->getKind());
2079 Record.push_back(
N->getFactorRaw());
2081 auto WriteWideInt = [&](
const APInt &
Value) {
2086 Record.push_back(Encoded);
2090 WriteWideInt(
N->getNumeratorRaw());
2091 WriteWideInt(
N->getDenominatorRaw());
2094 Record.push_back(
N->getLine());
2101void ModuleBitcodeWriter::writeDIStringType(
const DIStringType *
N,
2102 SmallVectorImpl<uint64_t> &Record,
2104 const unsigned SizeIsMetadata = 0x2;
2105 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2106 Record.push_back(
N->getTag());
2112 Record.push_back(
N->getAlignInBits());
2113 Record.push_back(
N->getEncoding());
2120void ModuleBitcodeWriter::writeDIDerivedType(
const DIDerivedType *
N,
2121 SmallVectorImpl<uint64_t> &Record,
2123 const unsigned SizeIsMetadata = 0x2;
2124 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2125 Record.push_back(
N->getTag());
2128 Record.push_back(
N->getLine());
2132 Record.push_back(
N->getAlignInBits());
2134 Record.push_back(
N->getFlags());
2139 if (
const auto &DWARFAddressSpace =
N->getDWARFAddressSpace())
2140 Record.push_back(*DWARFAddressSpace + 1);
2146 if (
auto PtrAuthData =
N->getPtrAuthData())
2147 Record.push_back(PtrAuthData->RawData);
2155void ModuleBitcodeWriter::writeDISubrangeType(
const DISubrangeType *
N,
2156 SmallVectorImpl<uint64_t> &Record,
2158 const unsigned SizeIsMetadata = 0x2;
2159 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2162 Record.push_back(
N->getLine());
2165 Record.push_back(
N->getAlignInBits());
2166 Record.push_back(
N->getFlags());
2177void ModuleBitcodeWriter::writeDICompositeType(
2178 const DICompositeType *
N, SmallVectorImpl<uint64_t> &Record,
2180 const unsigned IsNotUsedInOldTypeRef = 0x2;
2181 const unsigned SizeIsMetadata = 0x4;
2182 Record.push_back(SizeIsMetadata | IsNotUsedInOldTypeRef |
2183 (
unsigned)
N->isDistinct());
2184 Record.push_back(
N->getTag());
2187 Record.push_back(
N->getLine());
2191 Record.push_back(
N->getAlignInBits());
2193 Record.push_back(
N->getFlags());
2195 Record.push_back(
N->getRuntimeLang());
2205 Record.push_back(
N->getNumExtraInhabitants());
2215void ModuleBitcodeWriter::writeDISubroutineType(
2216 const DISubroutineType *
N, SmallVectorImpl<uint64_t> &Record,
2218 const unsigned HasNoOldTypeRefs = 0x2;
2219 Record.push_back(HasNoOldTypeRefs | (
unsigned)
N->isDistinct());
2220 Record.push_back(
N->getFlags());
2228void ModuleBitcodeWriter::writeDIFile(
const DIFile *
N,
2229 SmallVectorImpl<uint64_t> &Record,
2231 Record.push_back(
N->isDistinct());
2234 if (
N->getRawChecksum()) {
2235 Record.push_back(
N->getRawChecksum()->Kind);
2243 auto Source =
N->getRawSource();
2251void ModuleBitcodeWriter::writeDICompileUnit(
const DICompileUnit *
N,
2252 SmallVectorImpl<uint64_t> &Record,
2254 assert(
N->isDistinct() &&
"Expected distinct compile units");
2257 auto Lang =
N->getSourceLanguage();
2258 Record.push_back(Lang.getName());
2261 if (Lang.hasVersionedName())
2266 Record.push_back(
N->isOptimized());
2268 Record.push_back(
N->getRuntimeVersion());
2270 Record.push_back(
N->getEmissionKind());
2276 Record.push_back(
N->getDWOId());
2278 Record.push_back(
N->getSplitDebugInlining());
2279 Record.push_back(
N->getDebugInfoForProfiling());
2280 Record.push_back((
unsigned)
N->getNameTableKind());
2281 Record.push_back(
N->getRangesBaseAddress());
2284 Record.push_back(Lang.hasVersionedName() ? Lang.getVersion() : 0);
2285 Record.push_back(Lang.getDialect());
2291void ModuleBitcodeWriter::writeDISubprogram(
const DISubprogram *
N,
2292 SmallVectorImpl<uint64_t> &Record,
2294 const uint64_t HasUnitFlag = 1 << 1;
2295 const uint64_t HasSPFlagsFlag = 1 << 2;
2296 Record.push_back(
uint64_t(
N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
2301 Record.push_back(
N->getLine());
2303 Record.push_back(
N->getScopeLine());
2305 Record.push_back(
N->getSPFlags());
2306 Record.push_back(
N->getVirtualIndex());
2307 Record.push_back(
N->getFlags());
2312 Record.push_back(
N->getThisAdjustment());
2316 Record.push_back(
N->getKeyInstructionsEnabled());
2322void ModuleBitcodeWriter::writeDILexicalBlock(
const DILexicalBlock *
N,
2323 SmallVectorImpl<uint64_t> &Record,
2325 Record.push_back(
N->isDistinct());
2328 Record.push_back(
N->getLine());
2329 Record.push_back(
N->getColumn());
2335void ModuleBitcodeWriter::writeDILexicalBlockFile(
2336 const DILexicalBlockFile *
N, SmallVectorImpl<uint64_t> &Record,
2338 Record.push_back(
N->isDistinct());
2341 Record.push_back(
N->getDiscriminator());
2347void ModuleBitcodeWriter::writeDICommonBlock(
const DICommonBlock *
N,
2348 SmallVectorImpl<uint64_t> &Record,
2350 Record.push_back(
N->isDistinct());
2355 Record.push_back(
N->getLineNo());
2361void ModuleBitcodeWriter::writeDINamespace(
const DINamespace *
N,
2362 SmallVectorImpl<uint64_t> &Record,
2364 Record.push_back(
N->isDistinct() |
N->getExportSymbols() << 1);
2372void ModuleBitcodeWriter::writeDIMacro(
const DIMacro *
N,
2373 SmallVectorImpl<uint64_t> &Record,
2375 Record.push_back(
N->isDistinct());
2376 Record.push_back(
N->getMacinfoType());
2377 Record.push_back(
N->getLine());
2385void ModuleBitcodeWriter::writeDIMacroFile(
const DIMacroFile *
N,
2386 SmallVectorImpl<uint64_t> &Record,
2388 Record.push_back(
N->isDistinct());
2389 Record.push_back(
N->getMacinfoType());
2390 Record.push_back(
N->getLine());
2398void ModuleBitcodeWriter::writeDIArgList(
const DIArgList *
N,
2399 SmallVectorImpl<uint64_t> &Record) {
2400 Record.reserve(
N->getArgs().size());
2401 for (ValueAsMetadata *MD :
N->getArgs())
2408void ModuleBitcodeWriter::writeDIModule(
const DIModule *
N,
2409 SmallVectorImpl<uint64_t> &Record,
2411 Record.push_back(
N->isDistinct());
2412 for (
auto &
I :
N->operands())
2414 Record.push_back(
N->getLineNo());
2415 Record.push_back(
N->getIsDecl());
2421void ModuleBitcodeWriter::writeDIAssignID(
const DIAssignID *
N,
2422 SmallVectorImpl<uint64_t> &Record,
2425 Record.push_back(
N->isDistinct());
2430void ModuleBitcodeWriter::writeDITemplateTypeParameter(
2431 const DITemplateTypeParameter *
N, SmallVectorImpl<uint64_t> &Record,
2433 Record.push_back(
N->isDistinct());
2436 Record.push_back(
N->isDefault());
2442void ModuleBitcodeWriter::writeDITemplateValueParameter(
2443 const DITemplateValueParameter *
N, SmallVectorImpl<uint64_t> &Record,
2445 Record.push_back(
N->isDistinct());
2446 Record.push_back(
N->getTag());
2449 Record.push_back(
N->isDefault());
2456void ModuleBitcodeWriter::writeDIGlobalVariable(
2457 const DIGlobalVariable *
N, SmallVectorImpl<uint64_t> &Record,
2465 Record.push_back(
N->getLine());
2467 Record.push_back(
N->isLocalToUnit());
2468 Record.push_back(
N->isDefinition());
2471 Record.push_back(
N->getAlignInBits());
2478void ModuleBitcodeWriter::writeDILocalVariable(
2479 const DILocalVariable *
N, SmallVectorImpl<uint64_t> &Record,
2494 const uint64_t HasAlignmentFlag = 1 << 1;
2499 Record.push_back(
N->getLine());
2501 Record.push_back(
N->getArg());
2502 Record.push_back(
N->getFlags());
2503 Record.push_back(
N->getAlignInBits());
2510void ModuleBitcodeWriter::writeDILabel(
2511 const DILabel *
N, SmallVectorImpl<uint64_t> &Record,
2518 Record.push_back(
N->getLine());
2519 Record.push_back(
N->getColumn());
2520 Record.push_back(
N->getCoroSuspendIdx().has_value()
2521 ? (
uint64_t)
N->getCoroSuspendIdx().value()
2522 : std::numeric_limits<uint64_t>::max());
2528void ModuleBitcodeWriter::writeDIExpression(
const DIExpression *
N,
2529 SmallVectorImpl<uint64_t> &Record,
2531 Record.reserve(
N->getElements().size() + 1);
2534 Record.append(
N->elements_begin(),
N->elements_end());
2540void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
2541 const DIGlobalVariableExpression *
N, SmallVectorImpl<uint64_t> &Record,
2543 Record.push_back(
N->isDistinct());
2551void ModuleBitcodeWriter::writeDIObjCProperty(
const DIObjCProperty *
N,
2552 SmallVectorImpl<uint64_t> &Record,
2554 Record.push_back(
N->isDistinct());
2557 Record.push_back(
N->getLine());
2560 Record.push_back(
N->getAttributes());
2567void ModuleBitcodeWriter::writeDIProperty(
const DIProperty *
N,
2568 SmallVectorImpl<uint64_t> &Record,
2570 Record.push_back(
N->isDistinct());
2573 Record.push_back(
N->getLine());
2581void ModuleBitcodeWriter::writeDIImportedEntity(
2582 const DIImportedEntity *
N, SmallVectorImpl<uint64_t> &Record,
2584 Record.push_back(
N->isDistinct());
2585 Record.push_back(
N->getTag());
2588 Record.push_back(
N->getLine());
2597unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
2598 auto Abbv = std::make_shared<BitCodeAbbrev>();
2605void ModuleBitcodeWriter::writeNamedMetadata(
2606 SmallVectorImpl<uint64_t> &Record) {
2607 if (
M.named_metadata_empty())
2610 unsigned Abbrev = createNamedMetadataAbbrev();
2611 for (
const NamedMDNode &NMD :
M.named_metadata()) {
2613 StringRef Str = NMD.getName();
2614 Record.append(Str.bytes_begin(), Str.bytes_end());
2619 for (
const MDNode *
N : NMD.operands())
2626unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
2627 auto Abbv = std::make_shared<BitCodeAbbrev>();
2639void ModuleBitcodeWriter::writeMetadataStrings(
2641 if (Strings.
empty())
2649 SmallString<256> Blob;
2651 BitstreamWriter
W(Blob);
2671#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
2672#include "llvm/IR/Metadata.def"
2676void ModuleBitcodeWriter::writeMetadataRecords(
2678 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
2683#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
2684#include "llvm/IR/Metadata.def"
2690 assert(
N->isResolved() &&
"Expected forward references to be resolved");
2692 switch (
N->getMetadataID()) {
2695#define HANDLE_MDNODE_LEAF(CLASS) \
2696 case Metadata::CLASS##Kind: \
2698 write##CLASS(cast<CLASS>(N), Record, \
2699 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
2701 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
2703#include "llvm/IR/Metadata.def"
2714void ModuleBitcodeWriter::writeModuleMetadata() {
2715 if (!VE.
hasMDs() &&
M.named_metadata_empty())
2719 SmallVector<uint64_t, 64>
Record;
2723 std::vector<unsigned> MDAbbrevs;
2726 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] =
2727 createDILocationAbbrev(
false);
2728 DILocationLayersAbbrev = createDILocationAbbrev(
true);
2729 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
2730 createGenericDINodeAbbrev();
2732 auto Abbv = std::make_shared<BitCodeAbbrev>();
2736 unsigned OffsetAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
2738 Abbv = std::make_shared<BitCodeAbbrev>();
2742 unsigned IndexAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
2764 std::vector<uint64_t> IndexPos;
2768 writeMetadataRecords(VE.
getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2779 uint64_t PreviousValue = IndexOffsetRecordBitPos;
2780 for (
auto &Elt : IndexPos) {
2781 auto EltDelta = Elt - PreviousValue;
2782 PreviousValue = Elt;
2791 writeNamedMetadata(Record);
2793 auto AddDeclAttachedMetadata = [&](
const GlobalObject &GO) {
2794 SmallVector<uint64_t, 4>
Record;
2796 pushGlobalMetadataAttachment(Record, GO);
2800 if (
F.isDeclaration() &&
F.hasMetadata())
2801 AddDeclAttachedMetadata(
F);
2802 for (
const GlobalIFunc &GI :
M.ifuncs())
2803 if (GI.hasMetadata())
2804 AddDeclAttachedMetadata(GI);
2807 for (
const GlobalVariable &GV :
M.globals())
2808 if (GV.hasMetadata())
2809 AddDeclAttachedMetadata(GV);
2814void ModuleBitcodeWriter::writeFunctionMetadata(
const Function &
F) {
2821 DILocationLayersAbbrev = 0;
2822 SmallVector<uint64_t, 64>
Record;
2828void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2829 SmallVectorImpl<uint64_t> &Record,
const GlobalObject &GO) {
2833 for (
const auto &
I : MDs) {
2839void ModuleBitcodeWriter::writeFunctionMetadataAttachment(
const Function &
F) {
2842 SmallVector<uint64_t, 64>
Record;
2844 if (
F.hasMetadata()) {
2845 pushGlobalMetadataAttachment(Record,
F);
2853 for (
const BasicBlock &BB :
F)
2854 for (
const Instruction &
I : BB) {
2856 I.getAllMetadataOtherThanDebugLoc(MDs);
2859 if (MDs.
empty())
continue;
2863 for (
const auto &[ID, MD] : MDs) {
2874void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2875 SmallVector<uint64_t, 64>
Record;
2880 M.getMDKindNames(Names);
2882 if (Names.
empty())
return;
2886 for (
unsigned MDKindID = 0, e = Names.
size(); MDKindID != e; ++MDKindID) {
2887 Record.push_back(MDKindID);
2888 StringRef KName = Names[MDKindID];
2898void ModuleBitcodeWriter::writeOperandBundleTags() {
2906 M.getOperandBundleTags(Tags);
2913 SmallVector<uint64_t, 64>
Record;
2915 for (
auto Tag : Tags) {
2925void ModuleBitcodeWriter::writeSyncScopeNames() {
2927 M.getContext().getSyncScopeNames(SSNs);
2933 SmallVector<uint64_t, 64>
Record;
2934 for (
auto SSN : SSNs) {
2935 Record.append(SSN.begin(), SSN.end());
2943void ModuleBitcodeWriter::writeConstants(
unsigned FirstVal,
unsigned LastVal,
2945 if (FirstVal == LastVal)
return;
2949 unsigned AggregateAbbrev = 0;
2950 unsigned String8Abbrev = 0;
2951 unsigned CString7Abbrev = 0;
2952 unsigned CString6Abbrev = 0;
2956 auto Abbv = std::make_shared<BitCodeAbbrev>();
2960 AggregateAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
2963 Abbv = std::make_shared<BitCodeAbbrev>();
2967 String8Abbrev = Stream.
EmitAbbrev(std::move(Abbv));
2969 Abbv = std::make_shared<BitCodeAbbrev>();
2973 CString7Abbrev = Stream.
EmitAbbrev(std::move(Abbv));
2975 Abbv = std::make_shared<BitCodeAbbrev>();
2979 CString6Abbrev = Stream.
EmitAbbrev(std::move(Abbv));
2982 SmallVector<uint64_t, 64>
Record;
2985 Type *LastTy =
nullptr;
2986 for (
unsigned i = FirstVal; i != LastVal; ++i) {
2987 const Value *
V = Vals[i].first;
2989 if (
V->getType() != LastTy) {
2990 LastTy =
V->getType();
2993 CONSTANTS_SETTYPE_ABBREV);
3000 unsigned(
IA->hasSideEffects()) |
unsigned(
IA->isAlignStack()) << 1 |
3001 unsigned(
IA->getDialect() & 1) << 2 |
unsigned(
IA->canThrow()) << 3);
3004 StringRef AsmStr =
IA->getAsmString();
3009 StringRef ConstraintStr =
IA->getConstraintString();
3017 unsigned Code = -1U;
3018 unsigned AbbrevToUse = 0;
3019 if (
C->isNullValue()) {
3026 if (
IV->getBitWidth() <= 64) {
3030 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
3036 if (BV->getBitWidth() <= 64) {
3040 AbbrevToUse = CONSTANTS_BYTE_ABBREV;
3050 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
3054 APInt api = CFP->getValueAPF().bitcastToAPInt();
3056 Record.push_back((p[1] << 48) | (p[0] >> 16));
3057 Record.push_back(p[0] & 0xffffLL);
3059 APInt api = CFP->getValueAPF().bitcastToAPInt();
3064 assert(0 &&
"Unknown FP type!");
3070 uint64_t NumElts = Str->getNumElements();
3072 if (Str->isCString()) {
3077 AbbrevToUse = String8Abbrev;
3081 for (
uint64_t i = 0; i != NumElts; ++i) {
3082 unsigned char V = Str->getElementAsInteger(i);
3084 isCStr7 &= (
V & 128) == 0;
3090 AbbrevToUse = CString6Abbrev;
3092 AbbrevToUse = CString7Abbrev;
3093 }
else if (
const ConstantDataSequential *CDS =
3096 Type *EltTy = CDS->getElementType();
3098 for (
uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i)
3099 Record.push_back(CDS->getElementAsInteger(i));
3101 for (
uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i)
3103 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
3107 for (
const Value *
Op :
C->operands())
3109 AbbrevToUse = AggregateAbbrev;
3111 switch (
CE->getOpcode()) {
3118 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
3120 assert(
CE->getNumOperands() == 2 &&
"Unknown constant expr!");
3130 case Instruction::FNeg: {
3131 assert(
CE->getNumOperands() == 1 &&
"Unknown constant expr!");
3140 case Instruction::GetElementPtr: {
3145 if (std::optional<ConstantRange>
Range = GO->getInRange()) {
3149 for (
const Value *
Op :
CE->operands()) {
3155 case Instruction::ExtractElement:
3162 case Instruction::InsertElement:
3169 case Instruction::ShuffleVector:
3174 if (
C->getType() ==
C->getOperand(0)->getType()) {
3211 Stream.
EmitRecord(Code, Record, AbbrevToUse);
3218void ModuleBitcodeWriter::writeModuleConstants() {
3223 for (
unsigned i = 0, e = Vals.size(); i != e; ++i) {
3225 writeConstants(i, Vals.size(),
true);
3239bool ModuleBitcodeWriter::pushValueAndType(
const Value *V,
unsigned InstID,
3240 SmallVectorImpl<unsigned> &Vals) {
3244 if (ValID >= InstID) {
3251bool ModuleBitcodeWriter::pushValueOrMetadata(
const Value *V,
unsigned InstID,
3252 SmallVectorImpl<unsigned> &Vals) {
3253 bool IsMetadata =
V->getType()->isMetadataTy();
3261 return pushValueAndType(V, InstID, Vals);
3264void ModuleBitcodeWriter::writeOperandBundles(
const CallBase &CS,
3271 Record.push_back(
C.getOperandBundleTagID(Bundle.getTagName()));
3273 for (
auto &Input : Bundle.Inputs)
3274 pushValueOrMetadata(Input, InstID, Record);
3283void ModuleBitcodeWriter::pushValue(
const Value *V,
unsigned InstID,
3284 SmallVectorImpl<unsigned> &Vals) {
3289void ModuleBitcodeWriter::pushValueSigned(
const Value *V,
unsigned InstID,
3290 SmallVectorImpl<uint64_t> &Vals) {
3292 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
3297void ModuleBitcodeWriter::writeInstruction(
const Instruction &
I,
3299 SmallVectorImpl<unsigned> &Vals) {
3301 unsigned AbbrevToUse = 0;
3303 switch (
I.getOpcode()) {
3307 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3308 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
3313 if (AbbrevToUse == FUNCTION_INST_CAST_ABBREV)
3314 AbbrevToUse = FUNCTION_INST_CAST_FLAGS_ABBREV;
3320 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3321 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
3322 pushValue(
I.getOperand(1), InstID, Vals);
3326 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
3327 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
3332 case Instruction::FNeg: {
3334 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3335 AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
3339 if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
3340 AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
3345 case Instruction::GetElementPtr: {
3347 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
3351 for (
const Value *
Op :
I.operands())
3352 pushValueAndType(
Op, InstID, Vals);
3355 case Instruction::ExtractValue: {
3357 pushValueAndType(
I.getOperand(0), InstID, Vals);
3362 case Instruction::InsertValue: {
3364 pushValueAndType(
I.getOperand(0), InstID, Vals);
3365 pushValueAndType(
I.getOperand(1), InstID, Vals);
3370 case Instruction::Select: {
3372 pushValueAndType(
I.getOperand(1), InstID, Vals);
3373 pushValue(
I.getOperand(2), InstID, Vals);
3374 pushValueAndType(
I.getOperand(0), InstID, Vals);
3380 case Instruction::ExtractElement:
3382 pushValueAndType(
I.getOperand(0), InstID, Vals);
3383 pushValueAndType(
I.getOperand(1), InstID, Vals);
3385 case Instruction::InsertElement:
3387 pushValueAndType(
I.getOperand(0), InstID, Vals);
3388 pushValue(
I.getOperand(1), InstID, Vals);
3389 pushValueAndType(
I.getOperand(2), InstID, Vals);
3391 case Instruction::BitExtract:
3394 pushValueAndType(
I.getOperand(0), InstID, Vals);
3395 pushValueAndType(
I.getOperand(1), InstID, Vals);
3397 case Instruction::BitInsert:
3399 pushValueAndType(
I.getOperand(0), InstID, Vals);
3400 pushValueAndType(
I.getOperand(1), InstID, Vals);
3401 pushValueAndType(
I.getOperand(2), InstID, Vals);
3403 case Instruction::ShuffleVector:
3405 pushValueAndType(
I.getOperand(0), InstID, Vals);
3406 pushValue(
I.getOperand(1), InstID, Vals);
3410 case Instruction::ICmp:
3411 case Instruction::FCmp: {
3414 AbbrevToUse = FUNCTION_INST_CMP_ABBREV;
3415 if (pushValueAndType(
I.getOperand(0), InstID, Vals))
3417 pushValue(
I.getOperand(1), InstID, Vals);
3423 AbbrevToUse = FUNCTION_INST_CMP_FLAGS_ABBREV;
3428 case Instruction::Ret:
3431 unsigned NumOperands =
I.getNumOperands();
3432 if (NumOperands == 0)
3433 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
3434 else if (NumOperands == 1) {
3435 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3436 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
3438 for (
const Value *
Op :
I.operands())
3439 pushValueAndType(
Op, InstID, Vals);
3443 case Instruction::UncondBr: {
3445 AbbrevToUse = FUNCTION_INST_BR_UNCOND_ABBREV;
3449 case Instruction::CondBr: {
3451 AbbrevToUse = FUNCTION_INST_BR_COND_ABBREV;
3455 pushValue(
II.getCondition(), InstID, Vals);
3457 case Instruction::Switch:
3462 pushValue(
SI.getCondition(), InstID, Vals);
3464 for (
auto Case :
SI.cases()) {
3470 case Instruction::IndirectBr:
3474 pushValue(
I.getOperand(0), InstID, Vals);
3479 case Instruction::Invoke: {
3482 FunctionType *FTy =
II->getFunctionType();
3484 if (
II->hasOperandBundles())
3485 writeOperandBundles(*
II, InstID);
3494 pushValueAndType(Callee, InstID, Vals);
3497 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3498 pushValue(
I.getOperand(i), InstID, Vals);
3501 if (FTy->isVarArg()) {
3502 for (
unsigned i = FTy->getNumParams(), e =
II->arg_size(); i != e; ++i)
3503 pushValueAndType(
I.getOperand(i), InstID, Vals);
3507 case Instruction::Resume:
3509 pushValueAndType(
I.getOperand(0), InstID, Vals);
3511 case Instruction::CleanupRet: {
3514 pushValue(CRI.getCleanupPad(), InstID, Vals);
3515 if (CRI.hasUnwindDest())
3519 case Instruction::CatchRet: {
3522 pushValue(CRI.getCatchPad(), InstID, Vals);
3526 case Instruction::CleanupPad:
3527 case Instruction::CatchPad: {
3531 pushValue(FuncletPad.getParentPad(), InstID, Vals);
3533 unsigned NumArgOperands = FuncletPad.arg_size();
3535 for (
unsigned Op = 0;
Op != NumArgOperands; ++
Op)
3536 pushValueAndType(FuncletPad.getArgOperand(
Op), InstID, Vals);
3539 case Instruction::CatchSwitch: {
3543 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
3545 unsigned NumHandlers = CatchSwitch.getNumHandlers();
3547 for (
const BasicBlock *CatchPadBB : CatchSwitch.handlers())
3550 if (CatchSwitch.hasUnwindDest())
3554 case Instruction::CallBr: {
3560 writeOperandBundles(*CBI, InstID);
3575 pushValueAndType(Callee, InstID, Vals);
3578 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3579 pushValue(
I.getOperand(i), InstID, Vals);
3582 if (FTy->isVarArg()) {
3583 for (
unsigned i = FTy->getNumParams(), e = CBI->
arg_size(); i != e; ++i)
3584 pushValueAndType(
I.getOperand(i), InstID, Vals);
3588 case Instruction::Unreachable:
3590 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
3593 case Instruction::PHI: {
3611 Stream.
EmitRecord(Code, Vals64, AbbrevToUse);
3616 case Instruction::LandingPad: {
3627 pushValueAndType(LP.
getClause(
I), InstID, Vals);
3632 case Instruction::Alloca: {
3638 using APV = AllocaPackedValues;
3640 unsigned EncodedAlign = getEncodedAlign(AI.
getAlign());
3642 Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1));
3644 EncodedAlign >> APV::AlignLower::Bits);
3651 if (AS !=
M.getDataLayout().getAllocaAddrSpace())
3656 case Instruction::Load: {
3658 if (LI.isAtomic()) {
3660 pushValueAndType(LI.getOperand(0), InstID, Vals);
3663 if (!pushValueAndType(LI.getOperand(0), InstID, Vals))
3664 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
3667 Vals.
push_back(getEncodedAlign(LI.getAlign()));
3669 if (LI.isAtomic()) {
3671 Vals.
push_back(getEncodedSyncScopeID(LI.getSyncScopeID()));
3672 if (LI.isElementwise())
3678 case Instruction::Store: {
3680 if (
SI.isAtomic()) {
3684 AbbrevToUse = FUNCTION_INST_STORE_ABBREV;
3686 if (pushValueAndType(
I.getOperand(1), InstID, Vals))
3688 if (pushValueAndType(
I.getOperand(0), InstID, Vals))
3692 if (
SI.isAtomic()) {
3694 Vals.
push_back(getEncodedSyncScopeID(
SI.getSyncScopeID()));
3695 if (
SI.isElementwise())
3701 case Instruction::AtomicCmpXchg:
3703 pushValueAndType(
I.getOperand(0), InstID, Vals);
3704 pushValueAndType(
I.getOperand(1), InstID, Vals);
3705 pushValue(
I.getOperand(2), InstID, Vals);
3716 case Instruction::AtomicRMW:
3718 pushValueAndType(
I.getOperand(0), InstID, Vals);
3719 pushValueAndType(
I.getOperand(1), InstID, Vals);
3727 case Instruction::Fence:
3732 case Instruction::Call: {
3737 writeOperandBundles(CI, InstID);
3757 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3761 if (FTy->isVarArg()) {
3762 for (
unsigned i = FTy->getNumParams(), e = CI.
arg_size(); i != e; ++i)
3767 case Instruction::VAArg:
3770 pushValue(
I.getOperand(0), InstID, Vals);
3773 case Instruction::Freeze:
3775 pushValueAndType(
I.getOperand(0), InstID, Vals);
3785void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3786 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3791 VSTOffset -= bitcodeStartBit();
3792 assert((VSTOffset & 31) == 0 &&
"VST block not 32-bit aligned");
3796 Stream.
BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
3800 auto Abbv = std::make_shared<BitCodeAbbrev>();
3804 unsigned FnEntryAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
3809 if (
F.isDeclaration())
3816 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&
F] - bitcodeStartBit();
3817 assert((BitcodeIndex & 31) == 0 &&
"function block not 32-bit aligned");
3821 Record[1] = BitcodeIndex / 32 + 1;
3830void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3831 const ValueSymbolTable &VST) {
3839 SmallVector<uint64_t, 64> NameVals;
3845 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3854 AbbrevToUse = VST_BBENTRY_6_ABBREV;
3858 AbbrevToUse = VST_ENTRY_6_ABBREV;
3860 AbbrevToUse = VST_ENTRY_7_ABBREV;
3863 for (
const auto P :
Name.getKey())
3867 Stream.
EmitRecord(Code, NameVals, AbbrevToUse);
3874void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3875 assert(Order.Shuffle.size() >= 2 &&
"Shuffle too small");
3882 SmallVector<uint64_t, 64>
Record(Order.Shuffle.begin(), Order.Shuffle.end());
3887void ModuleBitcodeWriter::writeUseListBlock(
const Function *
F) {
3889 "Expected to be preserving use-list order");
3891 auto hasMore = [&]() {
3907void ModuleBitcodeWriter::writeFunction(
3909 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3926 unsigned CstStart, CstEnd;
3928 writeConstants(CstStart, CstEnd,
false);
3931 writeFunctionMetadata(
F);
3934 unsigned InstID = CstEnd;
3936 bool NeedsMetadataAttachment =
F.hasMetadata();
3938 DILocation *LastDL =
nullptr;
3939 SmallSetVector<Function *, 4> BlockAddressUsers;
3942 for (
const BasicBlock &BB :
F) {
3943 for (
const Instruction &
I : BB) {
3944 writeInstruction(
I, InstID, Vals);
3946 if (!
I.getType()->isVoidTy())
3950 NeedsMetadataAttachment |=
I.hasMetadataOtherThanDebugLoc();
3953 if (DILocation *
DL =
I.getDebugLoc()) {
3966 unsigned DLAbbrev = FUNCTION_DEBUG_LOC_ABBREV;
3967 if (DILayerLocList *IRLayers =
DL->getIRLayers()) {
3968 DLAbbrev = FUNCTION_DEBUG_LOC_LAYERS_ABBREV;
3982 if (
I.hasDbgRecords()) {
3986 auto PushValueOrMetadata = [&Vals, InstID,
3989 "RawLocation unexpectedly null in DbgVariableRecord");
3991 SmallVector<unsigned, 2> ValAndType;
3995 if (!pushValueAndType(VAM->getValue(), InstID, ValAndType)) {
4009 for (DbgRecord &DR :
I.getDbgMarker()->getDbgRecordRange()) {
4035 FUNCTION_DEBUG_RECORD_VALUE_ABBREV);
4059 SmallPtrSet<Value *, 8> Visited{BA};
4060 while (!Worklist.
empty()) {
4062 for (User *U :
V->users()) {
4068 Visited.
insert(U).second)
4075 if (!BlockAddressUsers.
empty()) {
4084 if (
auto *Symtab =
F.getValueSymbolTable())
4085 writeFunctionLevelValueSymbolTable(*Symtab);
4087 if (NeedsMetadataAttachment)
4088 writeFunctionMetadataAttachment(
F);
4090 writeUseListBlock(&
F);
4096void ModuleBitcodeWriter::writeBlockInfo() {
4109 auto Abbv = std::make_shared<BitCodeAbbrev>();
4120 auto Abbv = std::make_shared<BitCodeAbbrev>();
4130 auto Abbv = std::make_shared<BitCodeAbbrev>();
4140 auto Abbv = std::make_shared<BitCodeAbbrev>();
4146 VST_BBENTRY_6_ABBREV)
4151 auto Abbv = std::make_shared<BitCodeAbbrev>();
4153 Abbv->Add(TypeAbbrevOp);
4155 CONSTANTS_SETTYPE_ABBREV)
4160 auto Abbv = std::make_shared<BitCodeAbbrev>();
4164 CONSTANTS_INTEGER_ABBREV)
4169 auto Abbv = std::make_shared<BitCodeAbbrev>();
4173 CONSTANTS_BYTE_ABBREV)
4178 auto Abbv = std::make_shared<BitCodeAbbrev>();
4186 CONSTANTS_CE_CAST_Abbrev)
4190 auto Abbv = std::make_shared<BitCodeAbbrev>();
4193 CONSTANTS_NULL_Abbrev)
4200 auto Abbv = std::make_shared<BitCodeAbbrev>();
4202 Abbv->Add(ValAbbrevOp);
4203 Abbv->Add(TypeAbbrevOp);
4207 FUNCTION_INST_LOAD_ABBREV)
4211 auto Abbv = std::make_shared<BitCodeAbbrev>();
4213 Abbv->Add(ValAbbrevOp);
4214 Abbv->Add(ValAbbrevOp);
4218 FUNCTION_INST_STORE_ABBREV)
4222 auto Abbv = std::make_shared<BitCodeAbbrev>();
4224 Abbv->Add(ValAbbrevOp);
4227 FUNCTION_INST_UNOP_ABBREV)
4231 auto Abbv = std::make_shared<BitCodeAbbrev>();
4233 Abbv->Add(ValAbbrevOp);
4237 FUNCTION_INST_UNOP_FLAGS_ABBREV)
4241 auto Abbv = std::make_shared<BitCodeAbbrev>();
4243 Abbv->Add(ValAbbrevOp);
4244 Abbv->Add(ValAbbrevOp);
4247 FUNCTION_INST_BINOP_ABBREV)
4251 auto Abbv = std::make_shared<BitCodeAbbrev>();
4253 Abbv->Add(ValAbbrevOp);
4254 Abbv->Add(ValAbbrevOp);
4258 FUNCTION_INST_BINOP_FLAGS_ABBREV)
4262 auto Abbv = std::make_shared<BitCodeAbbrev>();
4264 Abbv->Add(ValAbbrevOp);
4265 Abbv->Add(TypeAbbrevOp);
4268 FUNCTION_INST_CAST_ABBREV)
4272 auto Abbv = std::make_shared<BitCodeAbbrev>();
4274 Abbv->Add(ValAbbrevOp);
4275 Abbv->Add(TypeAbbrevOp);
4279 FUNCTION_INST_CAST_FLAGS_ABBREV)
4284 auto Abbv = std::make_shared<BitCodeAbbrev>();
4287 FUNCTION_INST_RET_VOID_ABBREV)
4291 auto Abbv = std::make_shared<BitCodeAbbrev>();
4293 Abbv->Add(ValAbbrevOp);
4295 FUNCTION_INST_RET_VAL_ABBREV)
4299 auto Abbv = std::make_shared<BitCodeAbbrev>();
4302 Abbv->Add(ValAbbrevOp);
4304 FUNCTION_INST_BR_UNCOND_ABBREV)
4308 auto Abbv = std::make_shared<BitCodeAbbrev>();
4311 Abbv->Add(ValAbbrevOp);
4312 Abbv->Add(ValAbbrevOp);
4313 Abbv->Add(ValAbbrevOp);
4315 FUNCTION_INST_BR_COND_ABBREV)
4319 auto Abbv = std::make_shared<BitCodeAbbrev>();
4322 FUNCTION_INST_UNREACHABLE_ABBREV)
4326 auto Abbv = std::make_shared<BitCodeAbbrev>();
4329 Abbv->Add(TypeAbbrevOp);
4331 Abbv->Add(ValAbbrevOp);
4333 FUNCTION_INST_GEP_ABBREV)
4337 auto Abbv = std::make_shared<BitCodeAbbrev>();
4339 Abbv->Add(ValAbbrevOp);
4340 Abbv->Add(ValAbbrevOp);
4343 FUNCTION_INST_CMP_ABBREV)
4347 auto Abbv = std::make_shared<BitCodeAbbrev>();
4349 Abbv->Add(ValAbbrevOp);
4350 Abbv->Add(ValAbbrevOp);
4354 FUNCTION_INST_CMP_FLAGS_ABBREV)
4358 auto Abbv = std::make_shared<BitCodeAbbrev>();
4363 Abbv->Add(ValAbbrevOp);
4365 FUNCTION_DEBUG_RECORD_VALUE_ABBREV)
4369 auto Abbv = std::make_shared<BitCodeAbbrev>();
4380 FUNCTION_DEBUG_LOC_ABBREV)
4386 auto Abbv = std::make_shared<BitCodeAbbrev>();
4397 FUNCTION_DEBUG_LOC_LAYERS_ABBREV)
4405void IndexBitcodeWriter::writeModStrings() {
4411 auto Abbv = std::make_shared<BitCodeAbbrev>();
4416 unsigned Abbrev8Bit = Stream.
EmitAbbrev(std::move(Abbv));
4419 Abbv = std::make_shared<BitCodeAbbrev>();
4424 unsigned Abbrev7Bit = Stream.
EmitAbbrev(std::move(Abbv));
4427 Abbv = std::make_shared<BitCodeAbbrev>();
4432 unsigned Abbrev6Bit = Stream.
EmitAbbrev(std::move(Abbv));
4435 Abbv = std::make_shared<BitCodeAbbrev>();
4442 unsigned AbbrevHash = Stream.
EmitAbbrev(std::move(Abbv));
4445 forEachModule([&](
const StringMapEntry<ModuleHash> &MPSE) {
4447 const auto &Hash = MPSE.
getValue();
4449 unsigned AbbrevToUse = Abbrev8Bit;
4451 AbbrevToUse = Abbrev6Bit;
4453 AbbrevToUse = Abbrev7Bit;
4455 auto ModuleId = ModuleIdMap.
size();
4456 ModuleIdMap[
Key] = ModuleId;
4466 Vals.
assign(Hash.begin(), Hash.end());
4478template <
typename Fn>
4482 if (!FS->type_tests().empty())
4487 auto WriteVFuncIdVec = [&](
uint64_t Ty,
4492 for (
auto &VF : VFs) {
4493 Record.push_back(VF.GUID);
4494 Record.push_back(VF.Offset);
4500 FS->type_test_assume_vcalls());
4502 FS->type_checked_load_vcalls());
4504 auto WriteConstVCallVec = [&](
uint64_t Ty,
4506 for (
auto &VC : VCs) {
4508 Record.push_back(VC.VFunc.GUID);
4509 Record.push_back(VC.VFunc.Offset);
4516 FS->type_test_assume_const_vcalls());
4518 FS->type_checked_load_const_vcalls());
4528 if (!FS->paramAccesses().empty()) {
4530 for (
auto &Arg : FS->paramAccesses()) {
4531 size_t UndoSize =
Record.size();
4532 Record.push_back(Arg.ParamNo);
4533 WriteRange(Arg.Use);
4534 Record.push_back(Arg.Calls.size());
4535 for (
auto &
Call : Arg.Calls) {
4537 std::optional<unsigned> ValueID = GetValueID(
Call.Callee);
4544 Record.push_back(*ValueID);
4545 WriteRange(
Call.Offsets);
4556 std::set<GlobalValue::GUID> &ReferencedTypeIds) {
4557 if (!FS->type_tests().empty())
4558 for (
auto &TT : FS->type_tests())
4559 ReferencedTypeIds.insert(TT);
4561 auto GetReferencedTypesFromVFuncIdVec =
4563 for (
auto &VF : VFs)
4564 ReferencedTypeIds.insert(VF.GUID);
4567 GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
4568 GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
4570 auto GetReferencedTypesFromConstVCallVec =
4572 for (
auto &VC : VCs)
4573 ReferencedTypeIds.insert(VC.VFunc.GUID);
4576 GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
4577 GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
4613 NameVals.
push_back(Summary.TTRes.TheKind);
4614 NameVals.
push_back(Summary.TTRes.SizeM1BitWidth);
4615 NameVals.
push_back(Summary.TTRes.AlignLog2);
4616 NameVals.
push_back(Summary.TTRes.SizeM1);
4617 NameVals.
push_back(Summary.TTRes.BitMask);
4618 NameVals.
push_back(Summary.TTRes.InlineBits);
4620 for (
auto &W : Summary.WPDRes)
4632 for (
auto &
P : Summary) {
4634 NameVals.
push_back(
VE.getValueID(
P.VTableVI.getValue()));
4648 static_assert(std::is_same_v<LinearFrameId, unsigned>);
4649 for (
auto &AI : FS->allocs()) {
4650 for (
auto &MIB : AI.MIBs) {
4652 StackIdIndices.
reserve(MIB.StackIdIndices.size());
4653 for (
auto Id : MIB.StackIdIndices)
4654 StackIdIndices.
push_back(GetStackIndex(Id));
4656 CallStacks.insert({CallStacks.size(), StackIdIndices});
4669 assert(!CallStacks.empty());
4675 Builder.
build(std::move(CallStacks),
nullptr,
4679 return Builder.takeCallStackPos();
4684 unsigned AllocAbbrev,
unsigned ContextIdAbbvId,
bool PerModule,
4685 std::function<
unsigned(
const ValueInfo &VI)> GetValueID,
4686 std::function<
unsigned(
unsigned)> GetStackIndex,
4687 bool WriteContextSizeInfoIndex,
4692 for (
auto &CI : FS->callsites()) {
4696 assert(!PerModule || (CI.Clones.size() == 1 && CI.Clones[0] == 0));
4697 Record.push_back(GetValueID(CI.Callee));
4699 Record.push_back(CI.StackIdIndices.size());
4700 Record.push_back(CI.Clones.size());
4702 for (
auto Id : CI.StackIdIndices)
4703 Record.push_back(GetStackIndex(Id));
4711 for (
auto &AI : FS->allocs()) {
4715 assert(!PerModule || (AI.Versions.size() == 1 && AI.Versions[0] == 0));
4716 Record.push_back(AI.MIBs.size());
4718 Record.push_back(AI.Versions.size());
4719 for (
auto &MIB : AI.MIBs) {
4726 assert(CallStackCount <= CallStackPos.
size());
4727 Record.push_back(CallStackPos[CallStackCount++]);
4732 assert(AI.ContextSizeInfos.empty() ||
4733 AI.ContextSizeInfos.size() == AI.MIBs.size());
4735 if (WriteContextSizeInfoIndex && !AI.ContextSizeInfos.empty()) {
4743 ContextIds.
reserve(AI.ContextSizeInfos.size() * 2);
4744 for (
auto &Infos : AI.ContextSizeInfos) {
4745 Record.push_back(Infos.size());
4746 for (
auto [FullStackId, TotalSize] : Infos) {
4753 Record.push_back(TotalSize);
4771void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
4772 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
4773 unsigned ValueID,
unsigned FSCallsProfileAbbrev,
unsigned CallsiteAbbrev,
4774 unsigned AllocAbbrev,
unsigned ContextIdAbbvId,
const Function &
F,
4775 DenseMap<CallStackId, LinearCallStackId> &CallStackPos,
4782 Stream, FS, [&](
const ValueInfo &VI) -> std::optional<unsigned> {
4786 auto SpecialRefCnts =
FS->specialRefCounts();
4791 NameVals.
push_back(SpecialRefCnts.first);
4792 NameVals.
push_back(SpecialRefCnts.second);
4794 for (
auto &RI :
FS->refs())
4797 for (
auto &ECI :
FS->calls()) {
4798 NameVals.
push_back(getValueId(ECI.first));
4807 Stream, FS, CallsiteAbbrev, AllocAbbrev, ContextIdAbbvId,
4809 [&](
const ValueInfo &VI) {
return getValueId(VI); },
4810 [&](
unsigned I) {
return I; },
4811 true, CallStackPos, CallStackCount);
4816void ModuleBitcodeWriterBase::writeModuleLevelReferences(
4817 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
4818 unsigned FSModRefsAbbrev,
unsigned FSModVTableRefsAbbrev) {
4823 auto VI =
Index->getValueInfo(GUID);
4824 if (!VI ||
VI.getSummaryList().empty()) {
4830 auto *
Summary =
VI.getSummaryList()[0].get();
4836 auto VTableFuncs =
VS->vTableFuncs();
4837 if (!VTableFuncs.empty())
4840 unsigned SizeBeforeRefs = NameVals.
size();
4841 for (
auto &RI :
VS->refs())
4847 if (VTableFuncs.empty())
4852 for (
auto &
P : VTableFuncs) {
4858 FSModVTableRefsAbbrev);
4865void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
4868 bool IsThinLTO =
true;
4871 IsThinLTO = MD->getZExtValue();
4883 if (
Index->enableSplitLTOUnit())
4885 if (
Index->hasUnifiedLTO())
4895 auto Abbv = std::make_shared<BitCodeAbbrev>();
4901 unsigned ValueGuidAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4903 for (
const auto &GVI : valueIds()) {
4905 ArrayRef<uint32_t>{GVI.second,
4906 static_cast<uint32_t
>(GVI.first >> 32),
4907 static_cast<uint32_t
>(GVI.first)},
4911 if (!
Index->stackIds().empty()) {
4912 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4919 unsigned StackIdAbbvId = Stream.
EmitAbbrev(std::move(StackIdAbbv));
4920 SmallVector<uint32_t> Vals;
4922 for (
auto Id :
Index->stackIds()) {
4923 Vals.
push_back(
static_cast<uint32_t
>(Id >> 32));
4924 Vals.
push_back(
static_cast<uint32_t
>(Id));
4929 unsigned ContextIdAbbvId = 0;
4932 auto ContextIdAbbv = std::make_shared<BitCodeAbbrev>();
4944 ContextIdAbbvId = Stream.
EmitAbbrev(std::move(ContextIdAbbv));
4948 Abbv = std::make_shared<BitCodeAbbrev>();
4960 unsigned FSCallsProfileAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4963 Abbv = std::make_shared<BitCodeAbbrev>();
4969 unsigned FSModRefsAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4972 Abbv = std::make_shared<BitCodeAbbrev>();
4980 unsigned FSModVTableRefsAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4983 Abbv = std::make_shared<BitCodeAbbrev>();
4988 unsigned FSAliasAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4991 Abbv = std::make_shared<BitCodeAbbrev>();
4998 unsigned TypeIdCompatibleVtableAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5000 Abbv = std::make_shared<BitCodeAbbrev>();
5006 unsigned CallsiteAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5008 Abbv = std::make_shared<BitCodeAbbrev>();
5015 unsigned AllocAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5017 Abbv = std::make_shared<BitCodeAbbrev>();
5022 unsigned RadixAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5029 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks;
5040 ValueInfo
VI =
Index->getValueInfo(GUID);
5041 if (!VI ||
VI.getSummaryList().empty()) {
5044 if (!
F.isDeclaration())
5046 " to have an associated value info.");
5049 auto *
Summary =
VI.getSummaryList()[0].get();
5052 FS, [](
unsigned I) {
return I; }, CallStacks);
5056 DenseMap<CallStackId, LinearCallStackId> CallStackPos;
5057 if (!CallStacks.
empty()) {
5065 SmallVector<uint64_t, 64> NameVals;
5076 ValueInfo
VI =
Index->getValueInfo(GUID);
5077 if (!VI ||
VI.getSummaryList().empty()) {
5083 auto *
Summary =
VI.getSummaryList()[0].get();
5084 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.
getValueID(&
F),
5085 FSCallsProfileAbbrev, CallsiteAbbrev,
5086 AllocAbbrev, ContextIdAbbvId,
F,
5087 CallStackPos, CallStackCount);
5092 for (
const GlobalVariable &
G :
M.globals())
5093 writeModuleLevelReferences(
G, NameVals, FSModRefsAbbrev,
5094 FSModVTableRefsAbbrev);
5096 for (
const GlobalAlias &
A :
M.aliases()) {
5097 auto *Aliasee =
A.getAliaseeObject();
5113 for (
auto &S :
Index->typeIdCompatibleVtableMap()) {
5117 TypeIdCompatibleVtableAbbrev);
5121 if (
Index->getBlockCount())
5123 ArrayRef<uint64_t>{
Index->getBlockCount()});
5128void ModuleBitcodeWriterBase::writeGUIDList() {
5130 const size_t Max = Vals.size();
5132 std::vector<GlobalValue::GUID> GUIDs(Max, 0);
5133 for (
const GlobalValue &GV :
M.global_values()) {
5134 auto MaybeGUID = GV.getGUIDIfAssigned();
5137 auto GUID = *MaybeGUID;
5140 GUIDs[ValueID] =
GUID;
5143 auto Abbv = std::make_shared<BitCodeAbbrev>();
5147 unsigned GUIDListAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5149 SmallVector<uint32_t> RecordVals;
5151 for (
auto GUID : GUIDs) {
5152 RecordVals.
push_back(
static_cast<uint32_t
>(GUID >> 32));
5153 RecordVals.
push_back(
static_cast<uint32_t
>(GUID));
5160void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
5169 auto Abbv = std::make_shared<BitCodeAbbrev>();
5175 unsigned ValueGuidAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5177 for (
const auto &GVI : valueIds()) {
5179 ArrayRef<uint32_t>{GVI.second,
5180 static_cast<uint32_t
>(GVI.first >> 32),
5181 static_cast<uint32_t
>(GVI.first)},
5187 if (!StackIds.empty()) {
5188 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
5195 unsigned StackIdAbbvId = Stream.
EmitAbbrev(std::move(StackIdAbbv));
5196 SmallVector<uint32_t> Vals;
5197 Vals.
reserve(StackIds.size() * 2);
5198 for (
auto Id : StackIds) {
5199 Vals.
push_back(
static_cast<uint32_t
>(Id >> 32));
5200 Vals.
push_back(
static_cast<uint32_t
>(Id));
5206 Abbv = std::make_shared<BitCodeAbbrev>();
5220 unsigned FSCallsProfileAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5223 Abbv = std::make_shared<BitCodeAbbrev>();
5230 unsigned FSModRefsAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5233 Abbv = std::make_shared<BitCodeAbbrev>();
5239 unsigned FSAliasAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5241 Abbv = std::make_shared<BitCodeAbbrev>();
5249 unsigned CallsiteAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5251 Abbv = std::make_shared<BitCodeAbbrev>();
5262 unsigned AllocAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5264 auto shouldImportValueAsDecl = [&](GlobalValueSummary *GVS) ->
bool {
5265 if (DecSummaries ==
nullptr)
5267 return DecSummaries->
count(GVS);
5275 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
5277 SmallVector<uint64_t, 64> NameVals;
5281 std::set<GlobalValue::GUID> ReferencedTypeIds;
5285 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
5295 NameVals.
push_back(S.getOriginalName());
5300 DenseMap<CallStackId, LinearCallStackId> CallStackPos;
5302 Abbv = std::make_shared<BitCodeAbbrev>();
5307 unsigned RadixAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5314 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks;
5315 forEachSummary([&](GVInfo
I,
bool IsAliasee) {
5321 GlobalValueSummary *S =
I.second;
5334 return StackIdIndicesToIndex[
I];
5340 if (!CallStacks.
empty()) {
5350 DenseSet<GlobalValue::GUID> DefOrUseGUIDs;
5351 forEachSummary([&](GVInfo
I,
bool IsAliasee) {
5352 GlobalValueSummary *S =
I.second;
5354 DefOrUseGUIDs.
insert(
I.first);
5355 for (
const ValueInfo &VI : S->
refs())
5356 DefOrUseGUIDs.
insert(
VI.getGUID());
5358 auto ValueId = getValueId(
I.first);
5360 SummaryToValueIdMap[S] = *ValueId;
5378 NameVals.
push_back(ModuleIdMap[
VS->modulePath()]);
5382 for (
auto &RI :
VS->refs()) {
5383 auto RefValueId = getValueId(RI.getGUID());
5393 MaybeEmitOriginalName(*S);
5397 auto GetValueId = [&](
const ValueInfo &
VI) -> std::optional<unsigned> {
5399 return std::nullopt;
5400 return getValueId(
VI.getGUID());
5409 NameVals.
push_back(ModuleIdMap[
FS->modulePath()]);
5422 unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;
5423 for (
auto &RI :
FS->refs()) {
5424 auto RefValueId = getValueId(RI.getGUID());
5428 if (RI.isReadOnly())
5430 else if (RI.isWriteOnly())
5434 NameVals[6] =
Count;
5435 NameVals[7] = RORefCnt;
5436 NameVals[8] = WORefCnt;
5438 for (
auto &EI :
FS->calls()) {
5441 std::optional<unsigned> CallValueId = GetValueId(EI.first);
5450 FSCallsProfileAbbrev);
5454 Stream, FS, CallsiteAbbrev, AllocAbbrev, 0,
5457 [&](
const ValueInfo &VI) ->
unsigned {
5458 std::optional<unsigned> ValueID = GetValueId(VI);
5473 return StackIdIndicesToIndex[
I];
5475 false, CallStackPos, CallStackCount);
5477 MaybeEmitOriginalName(*S);
5480 for (
auto *AS : Aliases) {
5481 auto AliasValueId = SummaryToValueIdMap[AS];
5490 auto AliaseeValueId =
5497 MaybeEmitOriginalName(*AS);
5505 auto EmitCfiFunctions = [&](
const CfiFunctionIndex &CfiIndex,
5507 if (CfiIndex.
empty())
5511 for (StringRef Name : Names)
5514 if (Functions.
empty())
5517 for (
const auto &Record : Functions) {
5532 for (
auto &
T : ReferencedTypeIds) {
5533 auto TidIter =
Index.typeIds().equal_range(
T);
5534 for (
const auto &[GUID, TypeIdPair] :
make_range(TidIter)) {
5542 if (
Index.getBlockCount())
5544 ArrayRef<uint64_t>{
Index.getBlockCount()});
5555 auto Abbv = std::make_shared<BitCodeAbbrev>();
5559 auto StringAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5561 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
5564 Abbv = std::make_shared<BitCodeAbbrev>();
5567 auto EpochAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5573void ModuleBitcodeWriter::writeModuleHash(StringRef View) {
5578 Hasher.
update(ArrayRef<uint8_t>(
5579 reinterpret_cast<const uint8_t *
>(
View.data()),
View.size()));
5580 std::array<uint8_t, 20> Hash = Hasher.
result();
5581 for (
int Pos = 0; Pos < 20; Pos += 4) {
5594void ModuleBitcodeWriter::write() {
5602 writeModuleVersion();
5611 writeAttributeGroupTable();
5614 writeAttributeTable();
5623 writeModuleConstants();
5626 writeModuleMetadataKinds();
5629 writeModuleMetadata();
5633 writeUseListBlock(
nullptr);
5635 writeOperandBundleTags();
5636 writeSyncScopeNames();
5639 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
5641 if (!
F.isDeclaration())
5642 writeFunction(
F, FunctionToBitcodeIndex);
5647 writePerModuleGlobalValueSummary();
5649 writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
5677 unsigned CPUType = ~0U;
5684 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
5685 DARWIN_CPU_TYPE_X86 = 7,
5686 DARWIN_CPU_TYPE_ARM = 12,
5687 DARWIN_CPU_TYPE_POWERPC = 18
5692 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
5694 CPUType = DARWIN_CPU_TYPE_X86;
5696 CPUType = DARWIN_CPU_TYPE_POWERPC;
5698 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
5700 CPUType = DARWIN_CPU_TYPE_ARM;
5704 "Expected header size to be reserved");
5709 unsigned Position = 0;
5717 while (Buffer.
size() & 15)
5724 Stream.
Emit((
unsigned)
'B', 8);
5725 Stream.
Emit((
unsigned)
'C', 8);
5726 Stream.
Emit(0x0, 4);
5727 Stream.
Emit(0xC, 4);
5728 Stream.
Emit(0xE, 4);
5729 Stream.
Emit(0xD, 4);
5747 auto Abbv = std::make_shared<BitCodeAbbrev>();
5750 auto AbbrevNo = Stream->
EmitAbbrev(std::move(Abbv));
5758 assert(!WroteStrtab && !WroteSymtab);
5764 if (M->getModuleInlineAsm().empty())
5768 const Triple TT(M->getTargetTriple());
5770 if (!
T || !
T->hasMCAsmParser())
5792 std::vector<char> Strtab;
5793 StrtabBuilder.finalizeInOrder();
5794 Strtab.resize(StrtabBuilder.getSize());
5795 StrtabBuilder.write((
uint8_t *)Strtab.data());
5798 {Strtab.data(), Strtab.size()});
5809 bool ShouldPreserveUseListOrder,
5818 assert(M.isMaterialized());
5819 Mods.push_back(
const_cast<Module *
>(&M));
5821 ModuleBitcodeWriter ModuleWriter(M, StrtabBuilder, *Stream,
5822 ShouldPreserveUseListOrder, Index,
5823 GenerateHash, ModHash);
5824 ModuleWriter.write();
5831 IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index, DecSummaries,
5832 ModuleToSummariesForIndex);
5833 IndexWriter.write();
5838 bool ShouldPreserveUseListOrder,
5842 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
5844 Writer.writeSymtab();
5845 Writer.writeStrtab();
5847 Triple TT(M.getTargetTriple());
5848 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) {
5859 Out.write(Buffer.
data(), Buffer.
size());
5866void IndexBitcodeWriter::write() {
5869 writeModuleVersion();
5875 writeCombinedGlobalValueSummary();
5892 Writer.
writeIndex(&Index, ModuleToSummariesForIndex, DecSummaries);
5895 Out.write((
char *)&Buffer.
front(), Buffer.
size());
5901class ThinLinkBitcodeWriter :
public ModuleBitcodeWriterBase {
5911 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
5913 ModHash(&ModHash) {}
5918 void writeSimplifiedModuleInfo();
5928void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
5940 auto Abbv = std::make_shared<BitCodeAbbrev>();
5943 Abbv->Add(AbbrevOpToUse);
5944 unsigned FilenameAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5946 for (
const auto P :
M.getSourceFileName())
6012void ThinLinkBitcodeWriter::write() {
6015 writeModuleVersion();
6017 writeSimplifiedModuleInfo();
6019 writePerModuleGlobalValueSummary();
6036 assert(M.isMaterialized());
6037 Mods.push_back(
const_cast<Module *
>(&M));
6039 ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
6041 ThinLinkWriter.write();
6058 Out.write((
char *)&Buffer.
front(), Buffer.
size());
6062 switch (
T.getObjectFormat()) {
6064 return "__LLVM,__bitcode";
6089 switch (
T.getObjectFormat()) {
6091 return "__LLVM,__cmdline";
6117 const std::vector<uint8_t> &CmdArgs) {
6122 Type *UsedElementType = Used ? Used->getValueType()->getArrayElementType()
6124 for (
auto *GV : UsedGlobals) {
6125 if (GV->getName() !=
"llvm.embedded.module" &&
6126 GV->getName() !=
"llvm.cmdline")
6131 Used->eraseFromParent();
6136 Triple T(M.getTargetTriple());
6165 M.getGlobalVariable(
"llvm.embedded.module",
true)) {
6166 assert(Old->hasZeroLiveUses() &&
6167 "llvm.embedded.module can only be used once in llvm.compiler.used");
6169 Old->eraseFromParent();
6171 GV->
setName(
"llvm.embedded.module");
6189 assert(Old->hasZeroLiveUses() &&
6190 "llvm.cmdline can only be used once in llvm.compiler.used");
6192 Old->eraseFromParent();
6198 if (UsedArray.
empty())
6206 NewUsed->setSection(
"llvm.metadata");
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void writeDIMacro(raw_ostream &Out, const DIMacro *N, AsmWriterContext &WriterCtx)
static void writeDIGlobalVariableExpression(raw_ostream &Out, const DIGlobalVariableExpression *N, AsmWriterContext &WriterCtx)
static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N, AsmWriterContext &WriterCtx)
static void writeDIFixedPointType(raw_ostream &Out, const DIFixedPointType *N, AsmWriterContext &WriterCtx)
static void writeDISubrangeType(raw_ostream &Out, const DISubrangeType *N, AsmWriterContext &WriterCtx)
static void writeDIStringType(raw_ostream &Out, const DIStringType *N, AsmWriterContext &WriterCtx)
static void writeDILayerLocList(raw_ostream &Out, const DILayerLocList *N, AsmWriterContext &WriterCtx)
static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N, AsmWriterContext &WriterCtx)
static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N, AsmWriterContext &WriterCtx)
static void writeDILayerLoc(raw_ostream &Out, const DILayerLoc *N, AsmWriterContext &WriterCtx)
static void writeDIModule(raw_ostream &Out, const DIModule *N, AsmWriterContext &WriterCtx)
static void writeDIFile(raw_ostream &Out, const DIFile *N, AsmWriterContext &)
static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N, AsmWriterContext &WriterCtx)
static void writeDILabel(raw_ostream &Out, const DILabel *N, AsmWriterContext &WriterCtx)
static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N, AsmWriterContext &WriterCtx)
static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N, AsmWriterContext &WriterCtx)
static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N, AsmWriterContext &WriterCtx)
static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N, AsmWriterContext &WriterCtx)
static void writeDILocation(raw_ostream &Out, const DILocation *DL, AsmWriterContext &WriterCtx)
static void writeDINamespace(raw_ostream &Out, const DINamespace *N, AsmWriterContext &WriterCtx)
static void writeDICommonBlock(raw_ostream &Out, const DICommonBlock *N, AsmWriterContext &WriterCtx)
static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N, AsmWriterContext &WriterCtx)
static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N, AsmWriterContext &WriterCtx)
static void writeDITemplateTypeParameter(raw_ostream &Out, const DITemplateTypeParameter *N, AsmWriterContext &WriterCtx)
static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N, AsmWriterContext &WriterCtx)
static void writeDIGenericSubrange(raw_ostream &Out, const DIGenericSubrange *N, AsmWriterContext &WriterCtx)
static void writeDISubrange(raw_ostream &Out, const DISubrange *N, AsmWriterContext &WriterCtx)
static void writeDIProperty(raw_ostream &Out, const DIProperty *N, AsmWriterContext &WriterCtx)
static void writeDILexicalBlockFile(raw_ostream &Out, const DILexicalBlockFile *N, AsmWriterContext &WriterCtx)
static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N, AsmWriterContext &)
static void writeMDTuple(raw_ostream &Out, const MDTuple *Node, AsmWriterContext &WriterCtx)
static void writeDIExpression(raw_ostream &Out, const DIExpression *N, AsmWriterContext &WriterCtx)
static void writeDIAssignID(raw_ostream &Out, const DIAssignID *DL, AsmWriterContext &WriterCtx)
static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N, AsmWriterContext &WriterCtx)
static void writeDIArgList(raw_ostream &Out, const DIArgList *N, AsmWriterContext &WriterCtx, bool FromValue=false)
static void writeDITemplateValueParameter(raw_ostream &Out, const DITemplateValueParameter *N, AsmWriterContext &WriterCtx)
static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N, AsmWriterContext &WriterCtx)
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
static void writeFunctionHeapProfileRecords(BitstreamWriter &Stream, FunctionSummary *FS, unsigned CallsiteAbbrev, unsigned AllocAbbrev, unsigned ContextIdAbbvId, bool PerModule, std::function< unsigned(const ValueInfo &VI)> GetValueID, std::function< unsigned(unsigned)> GetStackIndex, bool WriteContextSizeInfoIndex, DenseMap< CallStackId, LinearCallStackId > &CallStackPos, CallStackId &CallStackCount)
static unsigned serializeSanitizerMetadata(const GlobalValue::SanitizerMetadata &Meta)
static void writeTypeIdCompatibleVtableSummaryRecord(SmallVector< uint64_t, 64 > &NameVals, StringTableBuilder &StrtabBuilder, StringRef Id, const TypeIdCompatibleVtableInfo &Summary, ValueEnumerator &VE)
static void getReferencedTypeIds(FunctionSummary *FS, std::set< GlobalValue::GUID > &ReferencedTypeIds)
Collect type IDs from type tests used by function.
static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind)
static void collectMemProfCallStacks(FunctionSummary *FS, std::function< LinearFrameId(unsigned)> GetStackIndex, MapVector< CallStackId, llvm::SmallVector< LinearFrameId > > &CallStacks)
static unsigned getEncodedUnaryOpcode(unsigned Opcode)
static void emitSignedInt64(SmallVectorImpl< uint64_t > &Vals, uint64_t V)
static unsigned getEncodedVisibility(const GlobalValue &GV)
static uint64_t getOptimizationFlags(const Value *V)
static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage)
static cl::opt< bool > PreserveBitcodeUseListOrder("preserve-bc-uselistorder", cl::Hidden, cl::init(true), cl::desc("Preserve use-list order when writing LLVM bitcode."))
static unsigned getEncodedThreadLocalMode(const GlobalValue &GV)
static DenseMap< CallStackId, LinearCallStackId > writeMemoryProfileRadixTree(MapVector< CallStackId, llvm::SmallVector< LinearFrameId > > &&CallStacks, BitstreamWriter &Stream, unsigned RadixAbbrev)
static void writeIdentificationBlock(BitstreamWriter &Stream)
Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the current llvm version,...
static unsigned getEncodedCastOpcode(unsigned Opcode)
static cl::opt< uint32_t > FlushThreshold("bitcode-flush-threshold", cl::Hidden, cl::init(512), cl::desc("The threshold (unit M) for flushing LLVM bitcode."))
static unsigned getEncodedOrdering(AtomicOrdering Ordering)
static unsigned getEncodedUnnamedAddr(const GlobalValue &GV)
static unsigned getEncodedComdatSelectionKind(const Comdat &C)
static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags, bool ImportAsDecl=false)
static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl< char > &Buffer, const Triple &TT)
If generating a bc file on darwin, we have to emit a header and trailer to make it compatible with th...
static void writeBitcodeHeader(BitstreamWriter &Stream)
Helper to write the header common to all bitcode files.
static void writeWholeProgramDevirtResolutionByArg(SmallVector< uint64_t, 64 > &NameVals, const std::vector< uint64_t > &args, const WholeProgramDevirtResolution::ByArg &ByArg)
static void emitConstantRange(SmallVectorImpl< uint64_t > &Record, const ConstantRange &CR, bool EmitBitWidth)
static StringEncoding getStringEncoding(StringRef Str)
Determine the encoding to use for the given string name and length.
static uint64_t getEncodedGVarFlags(GlobalVarSummary::GVarFlags Flags)
static const char * getSectionNameForCommandline(const Triple &T)
static cl::opt< unsigned > IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25), cl::desc("Number of metadatas above which we emit an index " "to enable lazy-loading"))
static void writeTypeIdSummaryRecord(SmallVector< uint64_t, 64 > &NameVals, StringTableBuilder &StrtabBuilder, StringRef Id, const TypeIdSummary &Summary)
static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream, FunctionSummary *FS, Fn GetValueID)
Write the function type metadata related records that need to appear before a function summary entry ...
static uint64_t getEncodedHotnessCallEdgeInfo(const CalleeInfo &CI)
static void emitWideAPInt(SmallVectorImpl< uint64_t > &Vals, const APInt &A)
static void writeStringRecord(BitstreamWriter &Stream, unsigned Code, StringRef Str, unsigned AbbrevToUse)
static unsigned getEncodedRMWOperation(const AtomicRMWInst &I)
static void writeWholeProgramDevirtResolution(SmallVector< uint64_t, 64 > &NameVals, StringTableBuilder &StrtabBuilder, uint64_t Id, const WholeProgramDevirtResolution &Wpd)
static unsigned getEncodedDLLStorageClass(const GlobalValue &GV)
static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl< char > &Buffer, uint32_t &Position)
static const char * getSectionNameForBitcode(const Triple &T)
static cl::opt< bool > CombinedIndexMemProfContext("combined-index-memprof-context", cl::Hidden, cl::init(true), cl::desc(""))
static unsigned getEncodedBinaryOpcode(unsigned Opcode)
static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
static MaybeAlign getAlign(Value *Ptr)
Module.h This file contains the declarations for the Module class.
static cl::opt< LTOBitcodeEmbedding > EmbedBitcode("lto-embed-bitcode", cl::init(LTOBitcodeEmbedding::DoNotEmbed), cl::values(clEnumValN(LTOBitcodeEmbedding::DoNotEmbed, "none", "Do not embed"), clEnumValN(LTOBitcodeEmbedding::EmbedOptimized, "optimized", "Embed after all optimization passes"), clEnumValN(LTOBitcodeEmbedding::EmbedPostMergePreOptimized, "post-merge-pre-opt", "Embed post merge, but before optimizations")), cl::desc("Embed LLVM bitcode in object files produced by LTO"))
Machine Check Debug Module
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallString class.
This file defines the SmallVector class.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static const uint32_t IV[8]
Class for arbitrary precision integers.
unsigned getActiveWords() const
Compute the number of active words in the value of this APInt.
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
int64_t getSExtValue() const
Get sign extended value.
const GlobalValueSummary & getAliasee() const
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
bool isUsedWithInAlloca() const
Return true if this alloca is used as an inalloca argument to a call.
unsigned getAddressSpace() const
Return the address space for the allocation.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
bool empty() const
Check if the array is empty.
Class to represent array types.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
an instruction that atomically reads a memory location, combines it with another value,...
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
bool hasAttributes() const
Return true if attributes exists in this set.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
@ TombstoneKey
Use as Tombstone key for DenseMap of AttrKind.
@ None
No attributes have been set.
@ EmptyKey
Use as Empty key for DenseMap of AttrKind.
@ EndAttrKinds
Sentinel value useful for loops.
BitCodeAbbrevOp - This describes one or more operands in an abbreviation.
static bool isChar6(char C)
isChar6 - Return true if this character is legal in the Char6 encoding.
LLVM_ABI void writeThinLinkBitcode(const Module &M, const ModuleSummaryIndex &Index, const ModuleHash &ModHash)
Write the specified thin link bitcode file (i.e., the minimized bitcode file) to the buffer specified...
LLVM_ABI void writeIndex(const ModuleSummaryIndex *Index, const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex, const GVSummaryPtrSet *DecSummaries)
LLVM_ABI void copyStrtab(StringRef Strtab)
Copy the string table for another module into this bitcode file.
LLVM_ABI void writeStrtab()
Write the bitcode file's string table.
LLVM_ABI ~BitcodeWriter()
LLVM_ABI void writeSymtab()
Attempt to write a symbol table to the bitcode file.
LLVM_ABI void writeModule(const Module &M, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false, ModuleHash *ModHash=nullptr)
Write the specified module to the buffer specified at construction time.
LLVM_ABI BitcodeWriter(SmallVectorImpl< char > &Buffer)
Create a BitcodeWriter that writes to Buffer.
unsigned EmitAbbrev(std::shared_ptr< BitCodeAbbrev > Abbv)
Emits the abbreviation Abbv to the stream.
void markAndBlockFlushing()
For scenarios where the user wants to access a section of the stream to (for example) compute some ch...
StringRef getMarkedBufferAndResumeFlushing()
resumes flushing, but does not flush, and returns the section in the internal buffer starting from th...
void EmitRecord(unsigned Code, const Container &Vals, unsigned Abbrev=0)
EmitRecord - Emit the specified record to the stream, using an abbrev if we have one to compress the ...
void Emit(uint32_t Val, unsigned NumBits)
void EmitRecordWithBlob(unsigned Abbrev, const Container &Vals, StringRef Blob)
EmitRecordWithBlob - Emit the specified record to the stream, using an abbrev that includes a blob at...
unsigned EmitBlockInfoAbbrev(unsigned BlockID, std::shared_ptr< BitCodeAbbrev > Abbv)
EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified BlockID.
void EnterBlockInfoBlock()
EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
void BackpatchWord(uint64_t BitNo, unsigned Val)
void BackpatchWord64(uint64_t BitNo, uint64_t Val)
void EnterSubblock(unsigned BlockID, unsigned CodeLen)
uint64_t GetCurrentBitNo() const
Retrieve the current position in the stream, in bits.
void EmitRecordWithAbbrev(unsigned Abbrev, const Container &Vals)
EmitRecordWithAbbrev - Emit a record with the specified abbreviation.
static LLVM_ABI BlockAddress * lookup(const BasicBlock *BB)
Lookup an existing BlockAddress constant for the given BasicBlock.
OperandBundleUse getOperandBundleAt(unsigned Index) const
Return the operand bundle at a specific index.
unsigned getNumOperandBundles() const
Return the number of operand bundles associated with this User.
CallingConv::ID getCallingConv() const
Value * getCalledOperand() const
Value * getArgOperand(unsigned i) const
FunctionType * getFunctionType() const
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
bool hasOperandBundles() const
Return true if this User has any operand bundles.
BasicBlock * getIndirectDest(unsigned i) const
BasicBlock * getDefaultDest() const
unsigned getNumIndirectDests() const
Return the number of callbr indirect dest labels.
bool isNoTailCall() const
bool isMustTailCall() const
auto getNamesForGUID(GlobalValue::GUID GUID) const
get the name(s) associated with a given ThinLTO GUID.
@ Largest
The linker will choose the largest COMDAT.
@ SameSize
The data referenced by the COMDAT must be the same size.
@ Any
The linker may choose any COMDAT.
@ NoDeduplicate
No deduplication is performed.
@ ExactMatch
The data referenced by the COMDAT must be the same.
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
This class represents a range of values.
const APInt & getLower() const
Return the lower value for this range.
const APInt & getUpper() const
Return the upper value for this range.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
This is an important base class in LLVM.
DebugLoc getDebugLoc() const
LLVM_ABI DIAssignID * getAssignID() const
DIExpression * getExpression() const
DILocalVariable * getVariable() const
bool isDbgDeclareValue() const
Metadata * getRawLocation() const
Returns the metadata operand for the first location description.
bool isDbgDeclare() const
Metadata * getRawAddress() const
DIExpression * getAddressExpression() const
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Lightweight error class with error context and mandatory checking.
Function summary information to aid decisions and implementation of importing.
ForceSummaryHotnessType
Types for -force-summary-edges-cold debugging option.
LLVM_ABI void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
Appends all metadata attached to this value to MDs, sorting by KindID.
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
GVFlags flags() const
Get the flags for this GlobalValue (see struct GVFlags).
StringRef modulePath() const
Get the path to the module containing this function.
ArrayRef< ValueInfo > refs() const
Return the list of values referenced by this global value definition.
VisibilityTypes getVisibility() const
static bool isLocalLinkage(LinkageTypes Linkage)
LinkageTypes getLinkage() const
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
ThreadLocalMode getThreadLocalMode() const
@ DLLExportStorageClass
Function to be accessible from DLL.
@ DLLImportStorageClass
Function to be imported from DLL.
@ DefaultVisibility
The GV is visible.
@ HiddenVisibility
The GV is hidden.
@ ProtectedVisibility
The GV is protected.
UnnamedAddr getUnnamedAddr() const
LinkageTypes
An enumeration for the kinds of linkage for global values.
@ PrivateLinkage
Like Internal, but omit from symbol table.
@ CommonLinkage
Tentative definitions.
@ InternalLinkage
Rename collisions when linking (static functions).
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
@ WeakODRLinkage
Same, but only replaced by something equivalent.
@ ExternalLinkage
Externally visible function.
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
@ AppendingLinkage
Special purpose, only applies to global arrays.
@ AvailableExternallyLinkage
Available for inspection, not emission.
@ ExternalWeakLinkage
ExternalWeak linkage description.
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
DLLStorageClassTypes getDLLStorageClass() const
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
idx_iterator idx_end() const
idx_iterator idx_begin() const
bool isCleanup() const
Return 'true' if this landingpad instruction is a cleanup.
unsigned getNumClauses() const
Get the number of clauses for this landing pad.
bool isCatch(unsigned Idx) const
Return 'true' if the clause and index Idx is a catch clause.
Constant * getClause(unsigned Idx) const
Get the value of the clause at index Idx.
This class implements a map that also provides access to all stored values in a deterministic order.
size_t getBufferSize() const
const char * getBufferStart() const
const char * getBufferEnd() const
Class to hold module path string table and global value map, and encapsulate methods for operating on...
static constexpr uint64_t BitcodeSummaryVersion
A Module instance is used to store all the information related to an LLVM module.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Digest more data.
LLVM_ABI std::array< uint8_t, 20 > result()
Return the current raw 160-bits SHA1 for the digested data since the last call to init().
size_type size() const
Determine the number of elements in the SetVector.
bool empty() const
Determine if the SetVector is empty or not.
bool insert(const value_type &X)
Insert a new element into the SetVector.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void append(StringRef RHS)
Append from a StringRef.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
const ValueTy & getValue() const
Represent a constant reference to a string, i.e.
constexpr bool empty() const
Check if the string is empty.
constexpr size_t size() const
Get the string size.
Utility for building string tables with deduplicated suffixes.
LLVM_ABI size_t add(CachedHashStringRef S, uint8_t Priority=0)
Add a string to the builder.
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
The instances of the Type class are immutable: once they are created, they are never changed.
bool isX86_FP80Ty() const
Return true if this is x86 long double.
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
bool isFP128Ty() const
Return true if this is 'fp128'.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
std::vector< std::pair< const Value *, unsigned > > ValueList
unsigned getTypeID(Type *T) const
unsigned getMetadataID(const Metadata *MD) const
UseListOrderStack UseListOrders
ArrayRef< const Metadata * > getNonMDStrings() const
Get the non-MDString metadata for this block.
unsigned getInstructionID(const Instruction *I) const
unsigned getAttributeListID(AttributeList PAL) const
void incorporateFunction(const Function &F)
incorporateFunction/purgeFunction - If you'd like to deal with a function, use these two methods to g...
void getFunctionConstantRange(unsigned &Start, unsigned &End) const
getFunctionConstantRange - Return the range of values that corresponds to function-local constants.
unsigned getAttributeGroupID(IndexAndAttrSet Group) const
bool hasMDs() const
Check whether the current block has any metadata to emit.
unsigned getComdatID(const Comdat *C) const
uint64_t computeBitsRequiredForTypeIndices() const
unsigned getValueID(const Value *V) const
unsigned getMetadataOrNullID(const Metadata *MD) const
const std::vector< IndexAndAttrSet > & getAttributeGroups() const
const ValueList & getValues() const
unsigned getGlobalBasicBlockID(const BasicBlock *BB) const
getGlobalBasicBlockID - This returns the function-specific ID for the specified basic block.
void setInstructionID(const Instruction *I)
const std::vector< const BasicBlock * > & getBasicBlocks() const
const std::vector< AttributeList > & getAttributeLists() const
bool shouldPreserveUseListOrder() const
const ComdatSetType & getComdats() const
std::vector< Type * > TypeList
ArrayRef< const Metadata * > getMDStrings() const
Get the MDString metadata for this block.
std::pair< unsigned, AttributeSet > IndexAndAttrSet
Attribute groups as encoded in bitcode are almost AttributeSets, but they include the AttributeList i...
const TypeList & getTypes() const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
LLVMContext & getContext() const
All values hold a context through their type.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
std::pair< iterator, bool > insert(const ValueT &V)
void build(llvm::MapVector< CallStackId, llvm::SmallVector< FrameIdTy > > &&MemProfCallStackData, const llvm::DenseMap< FrameIdTy, LinearFrameId > *MemProfFrameIndexes, llvm::DenseMap< FrameIdTy, FrameStat > &FrameHistogram)
This class implements an extremely fast bulk output stream that can only output to a stream.
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
Predicate getPredicate(unsigned Condition, unsigned Hint)
Return predicate consisting of specified condition and hint bits.
@ CE
Windows NT (Windows on ARM)
@ TYPE_CODE_OPAQUE_POINTER
@ METADATA_TEMPLATE_VALUE
@ METADATA_LEXICAL_BLOCK_FILE
@ METADATA_SUBROUTINE_TYPE
@ METADATA_GLOBAL_DECL_ATTACHMENT
@ METADATA_IMPORTED_ENTITY
@ METADATA_GENERIC_SUBRANGE
@ METADATA_COMPOSITE_TYPE
@ METADATA_FIXED_POINT_TYPE
@ METADATA_GLOBAL_VAR_EXPR
GlobalValueSummarySymtabCodes
@ FS_CONTEXT_RADIX_TREE_ARRAY
@ FS_COMBINED_GLOBALVAR_INIT_REFS
@ FS_TYPE_CHECKED_LOAD_VCALLS
@ FS_COMBINED_ORIGINAL_NAME
@ FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_CONST_VCALL
@ FS_PERMODULE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_VCALLS
@ FS_COMBINED_ALLOC_INFO_NO_CONTEXT
@ FS_COMBINED_CALLSITE_INFO
@ FS_PERMODULE_CALLSITE_INFO
@ FS_PERMODULE_ALLOC_INFO
@ FS_TYPE_CHECKED_LOAD_CONST_VCALL
@ IDENTIFICATION_CODE_EPOCH
@ IDENTIFICATION_CODE_STRING
@ CST_CODE_DSO_LOCAL_EQUIVALENT
@ CST_CODE_CE_GEP_WITH_INRANGE
@ COMDAT_SELECTION_KIND_LARGEST
@ COMDAT_SELECTION_KIND_ANY
@ COMDAT_SELECTION_KIND_SAME_SIZE
@ COMDAT_SELECTION_KIND_EXACT_MATCH
@ COMDAT_SELECTION_KIND_NO_DUPLICATES
@ ATTR_KIND_STACK_PROTECT
@ ATTR_KIND_STACK_PROTECT_STRONG
@ ATTR_KIND_SANITIZE_MEMORY
@ ATTR_KIND_OPTIMIZE_FOR_SIZE
@ ATTR_KIND_FNRETTHUNK_EXTERN
@ ATTR_KIND_NO_DIVERGENCE_SOURCE
@ ATTR_KIND_SANITIZE_ADDRESS
@ ATTR_KIND_NO_IMPLICIT_FLOAT
@ ATTR_KIND_DEAD_ON_UNWIND
@ ATTR_KIND_STACK_ALIGNMENT
@ ATTR_KIND_STACK_PROTECT_REQ
@ ATTR_KIND_NULL_POINTER_IS_VALID
@ ATTR_KIND_SANITIZE_HWADDRESS
@ ATTR_KIND_RETURNS_TWICE
@ ATTR_KIND_SHADOWCALLSTACK
@ ATTR_KIND_OPT_FOR_FUZZING
@ ATTR_KIND_DENORMAL_FPENV
@ ATTR_KIND_SANITIZE_NUMERICAL_STABILITY
@ ATTR_KIND_ALLOCATED_POINTER
@ ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION
@ ATTR_KIND_CORO_ELIDE_SAFE
@ ATTR_KIND_NON_LAZY_BIND
@ ATTR_KIND_DEREFERENCEABLE
@ ATTR_KIND_OPTIMIZE_NONE
@ ATTR_KIND_HYBRID_PATCHABLE
@ ATTR_KIND_DEREFERENCEABLE_OR_NULL
@ ATTR_KIND_SANITIZE_REALTIME
@ ATTR_KIND_SPECULATIVE_LOAD_HARDENING
@ ATTR_KIND_ALWAYS_INLINE
@ ATTR_KIND_SANITIZE_TYPE
@ ATTR_KIND_PRESPLIT_COROUTINE
@ ATTR_KIND_SANITIZE_ALLOC_TOKEN
@ ATTR_KIND_NO_SANITIZE_COVERAGE
@ ATTR_KIND_NO_CREATE_UNDEF_OR_POISON
@ ATTR_KIND_DEAD_ON_RETURN
@ ATTR_KIND_SANITIZE_REALTIME_BLOCKING
@ ATTR_KIND_NO_SANITIZE_BOUNDS
@ ATTR_KIND_SANITIZE_MEMTAG
@ ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE
@ ATTR_KIND_SANITIZE_THREAD
@ ATTR_KIND_OPTIMIZE_FOR_DEBUGGING
@ SYNC_SCOPE_NAMES_BLOCK_ID
@ PARAMATTR_GROUP_BLOCK_ID
@ IDENTIFICATION_BLOCK_ID
@ GLOBALVAL_SUMMARY_BLOCK_ID
@ FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID
@ OPERAND_BUNDLE_TAGS_BLOCK_ID
@ MODULE_CODE_SOURCE_FILENAME
@ MODULE_CODE_SECTIONNAME
@ MODULE_CODE_ASM_PROPERTY
@ FUNC_CODE_INST_CATCHRET
@ FUNC_CODE_INST_LANDINGPAD
@ FUNC_CODE_INST_EXTRACTVAL
@ FUNC_CODE_INST_CATCHPAD
@ FUNC_CODE_INST_CATCHSWITCH
@ FUNC_CODE_INST_CLEANUPRET
@ FUNC_CODE_DEBUG_RECORD_VALUE
@ FUNC_CODE_INST_LOADATOMIC
@ FUNC_CODE_DEBUG_RECORD_ASSIGN
@ FUNC_CODE_INST_STOREATOMIC
@ FUNC_CODE_INST_BITEXTRACT
@ FUNC_CODE_INST_ATOMICRMW
@ FUNC_CODE_DEBUG_RECORD_DECLARE_VALUE
@ FUNC_CODE_DEBUG_LOC_AGAIN
@ FUNC_CODE_INST_EXTRACTELT
@ FUNC_CODE_INST_INDIRECTBR
@ FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE
@ FUNC_CODE_INST_INSERTVAL
@ FUNC_CODE_DECLAREBLOCKS
@ FUNC_CODE_DEBUG_RECORD_LABEL
@ FUNC_CODE_INST_INSERTELT
@ FUNC_CODE_BLOCKADDR_USERS
@ FUNC_CODE_INST_CLEANUPPAD
@ FUNC_CODE_INST_SHUFFLEVEC
@ FUNC_CODE_INST_UNREACHABLE
@ FUNC_CODE_INST_BITINSERT
@ FUNC_CODE_DEBUG_RECORD_DECLARE
@ FUNC_CODE_OPERAND_BUNDLE
@ FIRST_APPLICATION_ABBREV
@ PARAMATTR_GRP_CODE_ENTRY
initializer< Ty > init(const Ty &Val)
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
LLVM_ABI Error build(ArrayRef< Module * > Mods, SmallVector< char, 0 > &Symtab, StringTableBuilder &StrtabBuilder, BumpPtrAllocator &Alloc)
Fills in Symtab and StrtabBuilder with a valid symbol and string table for Mods.
llvm::unique_function< void(llvm::Expected< T >)> Callback
A Callback<T> is a void function that accepts Expected<T>.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract_or_null(Y &&MD)
Extract a Value from Metadata, allowing null.
LLVM_ABI bool metadataIncludesAllContextSizeInfo()
Whether the alloc memeprof metadata will include context size info for all MIBs.
template LLVM_ABI llvm::DenseMap< LinearFrameId, FrameStat > computeFrameHistogram< LinearFrameId >(llvm::MapVector< CallStackId, llvm::SmallVector< LinearFrameId > > &MemProfCallStackData)
LLVM_ABI bool metadataMayIncludeContextSizeInfo()
Whether the alloc memprof metadata may include context size info for some MIBs (but possibly not all)...
NodeAddr< CodeNode * > Code
void write32le(void *P, uint32_t V)
uint32_t read32be(const void *P)
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
StringMapEntry< Value * > ValueName
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
unsigned encode(MaybeAlign A)
Returns a representation of the alignment that encodes undefined as 0.
LLVM_ABI void WriteBitcodeToFile(const Module &M, raw_ostream &Out, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false, ModuleHash *ModHash=nullptr)
Write the specified module to the specified raw output stream.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
LLVM_ABI void writeThinLinkBitcodeToFile(const Module &M, raw_ostream &Out, const ModuleSummaryIndex &Index, const ModuleHash &ModHash)
Write the specified thin link bitcode file (i.e., the minimized bitcode file) to the given raw output...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI void writeIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out, const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex=nullptr, const GVSummaryPtrSet *DecSummaries=nullptr)
Write the specified module summary index to the given raw output stream, where it will be written in ...
LLVM_ABI void embedBitcodeInModule(Module &M, MemoryBufferRef Buf, bool EmbedBitcode, bool EmbedCmdline, const std::vector< uint8_t > &CmdArgs)
If EmbedBitcode is set, save a copy of the llvm IR as data in the __LLVM,__bitcode section (....
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
std::map< std::string, GVSummaryMapTy, std::less<> > ModuleToSummariesForIndexTy
Map of a module name to the GUIDs and summaries we will import from that module.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
AtomicOrdering
Atomic ordering for LLVM's memory model.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt copy(R &&Range, OutputIt Out)
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
bool isBitcode(const unsigned char *BufPtr, const unsigned char *BufEnd)
isBitcode - Return true if the given bytes are the magic bytes for LLVM IR bitcode,...
SmallPtrSet< GlobalValueSummary *, 0 > GVSummaryPtrSet
A set of global value summary pointers.
void consumeError(Error Err)
Consume a Error without doing anything.
LLVM_ABI Error write(DWPWriter &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue, Dwarf64StrOffsetsPromotion StrOffsetsOptValue, raw_pwrite_stream *OS=nullptr)
LLVM_ABI GlobalVariable * collectUsedGlobalVariables(const Module &M, SmallVectorImpl< GlobalValue * > &Vec, bool CompilerUsed)
Given "llvm.used" or "llvm.compiler.used" as a global name, collect the initializer elements of that ...
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
This struct is a compact representation of a valid (non-zero power of two) alignment.
static void set(StorageType &Packed, typename Bitfield::Type Value)
Sets the typed value in the provided Packed value.
Class to accumulate and hold information about a callee.
Flags specific to function summaries.
static constexpr uint32_t RangeWidth
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
static LLVM_ABI const Target * lookupTarget(const Triple &TheTriple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
Struct that holds a reference to a particular GUID in a global value summary.
uint64_t Info
Additional information for the resolution:
enum llvm::WholeProgramDevirtResolution::ByArg::Kind TheKind
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
std::string SingleImplName