33#include "llvm/Config/llvm-config.h"
95 cl::desc(
"Number of metadatas above which we emit an index "
96 "to enable lazy-loading"));
99 cl::desc(
"The threshold (unit M) for flushing LLVM bitcode."));
119 cl::desc(
"Preserve use-list order when writing LLVM bitcode."));
130 VST_BBENTRY_6_ABBREV,
134 CONSTANTS_INTEGER_ABBREV,
135 CONSTANTS_BYTE_ABBREV,
136 CONSTANTS_CE_CAST_Abbrev,
137 CONSTANTS_NULL_Abbrev,
141 FUNCTION_INST_STORE_ABBREV,
142 FUNCTION_INST_UNOP_ABBREV,
143 FUNCTION_INST_UNOP_FLAGS_ABBREV,
144 FUNCTION_INST_BINOP_ABBREV,
145 FUNCTION_INST_BINOP_FLAGS_ABBREV,
146 FUNCTION_INST_CAST_ABBREV,
147 FUNCTION_INST_CAST_FLAGS_ABBREV,
148 FUNCTION_INST_RET_VOID_ABBREV,
149 FUNCTION_INST_RET_VAL_ABBREV,
150 FUNCTION_INST_BR_UNCOND_ABBREV,
151 FUNCTION_INST_BR_COND_ABBREV,
152 FUNCTION_INST_UNREACHABLE_ABBREV,
153 FUNCTION_INST_GEP_ABBREV,
154 FUNCTION_INST_CMP_ABBREV,
155 FUNCTION_INST_CMP_FLAGS_ABBREV,
156 FUNCTION_DEBUG_RECORD_VALUE_ABBREV,
157 FUNCTION_DEBUG_LOC_ABBREV,
158 FUNCTION_DEBUG_LOC_LAYERS_ABBREV,
163class BitcodeWriterBase {
166 BitstreamWriter &Stream;
168 StringTableBuilder &StrtabBuilder;
173 BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
174 : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
177 void writeModuleVersion();
180void BitcodeWriterBase::writeModuleVersion() {
187class ModuleBitcodeWriterBase :
public BitcodeWriterBase {
196 const ModuleSummaryIndex *Index;
201 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
204 unsigned GlobalValueId;
213 ModuleBitcodeWriterBase(
const Module &M, StringTableBuilder &StrtabBuilder,
214 BitstreamWriter &Stream,
215 bool ShouldPreserveUseListOrder,
216 const ModuleSummaryIndex *Index)
217 : BitcodeWriterBase(Stream, StrtabBuilder),
M(
M),
220 : ShouldPreserveUseListOrder),
231 for (
const auto &GUIDSummaryLists :
232 Index->sortedGlobalValueSummariesRange())
234 for (
auto &Summary : GUIDSummaryLists.second.getSummaryList())
240 for (auto &CallEdge : FS->calls())
241 if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())
242 assignValueId(CallEdge.first.getGUID());
248 for (auto &RefEdge : FS->refs())
249 if (!RefEdge.haveGVs() || !RefEdge.getValue())
250 assignValueId(RefEdge.getGUID());
255 void writePerModuleGlobalValueSummary();
256 void writeGUIDList();
259 void writePerModuleFunctionSummaryRecord(
260 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
261 unsigned ValueID,
unsigned FSCallsProfileAbbrev,
unsigned CallsiteAbbrev,
262 unsigned AllocAbbrev,
unsigned ContextIdAbbvId,
const Function &
F,
263 DenseMap<CallStackId, LinearCallStackId> &CallStackPos,
265 void writeModuleLevelReferences(
const GlobalVariable &V,
266 SmallVector<uint64_t, 64> &NameVals,
267 unsigned FSModRefsAbbrev,
268 unsigned FSModVTableRefsAbbrev);
271 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
275 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
278 assert(VMI != GUIDToValueIdMap.end() &&
279 "GUID does not have assigned value Id");
284 unsigned getValueId(ValueInfo VI) {
285 if (!
VI.haveGVs() || !
VI.getValue())
286 return getValueId(
VI.getGUID());
290 std::map<GlobalValue::GUID, unsigned> &valueIds() {
return GUIDToValueIdMap; }
294class ModuleBitcodeWriter :
public ModuleBitcodeWriterBase {
310 unsigned DILocationLayersAbbrev = 0;
315 ModuleBitcodeWriter(
const Module &M, StringTableBuilder &StrtabBuilder,
316 BitstreamWriter &Stream,
bool ShouldPreserveUseListOrder,
317 const ModuleSummaryIndex *Index,
bool GenerateHash,
319 : ModuleBitcodeWriterBase(
M, StrtabBuilder, Stream,
320 ShouldPreserveUseListOrder,
Index),
321 GenerateHash(GenerateHash), ModHash(ModHash),
322 BitcodeStartBit(Stream.GetCurrentBitNo()) {}
328 uint64_t bitcodeStartBit() {
return BitcodeStartBit; }
330 size_t addToStrtab(StringRef Str);
332 void writeAttributeGroupTable();
333 void writeAttributeTable();
334 void writeTypeTable();
336 void writeValueSymbolTableForwardDecl();
337 void writeModuleInfo();
338 void writeValueAsMetadata(
const ValueAsMetadata *MD,
339 SmallVectorImpl<uint64_t> &Record);
340 void writeMDTuple(
const MDTuple *
N, SmallVectorImpl<uint64_t> &Record,
342 unsigned createDILocationAbbrev(
bool WithIRLayers);
343 void writeDILocation(
const DILocation *
N, SmallVectorImpl<uint64_t> &Record,
345 void writeDILayerLoc(
const DILayerLoc *
N, SmallVectorImpl<uint64_t> &Record,
348 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
349 unsigned createGenericDINodeAbbrev();
351 SmallVectorImpl<uint64_t> &Record,
unsigned &Abbrev);
352 void writeDISubrange(
const DISubrange *
N, SmallVectorImpl<uint64_t> &Record,
355 SmallVectorImpl<uint64_t> &Record,
358 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
362 SmallVectorImpl<uint64_t> &Record,
365 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
367 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
369 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
371 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
373 SmallVectorImpl<uint64_t> &Record,
375 void writeDIFile(
const DIFile *
N, SmallVectorImpl<uint64_t> &Record,
378 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
380 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
382 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
384 SmallVectorImpl<uint64_t> &Record,
387 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
390 void writeDIMacro(
const DIMacro *
N, SmallVectorImpl<uint64_t> &Record,
394 void writeDIArgList(
const DIArgList *
N, SmallVectorImpl<uint64_t> &Record);
395 void writeDIModule(
const DIModule *
N, SmallVectorImpl<uint64_t> &Record,
397 void writeDIAssignID(
const DIAssignID *
N, SmallVectorImpl<uint64_t> &Record,
400 SmallVectorImpl<uint64_t> &Record,
403 SmallVectorImpl<uint64_t> &Record,
406 SmallVectorImpl<uint64_t> &Record,
409 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
411 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
413 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
415 SmallVectorImpl<uint64_t> &Record,
418 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
419 void writeDIProperty(
const DIProperty *
N, SmallVectorImpl<uint64_t> &Record,
422 SmallVectorImpl<uint64_t> &Record,
424 unsigned createNamedMetadataAbbrev();
425 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
426 unsigned createMetadataStringsAbbrev();
428 SmallVectorImpl<uint64_t> &Record);
430 SmallVectorImpl<uint64_t> &Record,
431 std::vector<unsigned> *MDAbbrevs =
nullptr,
432 std::vector<uint64_t> *IndexPos =
nullptr);
433 void writeModuleMetadata();
434 void writeFunctionMetadata(
const Function &
F);
435 void writeFunctionMetadataAttachment(
const Function &
F);
436 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
437 const GlobalObject &GO);
438 void writeModuleMetadataKinds();
439 void writeOperandBundleTags();
440 void writeSyncScopeNames();
441 void writeConstants(
unsigned FirstVal,
unsigned LastVal,
bool isGlobal);
442 void writeModuleConstants();
443 bool pushValueAndType(
const Value *V,
unsigned InstID,
444 SmallVectorImpl<unsigned> &Vals);
445 bool pushValueOrMetadata(
const Value *V,
unsigned InstID,
446 SmallVectorImpl<unsigned> &Vals);
447 void writeOperandBundles(
const CallBase &CB,
unsigned InstID);
448 void pushValue(
const Value *V,
unsigned InstID,
449 SmallVectorImpl<unsigned> &Vals);
450 void pushValueSigned(
const Value *V,
unsigned InstID,
451 SmallVectorImpl<uint64_t> &Vals);
452 void writeInstruction(
const Instruction &
I,
unsigned InstID,
453 SmallVectorImpl<unsigned> &Vals);
454 void writeFunctionLevelValueSymbolTable(
const ValueSymbolTable &VST);
455 void writeGlobalValueSymbolTable(
456 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
457 void writeUseList(UseListOrder &&Order);
458 void writeUseListBlock(
const Function *
F);
461 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
462 void writeBlockInfo();
463 void writeModuleHash(StringRef View);
466 return unsigned(SSID);
469 unsigned getEncodedAlign(MaybeAlign Alignment) {
return encode(Alignment); }
473class IndexBitcodeWriter :
public BitcodeWriterBase {
475 const ModuleSummaryIndex &
Index;
491 SortedSummariesForIndex;
495 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
499 std::vector<uint64_t> StackIds;
504 DenseMap<unsigned, unsigned> StackIdIndicesToIndex;
507 unsigned GlobalValueId = 0;
511 DenseMap<StringRef, uint64_t> ModuleIdMap;
521 BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
522 const ModuleSummaryIndex &Index,
525 : BitcodeWriterBase(Stream, StrtabBuilder),
Index(
Index),
526 DecSummaries(DecSummaries),
527 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
528 if (ModuleToSummariesForIndex) {
529 for (
const auto &[ModPath, Summaries] : *ModuleToSummariesForIndex)
540 auto RecordStackIdReference = [&](
unsigned StackIdIndex) {
545 StackIdIndicesToIndex.
insert({StackIdIndex, StackIds.size()});
547 StackIds.push_back(
Index.getStackIdAtIndex(StackIdIndex));
554 forEachSummary([&](GVInfo
I,
bool IsAliasee) {
555 GUIDToValueIdMap[
I.first] = ++GlobalValueId;
567 for (
auto &CI :
FS->callsites()) {
578 if (CI.StackIdIndices.empty()) {
579 GUIDToValueIdMap[CI.Callee.getGUID()] = ++GlobalValueId;
582 for (
auto Idx : CI.StackIdIndices)
583 RecordStackIdReference(Idx);
586 for (
auto &AI :
FS->allocs())
587 for (
auto &MIB : AI.MIBs)
588 for (
auto Idx : MIB.StackIdIndices)
589 RecordStackIdReference(Idx);
595 using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
600 template<
typename Functor>
601 void forEachSummary(Functor Callback) {
602 if (ModuleToSummariesForIndex) {
603 for (
auto &[GUID, GVS] : SortedSummariesForIndex) {
609 Callback({AS->getAliaseeGUID(), &AS->getAliasee()},
true);
613 for (
const auto &Summaries :
Index.sortedGlobalValueSummariesRange())
614 for (
auto &Summary : Summaries.second.getSummaryList())
623 template <
typename Functor>
void forEachModule(Functor Callback) {
624 if (ModuleToSummariesForIndex) {
625 for (
const auto &M : *ModuleToSummariesForIndex) {
626 const auto &MPI =
Index.modulePaths().find(
M.first);
627 if (MPI ==
Index.modulePaths().end()) {
631 assert(ModuleToSummariesForIndex->size() == 1);
641 std::vector<StringRef> ModulePaths;
642 for (
auto &[ModPath,
_] :
Index.modulePaths())
643 ModulePaths.push_back(ModPath);
645 for (
auto &ModPath : ModulePaths)
654 void writeModStrings();
655 void writeCombinedGlobalValueSummary();
658 auto VMI = GUIDToValueIdMap.find(ValGUID);
659 if (VMI == GUIDToValueIdMap.end())
664 std::map<GlobalValue::GUID, unsigned> &valueIds() {
return GUIDToValueIdMap; }
699 case Instruction::Add:
701 case Instruction::Sub:
703 case Instruction::Mul:
706 case Instruction::FDiv:
709 case Instruction::FRem:
721 unsigned Encoding = 0;
722 switch (
I.getOperation()) {
795 if (
I.isElementwise())
830 case Attribute::Alignment:
832 case Attribute::AllocAlign:
834 case Attribute::AllocSize:
836 case Attribute::AlwaysInline:
838 case Attribute::Builtin:
840 case Attribute::ByVal:
842 case Attribute::Convergent:
844 case Attribute::InAlloca:
846 case Attribute::Cold:
848 case Attribute::DisableSanitizerInstrumentation:
850 case Attribute::FnRetThunkExtern:
852 case Attribute::Flatten:
856 case Attribute::ElementType:
858 case Attribute::HybridPatchable:
860 case Attribute::InlineHint:
862 case Attribute::InReg:
864 case Attribute::JumpTable:
866 case Attribute::MinSize:
868 case Attribute::AllocatedPointer:
870 case Attribute::AllocKind:
872 case Attribute::Memory:
874 case Attribute::NoFPClass:
876 case Attribute::Naked:
878 case Attribute::Nest:
880 case Attribute::NoAlias:
882 case Attribute::NoBuiltin:
884 case Attribute::NoCallback:
886 case Attribute::NoDivergenceSource:
888 case Attribute::NoDuplicate:
890 case Attribute::NoFree:
892 case Attribute::NoFreeObj:
894 case Attribute::NoImplicitFloat:
896 case Attribute::NoInline:
898 case Attribute::NoRecurse:
900 case Attribute::NoMerge:
902 case Attribute::NonLazyBind:
904 case Attribute::NonNull:
906 case Attribute::Dereferenceable:
908 case Attribute::DereferenceableOrNull:
910 case Attribute::NoRedZone:
912 case Attribute::NoReturn:
914 case Attribute::NoSync:
916 case Attribute::NoCfCheck:
918 case Attribute::NoProfile:
920 case Attribute::SkipProfile:
922 case Attribute::NoUnwind:
924 case Attribute::NoSanitizeBounds:
926 case Attribute::NoSanitizeCoverage:
928 case Attribute::NullPointerIsValid:
930 case Attribute::OptimizeForDebugging:
932 case Attribute::OptForFuzzing:
934 case Attribute::OptimizeForSize:
936 case Attribute::OptimizeNone:
938 case Attribute::ReadNone:
940 case Attribute::ReadOnly:
942 case Attribute::Returned:
944 case Attribute::ReturnsTwice:
946 case Attribute::SExt:
948 case Attribute::Speculatable:
950 case Attribute::StackAlignment:
952 case Attribute::StackProtect:
954 case Attribute::StackProtectReq:
956 case Attribute::StackProtectStrong:
958 case Attribute::SafeStack:
960 case Attribute::ShadowCallStack:
962 case Attribute::StrictFP:
964 case Attribute::StructRet:
966 case Attribute::SanitizeAddress:
968 case Attribute::SanitizeAllocToken:
970 case Attribute::SanitizeHWAddress:
972 case Attribute::SanitizeThread:
974 case Attribute::SanitizeConcurrency:
976 case Attribute::SanitizeType:
978 case Attribute::SanitizeMemory:
980 case Attribute::SanitizeNumericalStability:
982 case Attribute::SanitizeRealtime:
984 case Attribute::SanitizeRealtimeBlocking:
986 case Attribute::SpeculativeLoadHardening:
988 case Attribute::SwiftError:
990 case Attribute::SwiftSelf:
992 case Attribute::SwiftAsync:
994 case Attribute::UWTable:
996 case Attribute::VScaleRange:
998 case Attribute::WillReturn:
1000 case Attribute::WriteOnly:
1002 case Attribute::ZExt:
1004 case Attribute::ImmArg:
1006 case Attribute::SanitizeMemTag:
1008 case Attribute::Preallocated:
1010 case Attribute::NoUndef:
1012 case Attribute::ByRef:
1014 case Attribute::MustProgress:
1016 case Attribute::PresplitCoroutine:
1018 case Attribute::Writable:
1020 case Attribute::CoroDestroyOnlyWhenComplete:
1022 case Attribute::CoroElideSafe:
1024 case Attribute::DeadOnUnwind:
1026 case Attribute::Range:
1028 case Attribute::Initializes:
1030 case Attribute::NoExt:
1032 case Attribute::Captures:
1034 case Attribute::DeadOnReturn:
1036 case Attribute::NoCreateUndefOrPoison:
1038 case Attribute::DenormalFPEnv:
1040 case Attribute::NoOutline:
1042 case Attribute::NoIPA:
1057 if ((int64_t)V >= 0)
1068 unsigned NumWords =
A.getActiveWords();
1069 const uint64_t *RawData =
A.getRawData();
1070 for (
unsigned i = 0; i < NumWords; i++)
1090void ModuleBitcodeWriter::writeAttributeGroupTable() {
1091 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
1093 if (AttrGrps.empty())
return;
1097 SmallVector<uint64_t, 64>
Record;
1099 unsigned AttrListIndex = Pair.first;
1100 AttributeSet AS = Pair.second;
1102 Record.push_back(AttrListIndex);
1105 if (Attr.isEnumAttribute()) {
1108 }
else if (Attr.isIntAttribute()) {
1110 Attribute::AttrKind
Kind = Attr.getKindAsEnum();
1112 if (Kind == Attribute::Memory) {
1117 Record.push_back(Attr.getValueAsInt());
1119 }
else if (Attr.isStringAttribute()) {
1120 StringRef
Kind = Attr.getKindAsString();
1121 StringRef Val = Attr.getValueAsString();
1130 }
else if (Attr.isTypeAttribute()) {
1131 Type *Ty = Attr.getValueAsType();
1132 Record.push_back(Ty ? 6 : 5);
1136 }
else if (Attr.isConstantRangeAttribute()) {
1142 assert(Attr.isConstantRangeListAttribute());
1148 for (
auto &CR : Val)
1160void ModuleBitcodeWriter::writeAttributeTable() {
1162 if (
Attrs.empty())
return;
1166 SmallVector<uint64_t, 64>
Record;
1167 for (
const AttributeList &AL : Attrs) {
1168 for (
unsigned i :
AL.indexes()) {
1169 AttributeSet AS =
AL.getAttributes(i);
1182void ModuleBitcodeWriter::writeTypeTable() {
1186 SmallVector<uint64_t, 64> TypeVals;
1191 auto Abbv = std::make_shared<BitCodeAbbrev>();
1193 Abbv->Add(BitCodeAbbrevOp(0));
1194 unsigned OpaquePtrAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1197 Abbv = std::make_shared<BitCodeAbbrev>();
1202 unsigned FunctionAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1205 Abbv = std::make_shared<BitCodeAbbrev>();
1210 unsigned StructAnonAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1213 Abbv = std::make_shared<BitCodeAbbrev>();
1217 unsigned StructNameAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1220 Abbv = std::make_shared<BitCodeAbbrev>();
1225 unsigned StructNamedAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1228 Abbv = std::make_shared<BitCodeAbbrev>();
1232 unsigned ArrayAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1240 for (
Type *
T : TypeList) {
1241 int AbbrevToUse = 0;
1244 switch (
T->getTypeID()) {
1254 case Type::MetadataTyID:
1259 case Type::ByteTyID:
1264 case Type::IntegerTyID:
1269 case Type::PointerTyID: {
1276 AbbrevToUse = OpaquePtrAbbrev;
1279 case Type::FunctionTyID: {
1285 for (
unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
1287 AbbrevToUse = FunctionAbbrev;
1290 case Type::StructTyID: {
1295 for (
Type *ET :
ST->elements())
1298 if (
ST->isLiteral()) {
1300 AbbrevToUse = StructAnonAbbrev;
1302 if (
ST->isOpaque()) {
1306 AbbrevToUse = StructNamedAbbrev;
1310 if (!
ST->getName().empty())
1316 case Type::ArrayTyID: {
1320 TypeVals.
push_back(AT->getNumElements());
1322 AbbrevToUse = ArrayAbbrev;
1325 case Type::FixedVectorTyID:
1326 case Type::ScalableVectorTyID: {
1331 TypeVals.
push_back(VT->getElementCount().getKnownMinValue());
1337 case Type::TargetExtTyID: {
1343 for (
Type *InnerTy :
TET->type_params())
1348 case Type::TypedPointerTyID:
1353 Stream.
EmitRecord(Code, TypeVals, AbbrevToUse);
1394 RawFlags |= Flags.ReadNone;
1395 RawFlags |= (Flags.ReadOnly << 1);
1396 RawFlags |= (Flags.NoRecurse << 2);
1397 RawFlags |= (Flags.ReturnDoesNotAlias << 3);
1398 RawFlags |= (Flags.NoInline << 4);
1399 RawFlags |= (Flags.AlwaysInline << 5);
1400 RawFlags |= (Flags.NoUnwind << 6);
1401 RawFlags |= (Flags.MayThrow << 7);
1402 RawFlags |= (Flags.HasUnknownCall << 8);
1403 RawFlags |= (Flags.MustBeUnreachable << 9);
1410 bool ImportAsDecl =
false) {
1413 RawFlags |= Flags.NotEligibleToImport;
1414 RawFlags |= (Flags.Live << 1);
1415 RawFlags |= (Flags.DSOLocal << 2);
1416 RawFlags |= (Flags.CanAutoHide << 3);
1421 RawFlags = (RawFlags << 4) | Flags.Linkage;
1423 RawFlags |= (Flags.Visibility << 8);
1425 unsigned ImportType = Flags.ImportType | ImportAsDecl;
1426 RawFlags |= (ImportType << 10);
1428 RawFlags |= (Flags.NoRenameOnPromotion << 11);
1434 uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) |
1435 (Flags.Constant << 2) | Flags.VCallVisibility << 3;
1479 switch (
C.getSelectionKind()) {
1503size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1506 return StrtabBuilder.
add(Str);
1509void ModuleBitcodeWriter::writeComdats() {
1524void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
1529 auto Abbv = std::make_shared<BitCodeAbbrev>();
1535 unsigned VSTOffsetAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1551 bool isChar6 =
true;
1552 for (
char C : Str) {
1555 if ((
unsigned char)
C & 128)
1564static_assert(
sizeof(GlobalValue::SanitizerMetadata) <=
sizeof(unsigned),
1565 "Sanitizer Metadata is too large for naive serialization.");
1568 return Meta.NoAddress | (
Meta.NoHWAddress << 1) |
1569 (
Meta.Memtag << 2) | (
Meta.IsDynInit << 3);
1575void ModuleBitcodeWriter::writeModuleInfo() {
1577 if (!
M.getTargetTriple().empty())
1579 M.getTargetTriple().str(), 0 );
1580 const std::string &
DL =
M.getDataLayoutStr();
1584 for (
const Module::GlobalAsmFragment &Frag :
M.getModuleInlineAsm()) {
1586 Frag.Props.getAsStrings();
1599 std::map<std::string, unsigned> SectionMap;
1600 std::map<std::string, unsigned> GCMap;
1601 MaybeAlign MaxGVarAlignment;
1602 unsigned MaxGlobalType = 0;
1603 for (
const GlobalVariable &GV :
M.globals()) {
1604 if (MaybeAlign
A = GV.getAlign())
1605 MaxGVarAlignment = !MaxGVarAlignment ? *
A : std::max(*MaxGVarAlignment, *
A);
1606 MaxGlobalType = std::max(MaxGlobalType, VE.
getTypeID(GV.getValueType()));
1607 if (GV.hasSection()) {
1609 unsigned &
Entry = SectionMap[std::string(GV.getSection())];
1613 Entry = SectionMap.size();
1618 if (
F.hasSection()) {
1620 unsigned &
Entry = SectionMap[std::string(
F.getSection())];
1624 Entry = SectionMap.size();
1629 unsigned &
Entry = GCMap[
F.getGC()];
1633 Entry = GCMap.size();
1639 unsigned SimpleGVarAbbrev = 0;
1640 if (!
M.global_empty()) {
1642 auto Abbv = std::make_shared<BitCodeAbbrev>();
1653 if (!MaxGVarAlignment)
1654 Abbv->Add(BitCodeAbbrevOp(0));
1656 unsigned MaxEncAlignment = getEncodedAlign(MaxGVarAlignment);
1660 if (SectionMap.empty())
1661 Abbv->Add(BitCodeAbbrevOp(0));
1666 SimpleGVarAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1680 auto Abbv = std::make_shared<BitCodeAbbrev>();
1683 Abbv->Add(AbbrevOpToUse);
1684 unsigned FilenameAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1686 for (
const auto P :
M.getSourceFileName())
1697 for (
const GlobalVariable &GV :
M.globals()) {
1698 unsigned AbbrevToUse = 0;
1704 Vals.
push_back(addToStrtab(GV.getName()));
1707 Vals.
push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1711 Vals.
push_back(getEncodedAlign(GV.getAlign()));
1712 Vals.
push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]
1714 if (GV.isThreadLocal() ||
1716 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1717 GV.isExternallyInitialized() ||
1719 GV.hasComdat() || GV.hasAttributes() || GV.isDSOLocal() ||
1720 GV.hasPartition() || GV.hasSanitizerMetadata() || GV.getCodeModel()) {
1724 Vals.
push_back(GV.isExternallyInitialized());
1728 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1732 Vals.
push_back(addToStrtab(GV.getPartition()));
1733 Vals.
push_back(GV.getPartition().size());
1736 GV.getSanitizerMetadata())
1740 AbbrevToUse = SimpleGVarAbbrev;
1761 Vals.
push_back(getEncodedAlign(
F.getAlign()));
1762 Vals.
push_back(
F.hasSection() ? SectionMap[std::string(
F.getSection())]
1774 F.hasPersonalityFn() ? (VE.
getValueID(
F.getPersonalityFn()) + 1) : 0);
1778 Vals.
push_back(addToStrtab(
F.getPartition()));
1780 Vals.
push_back(getEncodedAlign(
F.getPreferredAlignment()));
1782 unsigned AbbrevToUse = 0;
1788 for (
const GlobalAlias &
A :
M.aliases()) {
1795 Vals.
push_back(
A.getType()->getAddressSpace());
1803 Vals.
push_back(addToStrtab(
A.getPartition()));
1806 unsigned AbbrevToUse = 0;
1812 for (
const GlobalIFunc &
I :
M.ifuncs()) {
1818 Vals.
push_back(
I.getType()->getAddressSpace());
1823 Vals.
push_back(addToStrtab(
I.getPartition()));
1829 writeValueSymbolTableForwardDecl();
1836 if (OBO->hasNoSignedWrap())
1838 if (OBO->hasNoUnsignedWrap())
1844 if (PDI->isDisjoint())
1847 if (FPMO->hasAllowReassoc())
1849 if (FPMO->hasNoNaNs())
1851 if (FPMO->hasNoInfs())
1853 if (FPMO->hasNoSignedZeros())
1855 if (FPMO->hasAllowReciprocal())
1857 if (FPMO->hasAllowContract())
1859 if (FPMO->hasApproxFunc())
1865 if (NNI->hasNonNeg())
1869 if (NNI->hasNonNeg())
1872 if (TI->hasNoSignedWrap())
1874 if (TI->hasNoUnsignedWrap())
1877 if (
GEP->isInBounds())
1879 if (
GEP->hasNoUnsignedSignedWrap())
1881 if (
GEP->hasNoUnsignedWrap())
1884 if (ICmp->hasSameSign())
1887 if (ASC->hasNonNull())
1894void ModuleBitcodeWriter::writeValueAsMetadata(
1895 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
1904void ModuleBitcodeWriter::writeMDTuple(
const MDTuple *
N,
1905 SmallVectorImpl<uint64_t> &Record,
1907 for (
const MDOperand &MDO :
N->operands()) {
1910 "Unexpected function-local metadata");
1919unsigned ModuleBitcodeWriter::createDILocationAbbrev(
bool WithIRLayers) {
1925 auto Abbv = std::make_shared<BitCodeAbbrev>();
1940void ModuleBitcodeWriter::writeDILocation(
const DILocation *
N,
1941 SmallVectorImpl<uint64_t> &Record,
1944 Abbrev = createDILocationAbbrev(
false);
1946 Record.push_back(
N->isDistinct());
1947 Record.push_back(
N->getLine());
1948 Record.push_back(
N->getColumn());
1951 Record.push_back(
N->isImplicitCode());
1952 Record.push_back(
N->getAtomGroup());
1953 Record.push_back(
N->getAtomRank());
1955 unsigned AbbrevToUse = Abbrev;
1956 if (DILayerLocList *IRLayers =
N->getIRLayers()) {
1957 if (!DILocationLayersAbbrev)
1958 DILocationLayersAbbrev = createDILocationAbbrev(
true);
1959 AbbrevToUse = DILocationLayersAbbrev;
1967void ModuleBitcodeWriter::writeDILayerLoc(
const DILayerLoc *
N,
1968 SmallVectorImpl<uint64_t> &Record,
1970 Record.push_back(
N->isDistinct());
1971 Record.push_back(
N->getLine());
1972 Record.push_back(
N->getColumn());
1979void ModuleBitcodeWriter::writeDILayerLocList(
const DILayerLocList *
N,
1980 SmallVectorImpl<uint64_t> &Record,
1982 Record.push_back(
N->isDistinct());
1983 for (
const MDOperand &
Op :
N->layers())
1989unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1992 auto Abbv = std::make_shared<BitCodeAbbrev>();
2003void ModuleBitcodeWriter::writeGenericDINode(
const GenericDINode *
N,
2004 SmallVectorImpl<uint64_t> &Record,
2007 Abbrev = createGenericDINodeAbbrev();
2009 Record.push_back(
N->isDistinct());
2010 Record.push_back(
N->getTag());
2013 for (
auto &
I :
N->operands())
2020void ModuleBitcodeWriter::writeDISubrange(
const DISubrange *
N,
2021 SmallVectorImpl<uint64_t> &Record,
2034void ModuleBitcodeWriter::writeDIGenericSubrange(
2035 const DIGenericSubrange *
N, SmallVectorImpl<uint64_t> &Record,
2047void ModuleBitcodeWriter::writeDIEnumerator(
const DIEnumerator *
N,
2048 SmallVectorImpl<uint64_t> &Record,
2051 Record.push_back(IsBigInt | (
N->isUnsigned() << 1) |
N->isDistinct());
2052 Record.push_back(
N->getValue().getBitWidth());
2060void ModuleBitcodeWriter::writeDIBasicType(
const DIBasicType *
N,
2061 SmallVectorImpl<uint64_t> &Record,
2063 const unsigned SizeIsMetadata = 0x2;
2064 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2065 Record.push_back(
N->getTag());
2068 Record.push_back(
N->getAlignInBits());
2069 Record.push_back(
N->getEncoding());
2070 Record.push_back(
N->getFlags());
2071 Record.push_back(
N->getNumExtraInhabitants());
2072 Record.push_back(
N->getDataSizeInBits());
2074 Record.push_back(
N->getLine());
2081void ModuleBitcodeWriter::writeDIFixedPointType(
2082 const DIFixedPointType *
N, SmallVectorImpl<uint64_t> &Record,
2084 const unsigned SizeIsMetadata = 0x2;
2085 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2086 Record.push_back(
N->getTag());
2089 Record.push_back(
N->getAlignInBits());
2090 Record.push_back(
N->getEncoding());
2091 Record.push_back(
N->getFlags());
2092 Record.push_back(
N->getKind());
2093 Record.push_back(
N->getFactorRaw());
2095 auto WriteWideInt = [&](
const APInt &
Value) {
2100 Record.push_back(Encoded);
2104 WriteWideInt(
N->getNumeratorRaw());
2105 WriteWideInt(
N->getDenominatorRaw());
2108 Record.push_back(
N->getLine());
2115void ModuleBitcodeWriter::writeDIStringType(
const DIStringType *
N,
2116 SmallVectorImpl<uint64_t> &Record,
2118 const unsigned SizeIsMetadata = 0x2;
2119 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2120 Record.push_back(
N->getTag());
2126 Record.push_back(
N->getAlignInBits());
2127 Record.push_back(
N->getEncoding());
2134void ModuleBitcodeWriter::writeDIDerivedType(
const DIDerivedType *
N,
2135 SmallVectorImpl<uint64_t> &Record,
2137 const unsigned SizeIsMetadata = 0x2;
2138 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2139 Record.push_back(
N->getTag());
2142 Record.push_back(
N->getLine());
2146 Record.push_back(
N->getAlignInBits());
2148 Record.push_back(
N->getFlags());
2153 if (
const auto &DWARFAddressSpace =
N->getDWARFAddressSpace())
2154 Record.push_back(*DWARFAddressSpace + 1);
2160 if (
auto PtrAuthData =
N->getPtrAuthData())
2161 Record.push_back(PtrAuthData->RawData);
2169void ModuleBitcodeWriter::writeDISubrangeType(
const DISubrangeType *
N,
2170 SmallVectorImpl<uint64_t> &Record,
2172 const unsigned SizeIsMetadata = 0x2;
2173 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2176 Record.push_back(
N->getLine());
2179 Record.push_back(
N->getAlignInBits());
2180 Record.push_back(
N->getFlags());
2191void ModuleBitcodeWriter::writeDICompositeType(
2192 const DICompositeType *
N, SmallVectorImpl<uint64_t> &Record,
2194 const unsigned IsNotUsedInOldTypeRef = 0x2;
2195 const unsigned SizeIsMetadata = 0x4;
2196 Record.push_back(SizeIsMetadata | IsNotUsedInOldTypeRef |
2197 (
unsigned)
N->isDistinct());
2198 Record.push_back(
N->getTag());
2201 Record.push_back(
N->getLine());
2205 Record.push_back(
N->getAlignInBits());
2207 Record.push_back(
N->getFlags());
2209 Record.push_back(
N->getRuntimeLang());
2219 Record.push_back(
N->getNumExtraInhabitants());
2229void ModuleBitcodeWriter::writeDISubroutineType(
2230 const DISubroutineType *
N, SmallVectorImpl<uint64_t> &Record,
2232 const unsigned HasNoOldTypeRefs = 0x2;
2233 Record.push_back(HasNoOldTypeRefs | (
unsigned)
N->isDistinct());
2234 Record.push_back(
N->getFlags());
2242void ModuleBitcodeWriter::writeDIFile(
const DIFile *
N,
2243 SmallVectorImpl<uint64_t> &Record,
2245 Record.push_back(
N->isDistinct());
2248 if (
N->getRawChecksum()) {
2249 Record.push_back(
N->getRawChecksum()->Kind);
2257 auto Source =
N->getRawSource();
2265void ModuleBitcodeWriter::writeDICompileUnit(
const DICompileUnit *
N,
2266 SmallVectorImpl<uint64_t> &Record,
2268 assert(
N->isDistinct() &&
"Expected distinct compile units");
2271 auto Lang =
N->getSourceLanguage();
2272 Record.push_back(Lang.getName());
2275 if (Lang.hasVersionedName())
2280 Record.push_back(
N->isOptimized());
2282 Record.push_back(
N->getRuntimeVersion());
2284 Record.push_back(
N->getEmissionKind());
2290 Record.push_back(
N->getDWOId());
2292 Record.push_back(
N->getSplitDebugInlining());
2293 Record.push_back(
N->getDebugInfoForProfiling());
2294 Record.push_back((
unsigned)
N->getNameTableKind());
2295 Record.push_back(
N->getRangesBaseAddress());
2298 Record.push_back(Lang.hasVersionedName() ? Lang.getVersion() : 0);
2299 Record.push_back(Lang.getDialect());
2305void ModuleBitcodeWriter::writeDISubprogram(
const DISubprogram *
N,
2306 SmallVectorImpl<uint64_t> &Record,
2308 const uint64_t HasUnitFlag = 1 << 1;
2309 const uint64_t HasSPFlagsFlag = 1 << 2;
2310 Record.push_back(
uint64_t(
N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
2315 Record.push_back(
N->getLine());
2317 Record.push_back(
N->getScopeLine());
2319 Record.push_back(
N->getSPFlags());
2320 Record.push_back(
N->getVirtualIndex());
2321 Record.push_back(
N->getFlags());
2326 Record.push_back(
N->getThisAdjustment());
2330 Record.push_back(
N->getKeyInstructionsEnabled());
2336void ModuleBitcodeWriter::writeDILexicalBlock(
const DILexicalBlock *
N,
2337 SmallVectorImpl<uint64_t> &Record,
2339 Record.push_back(
N->isDistinct());
2342 Record.push_back(
N->getLine());
2343 Record.push_back(
N->getColumn());
2349void ModuleBitcodeWriter::writeDILexicalBlockFile(
2350 const DILexicalBlockFile *
N, SmallVectorImpl<uint64_t> &Record,
2352 Record.push_back(
N->isDistinct());
2355 Record.push_back(
N->getDiscriminator());
2361void ModuleBitcodeWriter::writeDICommonBlock(
const DICommonBlock *
N,
2362 SmallVectorImpl<uint64_t> &Record,
2364 Record.push_back(
N->isDistinct());
2369 Record.push_back(
N->getLineNo());
2375void ModuleBitcodeWriter::writeDINamespace(
const DINamespace *
N,
2376 SmallVectorImpl<uint64_t> &Record,
2378 Record.push_back(
N->isDistinct() |
N->getExportSymbols() << 1);
2386void ModuleBitcodeWriter::writeDIMacro(
const DIMacro *
N,
2387 SmallVectorImpl<uint64_t> &Record,
2389 Record.push_back(
N->isDistinct());
2390 Record.push_back(
N->getMacinfoType());
2391 Record.push_back(
N->getLine());
2399void ModuleBitcodeWriter::writeDIMacroFile(
const DIMacroFile *
N,
2400 SmallVectorImpl<uint64_t> &Record,
2402 Record.push_back(
N->isDistinct());
2403 Record.push_back(
N->getMacinfoType());
2404 Record.push_back(
N->getLine());
2412void ModuleBitcodeWriter::writeDIArgList(
const DIArgList *
N,
2413 SmallVectorImpl<uint64_t> &Record) {
2414 Record.reserve(
N->getArgs().size());
2415 for (ValueAsMetadata *MD :
N->getArgs())
2422void ModuleBitcodeWriter::writeDIModule(
const DIModule *
N,
2423 SmallVectorImpl<uint64_t> &Record,
2425 Record.push_back(
N->isDistinct());
2426 for (
auto &
I :
N->operands())
2428 Record.push_back(
N->getLineNo());
2429 Record.push_back(
N->getIsDecl());
2435void ModuleBitcodeWriter::writeDIAssignID(
const DIAssignID *
N,
2436 SmallVectorImpl<uint64_t> &Record,
2439 Record.push_back(
N->isDistinct());
2444void ModuleBitcodeWriter::writeDITemplateTypeParameter(
2445 const DITemplateTypeParameter *
N, SmallVectorImpl<uint64_t> &Record,
2447 Record.push_back(
N->isDistinct());
2450 Record.push_back(
N->isDefault());
2456void ModuleBitcodeWriter::writeDITemplateValueParameter(
2457 const DITemplateValueParameter *
N, SmallVectorImpl<uint64_t> &Record,
2459 Record.push_back(
N->isDistinct());
2460 Record.push_back(
N->getTag());
2463 Record.push_back(
N->isDefault());
2470void ModuleBitcodeWriter::writeDIGlobalVariable(
2471 const DIGlobalVariable *
N, SmallVectorImpl<uint64_t> &Record,
2479 Record.push_back(
N->getLine());
2481 Record.push_back(
N->isLocalToUnit());
2482 Record.push_back(
N->isDefinition());
2485 Record.push_back(
N->getAlignInBits());
2492void ModuleBitcodeWriter::writeDILocalVariable(
2493 const DILocalVariable *
N, SmallVectorImpl<uint64_t> &Record,
2508 const uint64_t HasAlignmentFlag = 1 << 1;
2513 Record.push_back(
N->getLine());
2515 Record.push_back(
N->getArg());
2516 Record.push_back(
N->getFlags());
2517 Record.push_back(
N->getAlignInBits());
2524void ModuleBitcodeWriter::writeDILabel(
2525 const DILabel *
N, SmallVectorImpl<uint64_t> &Record,
2532 Record.push_back(
N->getLine());
2533 Record.push_back(
N->getColumn());
2534 Record.push_back(
N->getCoroSuspendIdx().has_value()
2535 ? (
uint64_t)
N->getCoroSuspendIdx().value()
2536 : std::numeric_limits<uint64_t>::max());
2542void ModuleBitcodeWriter::writeDIExpression(
const DIExpression *
N,
2543 SmallVectorImpl<uint64_t> &Record,
2545 Record.reserve(
N->getElements().size() + 1);
2548 Record.append(
N->elements_begin(),
N->elements_end());
2554void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
2555 const DIGlobalVariableExpression *
N, SmallVectorImpl<uint64_t> &Record,
2557 Record.push_back(
N->isDistinct());
2565void ModuleBitcodeWriter::writeDIObjCProperty(
const DIObjCProperty *
N,
2566 SmallVectorImpl<uint64_t> &Record,
2568 Record.push_back(
N->isDistinct());
2571 Record.push_back(
N->getLine());
2574 Record.push_back(
N->getAttributes());
2581void ModuleBitcodeWriter::writeDIProperty(
const DIProperty *
N,
2582 SmallVectorImpl<uint64_t> &Record,
2584 Record.push_back(
N->isDistinct());
2587 Record.push_back(
N->getLine());
2595void ModuleBitcodeWriter::writeDIImportedEntity(
2596 const DIImportedEntity *
N, SmallVectorImpl<uint64_t> &Record,
2598 Record.push_back(
N->isDistinct());
2599 Record.push_back(
N->getTag());
2602 Record.push_back(
N->getLine());
2611unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
2612 auto Abbv = std::make_shared<BitCodeAbbrev>();
2619void ModuleBitcodeWriter::writeNamedMetadata(
2620 SmallVectorImpl<uint64_t> &Record) {
2621 if (
M.named_metadata_empty())
2624 unsigned Abbrev = createNamedMetadataAbbrev();
2625 for (
const NamedMDNode &NMD :
M.named_metadata()) {
2627 StringRef Str = NMD.getName();
2628 Record.append(Str.bytes_begin(), Str.bytes_end());
2633 for (
const MDNode *
N : NMD.operands())
2640unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
2641 auto Abbv = std::make_shared<BitCodeAbbrev>();
2653void ModuleBitcodeWriter::writeMetadataStrings(
2655 if (Strings.
empty())
2663 SmallString<256> Blob;
2665 BitstreamWriter
W(Blob);
2685#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
2686#include "llvm/IR/Metadata.def"
2690void ModuleBitcodeWriter::writeMetadataRecords(
2692 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
2697#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
2698#include "llvm/IR/Metadata.def"
2704 assert(
N->isResolved() &&
"Expected forward references to be resolved");
2706 switch (
N->getMetadataID()) {
2709#define HANDLE_MDNODE_LEAF(CLASS) \
2710 case Metadata::CLASS##Kind: \
2712 write##CLASS(cast<CLASS>(N), Record, \
2713 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
2715 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
2717#include "llvm/IR/Metadata.def"
2728void ModuleBitcodeWriter::writeModuleMetadata() {
2729 if (!VE.
hasMDs() &&
M.named_metadata_empty())
2733 SmallVector<uint64_t, 64>
Record;
2737 std::vector<unsigned> MDAbbrevs;
2740 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] =
2741 createDILocationAbbrev(
false);
2742 DILocationLayersAbbrev = createDILocationAbbrev(
true);
2743 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
2744 createGenericDINodeAbbrev();
2746 auto Abbv = std::make_shared<BitCodeAbbrev>();
2750 unsigned OffsetAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
2752 Abbv = std::make_shared<BitCodeAbbrev>();
2756 unsigned IndexAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
2778 std::vector<uint64_t> IndexPos;
2782 writeMetadataRecords(VE.
getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2793 uint64_t PreviousValue = IndexOffsetRecordBitPos;
2794 for (
auto &Elt : IndexPos) {
2795 auto EltDelta = Elt - PreviousValue;
2796 PreviousValue = Elt;
2805 writeNamedMetadata(Record);
2807 auto AddDeclAttachedMetadata = [&](
const GlobalObject &GO) {
2808 SmallVector<uint64_t, 4>
Record;
2810 pushGlobalMetadataAttachment(Record, GO);
2814 if (
F.isDeclaration() &&
F.hasMetadata())
2815 AddDeclAttachedMetadata(
F);
2816 for (
const GlobalIFunc &GI :
M.ifuncs())
2817 if (GI.hasMetadata())
2818 AddDeclAttachedMetadata(GI);
2821 for (
const GlobalVariable &GV :
M.globals())
2822 if (GV.hasMetadata())
2823 AddDeclAttachedMetadata(GV);
2828void ModuleBitcodeWriter::writeFunctionMetadata(
const Function &
F) {
2835 DILocationLayersAbbrev = 0;
2836 SmallVector<uint64_t, 64>
Record;
2842void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2843 SmallVectorImpl<uint64_t> &Record,
const GlobalObject &GO) {
2847 for (
const auto &
I : MDs) {
2853void ModuleBitcodeWriter::writeFunctionMetadataAttachment(
const Function &
F) {
2856 SmallVector<uint64_t, 64>
Record;
2858 if (
F.hasMetadata()) {
2859 pushGlobalMetadataAttachment(Record,
F);
2867 for (
const BasicBlock &BB :
F)
2868 for (
const Instruction &
I : BB) {
2870 I.getAllMetadataOtherThanDebugLoc(MDs);
2873 if (MDs.
empty())
continue;
2877 for (
const auto &[ID, MD] : MDs) {
2888void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2889 SmallVector<uint64_t, 64>
Record;
2894 M.getMDKindNames(Names);
2896 if (Names.
empty())
return;
2900 for (
unsigned MDKindID = 0, e = Names.
size(); MDKindID != e; ++MDKindID) {
2901 Record.push_back(MDKindID);
2902 StringRef KName = Names[MDKindID];
2912void ModuleBitcodeWriter::writeOperandBundleTags() {
2920 M.getOperandBundleTags(Tags);
2927 SmallVector<uint64_t, 64>
Record;
2929 for (
auto Tag : Tags) {
2939void ModuleBitcodeWriter::writeSyncScopeNames() {
2941 M.getContext().getSyncScopeNames(SSNs);
2947 SmallVector<uint64_t, 64>
Record;
2948 for (
auto SSN : SSNs) {
2949 Record.append(SSN.begin(), SSN.end());
2957void ModuleBitcodeWriter::writeConstants(
unsigned FirstVal,
unsigned LastVal,
2959 if (FirstVal == LastVal)
return;
2963 unsigned AggregateAbbrev = 0;
2964 unsigned String8Abbrev = 0;
2965 unsigned CString7Abbrev = 0;
2966 unsigned CString6Abbrev = 0;
2970 auto Abbv = std::make_shared<BitCodeAbbrev>();
2974 AggregateAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
2977 Abbv = std::make_shared<BitCodeAbbrev>();
2981 String8Abbrev = Stream.
EmitAbbrev(std::move(Abbv));
2983 Abbv = std::make_shared<BitCodeAbbrev>();
2987 CString7Abbrev = Stream.
EmitAbbrev(std::move(Abbv));
2989 Abbv = std::make_shared<BitCodeAbbrev>();
2993 CString6Abbrev = Stream.
EmitAbbrev(std::move(Abbv));
2996 SmallVector<uint64_t, 64>
Record;
2999 Type *LastTy =
nullptr;
3000 for (
unsigned i = FirstVal; i != LastVal; ++i) {
3001 const Value *
V = Vals[i].first;
3003 if (
V->getType() != LastTy) {
3004 LastTy =
V->getType();
3007 CONSTANTS_SETTYPE_ABBREV);
3014 unsigned(
IA->hasSideEffects()) |
unsigned(
IA->isAlignStack()) << 1 |
3015 unsigned(
IA->getDialect() & 1) << 2 |
unsigned(
IA->canThrow()) << 3);
3018 StringRef AsmStr =
IA->getAsmString();
3023 StringRef ConstraintStr =
IA->getConstraintString();
3031 unsigned Code = -1U;
3032 unsigned AbbrevToUse = 0;
3033 if (
C->isNullValue()) {
3040 if (
IV->getBitWidth() <= 64) {
3044 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
3050 if (BV->getBitWidth() <= 64) {
3054 AbbrevToUse = CONSTANTS_BYTE_ABBREV;
3064 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
3068 APInt api = CFP->getValueAPF().bitcastToAPInt();
3070 Record.push_back((p[1] << 48) | (p[0] >> 16));
3071 Record.push_back(p[0] & 0xffffLL);
3073 APInt api = CFP->getValueAPF().bitcastToAPInt();
3078 assert(0 &&
"Unknown FP type!");
3084 uint64_t NumElts = Str->getNumElements();
3086 if (Str->isCString()) {
3091 AbbrevToUse = String8Abbrev;
3095 for (
uint64_t i = 0; i != NumElts; ++i) {
3096 unsigned char V = Str->getElementAsInteger(i);
3098 isCStr7 &= (
V & 128) == 0;
3104 AbbrevToUse = CString6Abbrev;
3106 AbbrevToUse = CString7Abbrev;
3107 }
else if (
const ConstantDataSequential *CDS =
3110 Type *EltTy = CDS->getElementType();
3112 for (
uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i)
3113 Record.push_back(CDS->getElementAsInteger(i));
3115 for (
uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i)
3117 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
3121 for (
const Value *
Op :
C->operands())
3123 AbbrevToUse = AggregateAbbrev;
3125 switch (
CE->getOpcode()) {
3132 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
3134 assert(
CE->getNumOperands() == 2 &&
"Unknown constant expr!");
3144 case Instruction::GetElementPtr: {
3149 if (std::optional<ConstantRange>
Range = GO->getInRange()) {
3153 for (
const Value *
Op :
CE->operands()) {
3159 case Instruction::ExtractElement:
3166 case Instruction::InsertElement:
3173 case Instruction::ShuffleVector:
3178 if (
C->getType() ==
C->getOperand(0)->getType()) {
3215 Stream.
EmitRecord(Code, Record, AbbrevToUse);
3222void ModuleBitcodeWriter::writeModuleConstants() {
3227 for (
unsigned i = 0, e = Vals.size(); i != e; ++i) {
3229 writeConstants(i, Vals.size(),
true);
3243bool ModuleBitcodeWriter::pushValueAndType(
const Value *V,
unsigned InstID,
3244 SmallVectorImpl<unsigned> &Vals) {
3248 if (ValID >= InstID) {
3255bool ModuleBitcodeWriter::pushValueOrMetadata(
const Value *V,
unsigned InstID,
3256 SmallVectorImpl<unsigned> &Vals) {
3257 bool IsMetadata =
V->getType()->isMetadataTy();
3265 return pushValueAndType(V, InstID, Vals);
3268void ModuleBitcodeWriter::writeOperandBundles(
const CallBase &CS,
3275 Record.push_back(
C.getOperandBundleTagID(Bundle.getTagName()));
3277 for (
auto &Input : Bundle.Inputs)
3278 pushValueOrMetadata(Input, InstID, Record);
3287void ModuleBitcodeWriter::pushValue(
const Value *V,
unsigned InstID,
3288 SmallVectorImpl<unsigned> &Vals) {
3293void ModuleBitcodeWriter::pushValueSigned(
const Value *V,
unsigned InstID,
3294 SmallVectorImpl<uint64_t> &Vals) {
3296 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
3301void ModuleBitcodeWriter::writeInstruction(
const Instruction &
I,
3303 SmallVectorImpl<unsigned> &Vals) {
3305 unsigned AbbrevToUse = 0;
3307 switch (
I.getOpcode()) {
3311 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3312 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
3317 if (AbbrevToUse == FUNCTION_INST_CAST_ABBREV)
3318 AbbrevToUse = FUNCTION_INST_CAST_FLAGS_ABBREV;
3324 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3325 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
3326 pushValue(
I.getOperand(1), InstID, Vals);
3330 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
3331 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
3336 case Instruction::FNeg: {
3338 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3339 AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
3343 if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
3344 AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
3349 case Instruction::GetElementPtr: {
3351 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
3355 for (
const Value *
Op :
I.operands())
3356 pushValueAndType(
Op, InstID, Vals);
3359 case Instruction::ExtractValue: {
3361 pushValueAndType(
I.getOperand(0), InstID, Vals);
3366 case Instruction::InsertValue: {
3368 pushValueAndType(
I.getOperand(0), InstID, Vals);
3369 pushValueAndType(
I.getOperand(1), InstID, Vals);
3374 case Instruction::Select: {
3376 pushValueAndType(
I.getOperand(1), InstID, Vals);
3377 pushValue(
I.getOperand(2), InstID, Vals);
3378 pushValueAndType(
I.getOperand(0), InstID, Vals);
3384 case Instruction::ExtractElement:
3386 pushValueAndType(
I.getOperand(0), InstID, Vals);
3387 pushValueAndType(
I.getOperand(1), InstID, Vals);
3389 case Instruction::InsertElement:
3391 pushValueAndType(
I.getOperand(0), InstID, Vals);
3392 pushValue(
I.getOperand(1), InstID, Vals);
3393 pushValueAndType(
I.getOperand(2), InstID, Vals);
3395 case Instruction::BitExtract:
3398 pushValueAndType(
I.getOperand(0), InstID, Vals);
3399 pushValueAndType(
I.getOperand(1), InstID, Vals);
3401 case Instruction::BitInsert:
3403 pushValueAndType(
I.getOperand(0), InstID, Vals);
3404 pushValueAndType(
I.getOperand(1), InstID, Vals);
3405 pushValueAndType(
I.getOperand(2), InstID, Vals);
3407 case Instruction::ShuffleVector:
3409 pushValueAndType(
I.getOperand(0), InstID, Vals);
3410 pushValue(
I.getOperand(1), InstID, Vals);
3414 case Instruction::ICmp:
3415 case Instruction::FCmp: {
3418 AbbrevToUse = FUNCTION_INST_CMP_ABBREV;
3419 if (pushValueAndType(
I.getOperand(0), InstID, Vals))
3421 pushValue(
I.getOperand(1), InstID, Vals);
3427 AbbrevToUse = FUNCTION_INST_CMP_FLAGS_ABBREV;
3432 case Instruction::Ret:
3435 unsigned NumOperands =
I.getNumOperands();
3436 if (NumOperands == 0)
3437 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
3438 else if (NumOperands == 1) {
3439 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3440 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
3442 for (
const Value *
Op :
I.operands())
3443 pushValueAndType(
Op, InstID, Vals);
3447 case Instruction::UncondBr: {
3449 AbbrevToUse = FUNCTION_INST_BR_UNCOND_ABBREV;
3453 case Instruction::CondBr: {
3455 AbbrevToUse = FUNCTION_INST_BR_COND_ABBREV;
3459 pushValue(
II.getCondition(), InstID, Vals);
3461 case Instruction::Switch:
3466 pushValue(
SI.getCondition(), InstID, Vals);
3468 for (
auto Case :
SI.cases()) {
3474 case Instruction::IndirectBr:
3478 pushValue(
I.getOperand(0), InstID, Vals);
3483 case Instruction::Invoke: {
3486 FunctionType *FTy =
II->getFunctionType();
3488 if (
II->hasOperandBundles())
3489 writeOperandBundles(*
II, InstID);
3498 pushValueAndType(Callee, InstID, Vals);
3501 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3502 pushValue(
I.getOperand(i), InstID, Vals);
3505 if (FTy->isVarArg()) {
3506 for (
unsigned i = FTy->getNumParams(), e =
II->arg_size(); i != e; ++i)
3507 pushValueAndType(
I.getOperand(i), InstID, Vals);
3511 case Instruction::Resume:
3513 pushValueAndType(
I.getOperand(0), InstID, Vals);
3515 case Instruction::CleanupRet: {
3518 pushValue(CRI.getCleanupPad(), InstID, Vals);
3519 if (CRI.hasUnwindDest())
3523 case Instruction::CatchRet: {
3526 pushValue(CRI.getCatchPad(), InstID, Vals);
3530 case Instruction::CleanupPad:
3531 case Instruction::CatchPad: {
3535 pushValue(FuncletPad.getParentPad(), InstID, Vals);
3537 unsigned NumArgOperands = FuncletPad.arg_size();
3539 for (
unsigned Op = 0;
Op != NumArgOperands; ++
Op)
3540 pushValueAndType(FuncletPad.getArgOperand(
Op), InstID, Vals);
3543 case Instruction::CatchSwitch: {
3547 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
3549 unsigned NumHandlers = CatchSwitch.getNumHandlers();
3551 for (
const BasicBlock *CatchPadBB : CatchSwitch.handlers())
3554 if (CatchSwitch.hasUnwindDest())
3558 case Instruction::CallBr: {
3564 writeOperandBundles(*CBI, InstID);
3579 pushValueAndType(Callee, InstID, Vals);
3582 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3583 pushValue(
I.getOperand(i), InstID, Vals);
3586 if (FTy->isVarArg()) {
3587 for (
unsigned i = FTy->getNumParams(), e = CBI->
arg_size(); i != e; ++i)
3588 pushValueAndType(
I.getOperand(i), InstID, Vals);
3592 case Instruction::Unreachable:
3594 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
3597 case Instruction::PHI: {
3615 Stream.
EmitRecord(Code, Vals64, AbbrevToUse);
3620 case Instruction::LandingPad: {
3631 pushValueAndType(LP.
getClause(
I), InstID, Vals);
3636 case Instruction::Alloca: {
3642 using APV = AllocaPackedValues;
3644 unsigned EncodedAlign = getEncodedAlign(AI.
getAlign());
3646 Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1));
3648 EncodedAlign >> APV::AlignLower::Bits);
3655 if (AS !=
M.getDataLayout().getAllocaAddrSpace())
3660 case Instruction::Load: {
3662 if (LI.isAtomic()) {
3664 pushValueAndType(LI.getOperand(0), InstID, Vals);
3667 if (!pushValueAndType(LI.getOperand(0), InstID, Vals))
3668 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
3671 Vals.
push_back(getEncodedAlign(LI.getAlign()));
3673 if (LI.isAtomic()) {
3675 Vals.
push_back(getEncodedSyncScopeID(LI.getSyncScopeID()));
3676 if (LI.isElementwise())
3682 case Instruction::Store: {
3684 if (
SI.isAtomic()) {
3688 AbbrevToUse = FUNCTION_INST_STORE_ABBREV;
3690 if (pushValueAndType(
I.getOperand(1), InstID, Vals))
3692 if (pushValueAndType(
I.getOperand(0), InstID, Vals))
3696 if (
SI.isAtomic()) {
3698 Vals.
push_back(getEncodedSyncScopeID(
SI.getSyncScopeID()));
3699 if (
SI.isElementwise())
3705 case Instruction::AtomicCmpXchg:
3707 pushValueAndType(
I.getOperand(0), InstID, Vals);
3708 pushValueAndType(
I.getOperand(1), InstID, Vals);
3709 pushValue(
I.getOperand(2), InstID, Vals);
3720 case Instruction::AtomicRMW:
3722 pushValueAndType(
I.getOperand(0), InstID, Vals);
3723 pushValueAndType(
I.getOperand(1), InstID, Vals);
3731 case Instruction::Fence:
3736 case Instruction::Call: {
3741 writeOperandBundles(CI, InstID);
3761 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3765 if (FTy->isVarArg()) {
3766 for (
unsigned i = FTy->getNumParams(), e = CI.
arg_size(); i != e; ++i)
3771 case Instruction::VAArg:
3774 pushValue(
I.getOperand(0), InstID, Vals);
3777 case Instruction::Freeze:
3779 pushValueAndType(
I.getOperand(0), InstID, Vals);
3789void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3790 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3795 VSTOffset -= bitcodeStartBit();
3796 assert((VSTOffset & 31) == 0 &&
"VST block not 32-bit aligned");
3800 Stream.
BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
3804 auto Abbv = std::make_shared<BitCodeAbbrev>();
3808 unsigned FnEntryAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
3813 if (
F.isDeclaration())
3820 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&
F] - bitcodeStartBit();
3821 assert((BitcodeIndex & 31) == 0 &&
"function block not 32-bit aligned");
3825 Record[1] = BitcodeIndex / 32 + 1;
3834void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3835 const ValueSymbolTable &VST) {
3843 SmallVector<uint64_t, 64> NameVals;
3849 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3858 AbbrevToUse = VST_BBENTRY_6_ABBREV;
3862 AbbrevToUse = VST_ENTRY_6_ABBREV;
3864 AbbrevToUse = VST_ENTRY_7_ABBREV;
3867 for (
const auto P :
Name.getKey())
3871 Stream.
EmitRecord(Code, NameVals, AbbrevToUse);
3878void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3879 assert(Order.Shuffle.size() >= 2 &&
"Shuffle too small");
3886 SmallVector<uint64_t, 64>
Record(Order.Shuffle.begin(), Order.Shuffle.end());
3891void ModuleBitcodeWriter::writeUseListBlock(
const Function *
F) {
3893 "Expected to be preserving use-list order");
3895 auto hasMore = [&]() {
3911void ModuleBitcodeWriter::writeFunction(
3913 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3930 unsigned CstStart, CstEnd;
3932 writeConstants(CstStart, CstEnd,
false);
3935 writeFunctionMetadata(
F);
3938 unsigned InstID = CstEnd;
3940 bool NeedsMetadataAttachment =
F.hasMetadata();
3942 DILocation *LastDL =
nullptr;
3943 SmallSetVector<Function *, 4> BlockAddressUsers;
3946 for (
const BasicBlock &BB :
F) {
3947 for (
const Instruction &
I : BB) {
3948 writeInstruction(
I, InstID, Vals);
3950 if (!
I.getType()->isVoidTy())
3954 NeedsMetadataAttachment |=
I.hasMetadataOtherThanDebugLoc();
3957 if (DILocation *
DL =
I.getDebugLoc()) {
3970 unsigned DLAbbrev = FUNCTION_DEBUG_LOC_ABBREV;
3971 if (DILayerLocList *IRLayers =
DL->getIRLayers()) {
3972 DLAbbrev = FUNCTION_DEBUG_LOC_LAYERS_ABBREV;
3986 if (
I.hasDbgRecords()) {
3990 auto PushValueOrMetadata = [&Vals, InstID,
3993 "RawLocation unexpectedly null in DbgVariableRecord");
3995 SmallVector<unsigned, 2> ValAndType;
3999 if (!pushValueAndType(VAM->getValue(), InstID, ValAndType)) {
4013 for (DbgRecord &DR :
I.getDbgMarker()->getDbgRecordRange()) {
4039 FUNCTION_DEBUG_RECORD_VALUE_ABBREV);
4063 SmallPtrSet<Value *, 8> Visited{BA};
4064 while (!Worklist.
empty()) {
4066 for (User *U :
V->users()) {
4072 Visited.
insert(U).second)
4079 if (!BlockAddressUsers.
empty()) {
4088 if (
auto *Symtab =
F.getValueSymbolTable())
4089 writeFunctionLevelValueSymbolTable(*Symtab);
4091 if (NeedsMetadataAttachment)
4092 writeFunctionMetadataAttachment(
F);
4094 writeUseListBlock(&
F);
4100void ModuleBitcodeWriter::writeBlockInfo() {
4113 auto Abbv = std::make_shared<BitCodeAbbrev>();
4124 auto Abbv = std::make_shared<BitCodeAbbrev>();
4134 auto Abbv = std::make_shared<BitCodeAbbrev>();
4144 auto Abbv = std::make_shared<BitCodeAbbrev>();
4150 VST_BBENTRY_6_ABBREV)
4155 auto Abbv = std::make_shared<BitCodeAbbrev>();
4157 Abbv->Add(TypeAbbrevOp);
4159 CONSTANTS_SETTYPE_ABBREV)
4164 auto Abbv = std::make_shared<BitCodeAbbrev>();
4168 CONSTANTS_INTEGER_ABBREV)
4173 auto Abbv = std::make_shared<BitCodeAbbrev>();
4177 CONSTANTS_BYTE_ABBREV)
4182 auto Abbv = std::make_shared<BitCodeAbbrev>();
4190 CONSTANTS_CE_CAST_Abbrev)
4194 auto Abbv = std::make_shared<BitCodeAbbrev>();
4197 CONSTANTS_NULL_Abbrev)
4204 auto Abbv = std::make_shared<BitCodeAbbrev>();
4206 Abbv->Add(ValAbbrevOp);
4207 Abbv->Add(TypeAbbrevOp);
4211 FUNCTION_INST_LOAD_ABBREV)
4215 auto Abbv = std::make_shared<BitCodeAbbrev>();
4217 Abbv->Add(ValAbbrevOp);
4218 Abbv->Add(ValAbbrevOp);
4222 FUNCTION_INST_STORE_ABBREV)
4226 auto Abbv = std::make_shared<BitCodeAbbrev>();
4228 Abbv->Add(ValAbbrevOp);
4231 FUNCTION_INST_UNOP_ABBREV)
4235 auto Abbv = std::make_shared<BitCodeAbbrev>();
4237 Abbv->Add(ValAbbrevOp);
4241 FUNCTION_INST_UNOP_FLAGS_ABBREV)
4245 auto Abbv = std::make_shared<BitCodeAbbrev>();
4247 Abbv->Add(ValAbbrevOp);
4248 Abbv->Add(ValAbbrevOp);
4251 FUNCTION_INST_BINOP_ABBREV)
4255 auto Abbv = std::make_shared<BitCodeAbbrev>();
4257 Abbv->Add(ValAbbrevOp);
4258 Abbv->Add(ValAbbrevOp);
4262 FUNCTION_INST_BINOP_FLAGS_ABBREV)
4266 auto Abbv = std::make_shared<BitCodeAbbrev>();
4268 Abbv->Add(ValAbbrevOp);
4269 Abbv->Add(TypeAbbrevOp);
4272 FUNCTION_INST_CAST_ABBREV)
4276 auto Abbv = std::make_shared<BitCodeAbbrev>();
4278 Abbv->Add(ValAbbrevOp);
4279 Abbv->Add(TypeAbbrevOp);
4283 FUNCTION_INST_CAST_FLAGS_ABBREV)
4288 auto Abbv = std::make_shared<BitCodeAbbrev>();
4291 FUNCTION_INST_RET_VOID_ABBREV)
4295 auto Abbv = std::make_shared<BitCodeAbbrev>();
4297 Abbv->Add(ValAbbrevOp);
4299 FUNCTION_INST_RET_VAL_ABBREV)
4303 auto Abbv = std::make_shared<BitCodeAbbrev>();
4306 Abbv->Add(ValAbbrevOp);
4308 FUNCTION_INST_BR_UNCOND_ABBREV)
4312 auto Abbv = std::make_shared<BitCodeAbbrev>();
4315 Abbv->Add(ValAbbrevOp);
4316 Abbv->Add(ValAbbrevOp);
4317 Abbv->Add(ValAbbrevOp);
4319 FUNCTION_INST_BR_COND_ABBREV)
4323 auto Abbv = std::make_shared<BitCodeAbbrev>();
4326 FUNCTION_INST_UNREACHABLE_ABBREV)
4330 auto Abbv = std::make_shared<BitCodeAbbrev>();
4333 Abbv->Add(TypeAbbrevOp);
4335 Abbv->Add(ValAbbrevOp);
4337 FUNCTION_INST_GEP_ABBREV)
4341 auto Abbv = std::make_shared<BitCodeAbbrev>();
4343 Abbv->Add(ValAbbrevOp);
4344 Abbv->Add(ValAbbrevOp);
4347 FUNCTION_INST_CMP_ABBREV)
4351 auto Abbv = std::make_shared<BitCodeAbbrev>();
4353 Abbv->Add(ValAbbrevOp);
4354 Abbv->Add(ValAbbrevOp);
4358 FUNCTION_INST_CMP_FLAGS_ABBREV)
4362 auto Abbv = std::make_shared<BitCodeAbbrev>();
4367 Abbv->Add(ValAbbrevOp);
4369 FUNCTION_DEBUG_RECORD_VALUE_ABBREV)
4373 auto Abbv = std::make_shared<BitCodeAbbrev>();
4384 FUNCTION_DEBUG_LOC_ABBREV)
4390 auto Abbv = std::make_shared<BitCodeAbbrev>();
4401 FUNCTION_DEBUG_LOC_LAYERS_ABBREV)
4409void IndexBitcodeWriter::writeModStrings() {
4415 auto Abbv = std::make_shared<BitCodeAbbrev>();
4420 unsigned Abbrev8Bit = Stream.
EmitAbbrev(std::move(Abbv));
4423 Abbv = std::make_shared<BitCodeAbbrev>();
4428 unsigned Abbrev7Bit = Stream.
EmitAbbrev(std::move(Abbv));
4431 Abbv = std::make_shared<BitCodeAbbrev>();
4436 unsigned Abbrev6Bit = Stream.
EmitAbbrev(std::move(Abbv));
4439 Abbv = std::make_shared<BitCodeAbbrev>();
4446 unsigned AbbrevHash = Stream.
EmitAbbrev(std::move(Abbv));
4449 forEachModule([&](
const StringMapEntry<ModuleHash> &MPSE) {
4451 const auto &Hash = MPSE.
getValue();
4453 unsigned AbbrevToUse = Abbrev8Bit;
4455 AbbrevToUse = Abbrev6Bit;
4457 AbbrevToUse = Abbrev7Bit;
4459 auto ModuleId = ModuleIdMap.
size();
4460 ModuleIdMap[
Key] = ModuleId;
4470 Vals.
assign(Hash.begin(), Hash.end());
4482template <
typename Fn>
4486 if (!FS->type_tests().empty())
4491 auto WriteVFuncIdVec = [&](
uint64_t Ty,
4496 for (
auto &VF : VFs) {
4497 Record.push_back(VF.GUID);
4498 Record.push_back(VF.Offset);
4504 FS->type_test_assume_vcalls());
4506 FS->type_checked_load_vcalls());
4508 auto WriteConstVCallVec = [&](
uint64_t Ty,
4510 for (
auto &VC : VCs) {
4512 Record.push_back(VC.VFunc.GUID);
4513 Record.push_back(VC.VFunc.Offset);
4520 FS->type_test_assume_const_vcalls());
4522 FS->type_checked_load_const_vcalls());
4532 if (!FS->paramAccesses().empty()) {
4534 for (
auto &Arg : FS->paramAccesses()) {
4535 size_t UndoSize =
Record.size();
4536 Record.push_back(Arg.ParamNo);
4537 WriteRange(Arg.Use);
4538 Record.push_back(Arg.Calls.size());
4539 for (
auto &
Call : Arg.Calls) {
4541 std::optional<unsigned> ValueID = GetValueID(
Call.Callee);
4548 Record.push_back(*ValueID);
4549 WriteRange(
Call.Offsets);
4560 std::set<GlobalValue::GUID> &ReferencedTypeIds) {
4561 if (!FS->type_tests().empty())
4562 for (
auto &TT : FS->type_tests())
4563 ReferencedTypeIds.insert(TT);
4565 auto GetReferencedTypesFromVFuncIdVec =
4567 for (
auto &VF : VFs)
4568 ReferencedTypeIds.insert(VF.GUID);
4571 GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
4572 GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
4574 auto GetReferencedTypesFromConstVCallVec =
4576 for (
auto &VC : VCs)
4577 ReferencedTypeIds.insert(VC.VFunc.GUID);
4580 GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
4581 GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
4617 NameVals.
push_back(Summary.TTRes.TheKind);
4618 NameVals.
push_back(Summary.TTRes.SizeM1BitWidth);
4619 NameVals.
push_back(Summary.TTRes.AlignLog2);
4620 NameVals.
push_back(Summary.TTRes.SizeM1);
4621 NameVals.
push_back(Summary.TTRes.BitMask);
4622 NameVals.
push_back(Summary.TTRes.InlineBits);
4624 for (
auto &W : Summary.WPDRes)
4636 for (
auto &
P : Summary) {
4638 NameVals.
push_back(
VE.getValueID(
P.VTableVI.getValue()));
4652 static_assert(std::is_same_v<LinearFrameId, unsigned>);
4653 for (
auto &AI : FS->allocs()) {
4654 for (
auto &MIB : AI.MIBs) {
4656 StackIdIndices.
reserve(MIB.StackIdIndices.size());
4657 for (
auto Id : MIB.StackIdIndices)
4658 StackIdIndices.
push_back(GetStackIndex(Id));
4660 CallStacks.insert({CallStacks.size(), StackIdIndices});
4673 assert(!CallStacks.empty());
4679 Builder.
build(std::move(CallStacks),
nullptr,
4683 return Builder.takeCallStackPos();
4688 unsigned AllocAbbrev,
unsigned ContextIdAbbvId,
bool PerModule,
4689 std::function<
unsigned(
const ValueInfo &VI)> GetValueID,
4690 std::function<
unsigned(
unsigned)> GetStackIndex,
4691 bool WriteContextSizeInfoIndex,
4696 for (
auto &CI : FS->callsites()) {
4700 assert(!PerModule || (CI.Clones.size() == 1 && CI.Clones[0] == 0));
4701 Record.push_back(GetValueID(CI.Callee));
4703 Record.push_back(CI.StackIdIndices.size());
4704 Record.push_back(CI.Clones.size());
4706 for (
auto Id : CI.StackIdIndices)
4707 Record.push_back(GetStackIndex(Id));
4715 for (
auto &AI : FS->allocs()) {
4719 assert(!PerModule || (AI.Versions.size() == 1 && AI.Versions[0] == 0));
4720 Record.push_back(AI.MIBs.size());
4722 Record.push_back(AI.Versions.size());
4723 for (
auto &MIB : AI.MIBs) {
4730 assert(CallStackCount <= CallStackPos.
size());
4731 Record.push_back(CallStackPos[CallStackCount++]);
4736 assert(AI.ContextSizeInfos.empty() ||
4737 AI.ContextSizeInfos.size() == AI.MIBs.size());
4739 if (WriteContextSizeInfoIndex && !AI.ContextSizeInfos.empty()) {
4747 ContextIds.
reserve(AI.ContextSizeInfos.size() * 2);
4748 for (
auto &Infos : AI.ContextSizeInfos) {
4749 Record.push_back(Infos.size());
4750 for (
auto [FullStackId, TotalSize] : Infos) {
4757 Record.push_back(TotalSize);
4775void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
4776 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
4777 unsigned ValueID,
unsigned FSCallsProfileAbbrev,
unsigned CallsiteAbbrev,
4778 unsigned AllocAbbrev,
unsigned ContextIdAbbvId,
const Function &
F,
4779 DenseMap<CallStackId, LinearCallStackId> &CallStackPos,
4786 Stream, FS, [&](
const ValueInfo &VI) -> std::optional<unsigned> {
4790 auto SpecialRefCnts =
FS->specialRefCounts();
4795 NameVals.
push_back(SpecialRefCnts.first);
4796 NameVals.
push_back(SpecialRefCnts.second);
4798 for (
auto &RI :
FS->refs())
4801 for (
auto &ECI :
FS->calls()) {
4802 NameVals.
push_back(getValueId(ECI.first));
4811 Stream, FS, CallsiteAbbrev, AllocAbbrev, ContextIdAbbvId,
4813 [&](
const ValueInfo &VI) {
return getValueId(VI); },
4814 [&](
unsigned I) {
return I; },
4815 true, CallStackPos, CallStackCount);
4820void ModuleBitcodeWriterBase::writeModuleLevelReferences(
4821 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
4822 unsigned FSModRefsAbbrev,
unsigned FSModVTableRefsAbbrev) {
4827 auto VI =
Index->getValueInfo(GUID);
4828 if (!VI ||
VI.getSummaryList().empty()) {
4834 auto *
Summary =
VI.getSummaryList()[0].get();
4840 auto VTableFuncs =
VS->vTableFuncs();
4841 if (!VTableFuncs.empty())
4844 unsigned SizeBeforeRefs = NameVals.
size();
4845 for (
auto &RI :
VS->refs())
4851 if (VTableFuncs.empty())
4856 for (
auto &
P : VTableFuncs) {
4862 FSModVTableRefsAbbrev);
4869void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
4872 bool IsThinLTO =
true;
4875 IsThinLTO = MD->getZExtValue();
4887 if (
Index->enableSplitLTOUnit())
4889 if (
Index->hasUnifiedLTO())
4899 auto Abbv = std::make_shared<BitCodeAbbrev>();
4905 unsigned ValueGuidAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4907 for (
const auto &GVI : valueIds()) {
4909 ArrayRef<uint32_t>{GVI.second,
4910 static_cast<uint32_t
>(GVI.first >> 32),
4911 static_cast<uint32_t
>(GVI.first)},
4915 if (!
Index->stackIds().empty()) {
4916 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4923 unsigned StackIdAbbvId = Stream.
EmitAbbrev(std::move(StackIdAbbv));
4924 SmallVector<uint32_t> Vals;
4926 for (
auto Id :
Index->stackIds()) {
4927 Vals.
push_back(
static_cast<uint32_t
>(Id >> 32));
4928 Vals.
push_back(
static_cast<uint32_t
>(Id));
4933 unsigned ContextIdAbbvId = 0;
4936 auto ContextIdAbbv = std::make_shared<BitCodeAbbrev>();
4948 ContextIdAbbvId = Stream.
EmitAbbrev(std::move(ContextIdAbbv));
4952 Abbv = std::make_shared<BitCodeAbbrev>();
4964 unsigned FSCallsProfileAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4967 Abbv = std::make_shared<BitCodeAbbrev>();
4973 unsigned FSModRefsAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4976 Abbv = std::make_shared<BitCodeAbbrev>();
4984 unsigned FSModVTableRefsAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4987 Abbv = std::make_shared<BitCodeAbbrev>();
4992 unsigned FSAliasAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4995 Abbv = std::make_shared<BitCodeAbbrev>();
5002 unsigned TypeIdCompatibleVtableAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5004 Abbv = std::make_shared<BitCodeAbbrev>();
5010 unsigned CallsiteAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5012 Abbv = std::make_shared<BitCodeAbbrev>();
5019 unsigned AllocAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5021 Abbv = std::make_shared<BitCodeAbbrev>();
5026 unsigned RadixAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5033 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks;
5044 ValueInfo
VI =
Index->getValueInfo(GUID);
5045 if (!VI ||
VI.getSummaryList().empty()) {
5048 if (!
F.isDeclaration())
5050 " to have an associated value info.");
5053 auto *
Summary =
VI.getSummaryList()[0].get();
5056 FS, [](
unsigned I) {
return I; }, CallStacks);
5060 DenseMap<CallStackId, LinearCallStackId> CallStackPos;
5061 if (!CallStacks.
empty()) {
5069 SmallVector<uint64_t, 64> NameVals;
5080 ValueInfo
VI =
Index->getValueInfo(GUID);
5081 if (!VI ||
VI.getSummaryList().empty()) {
5087 auto *
Summary =
VI.getSummaryList()[0].get();
5088 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.
getValueID(&
F),
5089 FSCallsProfileAbbrev, CallsiteAbbrev,
5090 AllocAbbrev, ContextIdAbbvId,
F,
5091 CallStackPos, CallStackCount);
5096 for (
const GlobalVariable &
G :
M.globals())
5097 writeModuleLevelReferences(
G, NameVals, FSModRefsAbbrev,
5098 FSModVTableRefsAbbrev);
5100 for (
const GlobalAlias &
A :
M.aliases()) {
5101 auto *Aliasee =
A.getAliaseeObject();
5117 for (
auto &S :
Index->typeIdCompatibleVtableMap()) {
5121 TypeIdCompatibleVtableAbbrev);
5125 if (
Index->getBlockCount())
5127 ArrayRef<uint64_t>{
Index->getBlockCount()});
5132void ModuleBitcodeWriterBase::writeGUIDList() {
5134 for (
const GlobalValue &GV :
M.global_values()) {
5135 auto MaybeGUID = GV.getGUIDIfAssigned();
5136 if (!MaybeGUID || *MaybeGUID == 0)
5139 if (ValueID >= GUIDs.
size())
5140 GUIDs.
resize(ValueID + 1);
5141 GUIDs[ValueID] = *MaybeGUID;
5144 auto Abbv = std::make_shared<BitCodeAbbrev>();
5148 unsigned GUIDListAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5150 SmallVector<uint32_t> RecordVals;
5152 for (
auto GUID : GUIDs) {
5153 RecordVals.
push_back(
static_cast<uint32_t
>(GUID >> 32));
5154 RecordVals.
push_back(
static_cast<uint32_t
>(GUID));
5161void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
5170 auto Abbv = std::make_shared<BitCodeAbbrev>();
5176 unsigned ValueGuidAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5178 for (
const auto &GVI : valueIds()) {
5180 ArrayRef<uint32_t>{GVI.second,
5181 static_cast<uint32_t
>(GVI.first >> 32),
5182 static_cast<uint32_t
>(GVI.first)},
5188 if (!StackIds.empty()) {
5189 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
5196 unsigned StackIdAbbvId = Stream.
EmitAbbrev(std::move(StackIdAbbv));
5197 SmallVector<uint32_t> Vals;
5198 Vals.
reserve(StackIds.size() * 2);
5199 for (
auto Id : StackIds) {
5200 Vals.
push_back(
static_cast<uint32_t
>(Id >> 32));
5201 Vals.
push_back(
static_cast<uint32_t
>(Id));
5207 Abbv = std::make_shared<BitCodeAbbrev>();
5221 unsigned FSCallsProfileAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5224 Abbv = std::make_shared<BitCodeAbbrev>();
5231 unsigned FSModRefsAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5234 Abbv = std::make_shared<BitCodeAbbrev>();
5240 unsigned FSAliasAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5242 Abbv = std::make_shared<BitCodeAbbrev>();
5250 unsigned CallsiteAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5252 Abbv = std::make_shared<BitCodeAbbrev>();
5263 unsigned AllocAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5265 auto shouldImportValueAsDecl = [&](GlobalValueSummary *GVS) ->
bool {
5266 if (DecSummaries ==
nullptr)
5268 return DecSummaries->
count(GVS);
5276 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
5278 SmallVector<uint64_t, 64> NameVals;
5282 std::set<GlobalValue::GUID> ReferencedTypeIds;
5286 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
5296 NameVals.
push_back(S.getOriginalName());
5301 DenseMap<CallStackId, LinearCallStackId> CallStackPos;
5303 Abbv = std::make_shared<BitCodeAbbrev>();
5308 unsigned RadixAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5315 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks;
5316 forEachSummary([&](GVInfo
I,
bool IsAliasee) {
5322 GlobalValueSummary *S =
I.second;
5335 return StackIdIndicesToIndex[
I];
5341 if (!CallStacks.
empty()) {
5351 DenseSet<GlobalValue::GUID> DefOrUseGUIDs;
5352 forEachSummary([&](GVInfo
I,
bool IsAliasee) {
5353 GlobalValueSummary *S =
I.second;
5355 DefOrUseGUIDs.
insert(
I.first);
5356 for (
const ValueInfo &VI : S->
refs())
5357 DefOrUseGUIDs.
insert(
VI.getGUID());
5359 auto ValueId = getValueId(
I.first);
5361 SummaryToValueIdMap[S] = *ValueId;
5379 NameVals.
push_back(ModuleIdMap[
VS->modulePath()]);
5383 for (
auto &RI :
VS->refs()) {
5384 auto RefValueId = getValueId(RI.getGUID());
5394 MaybeEmitOriginalName(*S);
5398 auto GetValueId = [&](
const ValueInfo &
VI) -> std::optional<unsigned> {
5400 return std::nullopt;
5401 return getValueId(
VI.getGUID());
5410 NameVals.
push_back(ModuleIdMap[
FS->modulePath()]);
5423 unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;
5424 for (
auto &RI :
FS->refs()) {
5425 auto RefValueId = getValueId(RI.getGUID());
5429 if (RI.isReadOnly())
5431 else if (RI.isWriteOnly())
5435 NameVals[6] =
Count;
5436 NameVals[7] = RORefCnt;
5437 NameVals[8] = WORefCnt;
5439 for (
auto &EI :
FS->calls()) {
5442 std::optional<unsigned> CallValueId = GetValueId(EI.first);
5451 FSCallsProfileAbbrev);
5455 Stream, FS, CallsiteAbbrev, AllocAbbrev, 0,
5458 [&](
const ValueInfo &VI) ->
unsigned {
5459 std::optional<unsigned> ValueID = GetValueId(VI);
5474 return StackIdIndicesToIndex[
I];
5476 false, CallStackPos, CallStackCount);
5478 MaybeEmitOriginalName(*S);
5481 for (
auto *AS : Aliases) {
5482 auto AliasValueId = SummaryToValueIdMap[AS];
5491 auto AliaseeValueId =
5498 MaybeEmitOriginalName(*AS);
5506 auto EmitCfiFunctions = [&](
const CfiFunctionIndex &CfiIndex,
5508 if (CfiIndex.
empty())
5512 for (StringRef Name : Names)
5515 if (Functions.
empty())
5518 for (
const auto &Record : Functions) {
5533 for (
auto &
T : ReferencedTypeIds) {
5534 auto TidIter =
Index.typeIds().equal_range(
T);
5535 for (
const auto &[GUID, TypeIdPair] :
make_range(TidIter)) {
5543 if (
Index.getBlockCount())
5545 ArrayRef<uint64_t>{
Index.getBlockCount()});
5556 auto Abbv = std::make_shared<BitCodeAbbrev>();
5560 auto StringAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5562 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
5565 Abbv = std::make_shared<BitCodeAbbrev>();
5568 auto EpochAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5574void ModuleBitcodeWriter::writeModuleHash(StringRef View) {
5579 Hasher.
update(ArrayRef<uint8_t>(
5580 reinterpret_cast<const uint8_t *
>(
View.data()),
View.size()));
5581 std::array<uint8_t, 20> Hash = Hasher.
result();
5582 for (
int Pos = 0; Pos < 20; Pos += 4) {
5595void ModuleBitcodeWriter::write() {
5603 writeModuleVersion();
5612 writeAttributeGroupTable();
5615 writeAttributeTable();
5624 writeModuleConstants();
5627 writeModuleMetadataKinds();
5630 writeModuleMetadata();
5634 writeUseListBlock(
nullptr);
5636 writeOperandBundleTags();
5637 writeSyncScopeNames();
5640 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
5642 if (!
F.isDeclaration())
5643 writeFunction(
F, FunctionToBitcodeIndex);
5648 writePerModuleGlobalValueSummary();
5650 writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
5678 unsigned CPUType = ~0U;
5685 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
5686 DARWIN_CPU_TYPE_X86 = 7,
5687 DARWIN_CPU_TYPE_ARM = 12,
5688 DARWIN_CPU_TYPE_POWERPC = 18
5693 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
5695 CPUType = DARWIN_CPU_TYPE_X86;
5697 CPUType = DARWIN_CPU_TYPE_POWERPC;
5699 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
5701 CPUType = DARWIN_CPU_TYPE_ARM;
5705 "Expected header size to be reserved");
5710 unsigned Position = 0;
5718 while (Buffer.
size() & 15)
5725 Stream.
Emit((
unsigned)
'B', 8);
5726 Stream.
Emit((
unsigned)
'C', 8);
5727 Stream.
Emit(0x0, 4);
5728 Stream.
Emit(0xC, 4);
5729 Stream.
Emit(0xE, 4);
5730 Stream.
Emit(0xD, 4);
5748 auto Abbv = std::make_shared<BitCodeAbbrev>();
5751 auto AbbrevNo = Stream->
EmitAbbrev(std::move(Abbv));
5759 assert(!WroteStrtab && !WroteSymtab);
5765 if (M->getModuleInlineAsm().empty())
5769 const Triple TT(M->getTargetTriple());
5771 if (!
T || !
T->hasMCAsmParser())
5793 std::vector<char> Strtab;
5794 StrtabBuilder.finalizeInOrder();
5795 Strtab.resize(StrtabBuilder.getSize());
5796 StrtabBuilder.write((
uint8_t *)Strtab.data());
5799 {Strtab.data(), Strtab.size()});
5810 bool ShouldPreserveUseListOrder,
5819 assert(M.isMaterialized());
5820 Mods.push_back(
const_cast<Module *
>(&M));
5822 ModuleBitcodeWriter ModuleWriter(M, StrtabBuilder, *Stream,
5823 ShouldPreserveUseListOrder, Index,
5824 GenerateHash, ModHash);
5825 ModuleWriter.write();
5832 IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index, DecSummaries,
5833 ModuleToSummariesForIndex);
5834 IndexWriter.write();
5839 bool ShouldPreserveUseListOrder,
5843 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
5845 Writer.writeSymtab();
5846 Writer.writeStrtab();
5848 Triple TT(M.getTargetTriple());
5849 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) {
5860 Out.write(Buffer.
data(), Buffer.
size());
5867void IndexBitcodeWriter::write() {
5870 writeModuleVersion();
5876 writeCombinedGlobalValueSummary();
5893 Writer.
writeIndex(&Index, ModuleToSummariesForIndex, DecSummaries);
5896 Out.write((
char *)&Buffer.
front(), Buffer.
size());
5902class ThinLinkBitcodeWriter :
public ModuleBitcodeWriterBase {
5912 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
5914 ModHash(&ModHash) {}
5919 void writeSimplifiedModuleInfo();
5929void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
5941 auto Abbv = std::make_shared<BitCodeAbbrev>();
5944 Abbv->Add(AbbrevOpToUse);
5945 unsigned FilenameAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5947 for (
const auto P :
M.getSourceFileName())
6013void ThinLinkBitcodeWriter::write() {
6016 writeModuleVersion();
6018 writeSimplifiedModuleInfo();
6020 writePerModuleGlobalValueSummary();
6037 assert(M.isMaterialized());
6038 Mods.push_back(
const_cast<Module *
>(&M));
6040 ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
6042 ThinLinkWriter.write();
6059 Out.write((
char *)&Buffer.
front(), Buffer.
size());
6063 switch (
T.getObjectFormat()) {
6065 return "__LLVM,__bitcode";
6090 switch (
T.getObjectFormat()) {
6092 return "__LLVM,__cmdline";
6118 const std::vector<uint8_t> &CmdArgs) {
6123 Type *UsedElementType = Used ? Used->getValueType()->getArrayElementType()
6125 for (
auto *GV : UsedGlobals) {
6126 if (GV->getName() !=
"llvm.embedded.module" &&
6127 GV->getName() !=
"llvm.cmdline")
6132 Used->eraseFromParent();
6137 Triple T(M.getTargetTriple());
6166 M.getGlobalVariable(
"llvm.embedded.module",
true)) {
6167 assert(Old->hasZeroLiveUses() &&
6168 "llvm.embedded.module can only be used once in llvm.compiler.used");
6170 Old->eraseFromParent();
6172 GV->
setName(
"llvm.embedded.module");
6190 assert(Old->hasZeroLiveUses() &&
6191 "llvm.cmdline can only be used once in llvm.compiler.used");
6193 Old->eraseFromParent();
6199 if (UsedArray.
empty())
6207 NewUsed->setSection(
"llvm.metadata");
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void writeDIMacro(raw_ostream &Out, const DIMacro *N, AsmWriterContext &WriterCtx)
static void writeDIGlobalVariableExpression(raw_ostream &Out, const DIGlobalVariableExpression *N, AsmWriterContext &WriterCtx)
static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N, AsmWriterContext &WriterCtx)
static void writeDIFixedPointType(raw_ostream &Out, const DIFixedPointType *N, AsmWriterContext &WriterCtx)
static void writeDISubrangeType(raw_ostream &Out, const DISubrangeType *N, AsmWriterContext &WriterCtx)
static void writeDIStringType(raw_ostream &Out, const DIStringType *N, AsmWriterContext &WriterCtx)
static void writeDILayerLocList(raw_ostream &Out, const DILayerLocList *N, AsmWriterContext &WriterCtx)
static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N, AsmWriterContext &WriterCtx)
static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N, AsmWriterContext &WriterCtx)
static void writeDILayerLoc(raw_ostream &Out, const DILayerLoc *N, AsmWriterContext &WriterCtx)
static void writeDIModule(raw_ostream &Out, const DIModule *N, AsmWriterContext &WriterCtx)
static void writeDIFile(raw_ostream &Out, const DIFile *N, AsmWriterContext &)
static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N, AsmWriterContext &WriterCtx)
static void writeDILabel(raw_ostream &Out, const DILabel *N, AsmWriterContext &WriterCtx)
static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N, AsmWriterContext &WriterCtx)
static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N, AsmWriterContext &WriterCtx)
static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N, AsmWriterContext &WriterCtx)
static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N, AsmWriterContext &WriterCtx)
static void writeDILocation(raw_ostream &Out, const DILocation *DL, AsmWriterContext &WriterCtx)
static void writeDINamespace(raw_ostream &Out, const DINamespace *N, AsmWriterContext &WriterCtx)
static void writeDICommonBlock(raw_ostream &Out, const DICommonBlock *N, AsmWriterContext &WriterCtx)
static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N, AsmWriterContext &WriterCtx)
static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N, AsmWriterContext &WriterCtx)
static void writeDITemplateTypeParameter(raw_ostream &Out, const DITemplateTypeParameter *N, AsmWriterContext &WriterCtx)
static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N, AsmWriterContext &WriterCtx)
static void writeDIGenericSubrange(raw_ostream &Out, const DIGenericSubrange *N, AsmWriterContext &WriterCtx)
static void writeDISubrange(raw_ostream &Out, const DISubrange *N, AsmWriterContext &WriterCtx)
static void writeDIProperty(raw_ostream &Out, const DIProperty *N, AsmWriterContext &WriterCtx)
static void writeDILexicalBlockFile(raw_ostream &Out, const DILexicalBlockFile *N, AsmWriterContext &WriterCtx)
static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N, AsmWriterContext &)
static void writeMDTuple(raw_ostream &Out, const MDTuple *Node, AsmWriterContext &WriterCtx)
static void writeDIExpression(raw_ostream &Out, const DIExpression *N, AsmWriterContext &WriterCtx)
static void writeDIAssignID(raw_ostream &Out, const DIAssignID *DL, AsmWriterContext &WriterCtx)
static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N, AsmWriterContext &WriterCtx)
static void writeDIArgList(raw_ostream &Out, const DIArgList *N, AsmWriterContext &WriterCtx, bool FromValue=false)
static void writeDITemplateValueParameter(raw_ostream &Out, const DITemplateValueParameter *N, AsmWriterContext &WriterCtx)
static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N, AsmWriterContext &WriterCtx)
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
static void writeFunctionHeapProfileRecords(BitstreamWriter &Stream, FunctionSummary *FS, unsigned CallsiteAbbrev, unsigned AllocAbbrev, unsigned ContextIdAbbvId, bool PerModule, std::function< unsigned(const ValueInfo &VI)> GetValueID, std::function< unsigned(unsigned)> GetStackIndex, bool WriteContextSizeInfoIndex, DenseMap< CallStackId, LinearCallStackId > &CallStackPos, CallStackId &CallStackCount)
static unsigned serializeSanitizerMetadata(const GlobalValue::SanitizerMetadata &Meta)
static void writeTypeIdCompatibleVtableSummaryRecord(SmallVector< uint64_t, 64 > &NameVals, StringTableBuilder &StrtabBuilder, StringRef Id, const TypeIdCompatibleVtableInfo &Summary, ValueEnumerator &VE)
static void getReferencedTypeIds(FunctionSummary *FS, std::set< GlobalValue::GUID > &ReferencedTypeIds)
Collect type IDs from type tests used by function.
static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind)
static void collectMemProfCallStacks(FunctionSummary *FS, std::function< LinearFrameId(unsigned)> GetStackIndex, MapVector< CallStackId, llvm::SmallVector< LinearFrameId > > &CallStacks)
static unsigned getEncodedUnaryOpcode(unsigned Opcode)
static void emitSignedInt64(SmallVectorImpl< uint64_t > &Vals, uint64_t V)
static unsigned getEncodedVisibility(const GlobalValue &GV)
static uint64_t getOptimizationFlags(const Value *V)
static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage)
static cl::opt< bool > PreserveBitcodeUseListOrder("preserve-bc-uselistorder", cl::Hidden, cl::init(true), cl::desc("Preserve use-list order when writing LLVM bitcode."))
static unsigned getEncodedThreadLocalMode(const GlobalValue &GV)
static DenseMap< CallStackId, LinearCallStackId > writeMemoryProfileRadixTree(MapVector< CallStackId, llvm::SmallVector< LinearFrameId > > &&CallStacks, BitstreamWriter &Stream, unsigned RadixAbbrev)
static void writeIdentificationBlock(BitstreamWriter &Stream)
Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the current llvm version,...
static unsigned getEncodedCastOpcode(unsigned Opcode)
static cl::opt< uint32_t > FlushThreshold("bitcode-flush-threshold", cl::Hidden, cl::init(512), cl::desc("The threshold (unit M) for flushing LLVM bitcode."))
static unsigned getEncodedOrdering(AtomicOrdering Ordering)
static unsigned getEncodedUnnamedAddr(const GlobalValue &GV)
static unsigned getEncodedComdatSelectionKind(const Comdat &C)
static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags, bool ImportAsDecl=false)
static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl< char > &Buffer, const Triple &TT)
If generating a bc file on darwin, we have to emit a header and trailer to make it compatible with th...
static void writeBitcodeHeader(BitstreamWriter &Stream)
Helper to write the header common to all bitcode files.
static void writeWholeProgramDevirtResolutionByArg(SmallVector< uint64_t, 64 > &NameVals, const std::vector< uint64_t > &args, const WholeProgramDevirtResolution::ByArg &ByArg)
static void emitConstantRange(SmallVectorImpl< uint64_t > &Record, const ConstantRange &CR, bool EmitBitWidth)
static StringEncoding getStringEncoding(StringRef Str)
Determine the encoding to use for the given string name and length.
static uint64_t getEncodedGVarFlags(GlobalVarSummary::GVarFlags Flags)
static const char * getSectionNameForCommandline(const Triple &T)
static cl::opt< unsigned > IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25), cl::desc("Number of metadatas above which we emit an index " "to enable lazy-loading"))
static void writeTypeIdSummaryRecord(SmallVector< uint64_t, 64 > &NameVals, StringTableBuilder &StrtabBuilder, StringRef Id, const TypeIdSummary &Summary)
static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream, FunctionSummary *FS, Fn GetValueID)
Write the function type metadata related records that need to appear before a function summary entry ...
static uint64_t getEncodedHotnessCallEdgeInfo(const CalleeInfo &CI)
static void emitWideAPInt(SmallVectorImpl< uint64_t > &Vals, const APInt &A)
static void writeStringRecord(BitstreamWriter &Stream, unsigned Code, StringRef Str, unsigned AbbrevToUse)
static unsigned getEncodedRMWOperation(const AtomicRMWInst &I)
static void writeWholeProgramDevirtResolution(SmallVector< uint64_t, 64 > &NameVals, StringTableBuilder &StrtabBuilder, uint64_t Id, const WholeProgramDevirtResolution &Wpd)
static unsigned getEncodedDLLStorageClass(const GlobalValue &GV)
static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl< char > &Buffer, uint32_t &Position)
static const char * getSectionNameForBitcode(const Triple &T)
static cl::opt< bool > CombinedIndexMemProfContext("combined-index-memprof-context", cl::Hidden, cl::init(true), cl::desc(""))
static unsigned getEncodedBinaryOpcode(unsigned Opcode)
static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
static MaybeAlign getAlign(Value *Ptr)
Module.h This file contains the declarations for the Module class.
static cl::opt< LTOBitcodeEmbedding > EmbedBitcode("lto-embed-bitcode", cl::init(LTOBitcodeEmbedding::DoNotEmbed), cl::values(clEnumValN(LTOBitcodeEmbedding::DoNotEmbed, "none", "Do not embed"), clEnumValN(LTOBitcodeEmbedding::EmbedOptimized, "optimized", "Embed after all optimization passes"), clEnumValN(LTOBitcodeEmbedding::EmbedPostMergePreOptimized, "post-merge-pre-opt", "Embed post merge, but before optimizations")), cl::desc("Embed LLVM bitcode in object files produced by LTO"))
Machine Check Debug Module
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallString class.
This file defines the SmallVector class.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static const uint32_t IV[8]
Class for arbitrary precision integers.
unsigned getActiveWords() const
Compute the number of active words in the value of this APInt.
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
int64_t getSExtValue() const
Get sign extended value.
const GlobalValueSummary & getAliasee() const
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
bool isUsedWithInAlloca() const
Return true if this alloca is used as an inalloca argument to a call.
unsigned getAddressSpace() const
Return the address space for the allocation.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
bool empty() const
Check if the array is empty.
Class to represent array types.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
an instruction that atomically reads a memory location, combines it with another value,...
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
bool hasAttributes() const
Return true if attributes exists in this set.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
@ TombstoneKey
Use as Tombstone key for DenseMap of AttrKind.
@ None
No attributes have been set.
@ EmptyKey
Use as Empty key for DenseMap of AttrKind.
@ EndAttrKinds
Sentinel value useful for loops.
BitCodeAbbrevOp - This describes one or more operands in an abbreviation.
static bool isChar6(char C)
isChar6 - Return true if this character is legal in the Char6 encoding.
LLVM_ABI void writeThinLinkBitcode(const Module &M, const ModuleSummaryIndex &Index, const ModuleHash &ModHash)
Write the specified thin link bitcode file (i.e., the minimized bitcode file) to the buffer specified...
LLVM_ABI void writeIndex(const ModuleSummaryIndex *Index, const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex, const GVSummaryPtrSet *DecSummaries)
LLVM_ABI void copyStrtab(StringRef Strtab)
Copy the string table for another module into this bitcode file.
LLVM_ABI void writeStrtab()
Write the bitcode file's string table.
LLVM_ABI ~BitcodeWriter()
LLVM_ABI void writeSymtab()
Attempt to write a symbol table to the bitcode file.
LLVM_ABI void writeModule(const Module &M, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false, ModuleHash *ModHash=nullptr)
Write the specified module to the buffer specified at construction time.
LLVM_ABI BitcodeWriter(SmallVectorImpl< char > &Buffer)
Create a BitcodeWriter that writes to Buffer.
unsigned EmitAbbrev(std::shared_ptr< BitCodeAbbrev > Abbv)
Emits the abbreviation Abbv to the stream.
void markAndBlockFlushing()
For scenarios where the user wants to access a section of the stream to (for example) compute some ch...
StringRef getMarkedBufferAndResumeFlushing()
resumes flushing, but does not flush, and returns the section in the internal buffer starting from th...
void EmitRecord(unsigned Code, const Container &Vals, unsigned Abbrev=0)
EmitRecord - Emit the specified record to the stream, using an abbrev if we have one to compress the ...
void Emit(uint32_t Val, unsigned NumBits)
void EmitRecordWithBlob(unsigned Abbrev, const Container &Vals, StringRef Blob)
EmitRecordWithBlob - Emit the specified record to the stream, using an abbrev that includes a blob at...
unsigned EmitBlockInfoAbbrev(unsigned BlockID, std::shared_ptr< BitCodeAbbrev > Abbv)
EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified BlockID.
void EnterBlockInfoBlock()
EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
void BackpatchWord(uint64_t BitNo, unsigned Val)
void BackpatchWord64(uint64_t BitNo, uint64_t Val)
void EnterSubblock(unsigned BlockID, unsigned CodeLen)
uint64_t GetCurrentBitNo() const
Retrieve the current position in the stream, in bits.
void EmitRecordWithAbbrev(unsigned Abbrev, const Container &Vals)
EmitRecordWithAbbrev - Emit a record with the specified abbreviation.
static LLVM_ABI BlockAddress * lookup(const BasicBlock *BB)
Lookup an existing BlockAddress constant for the given BasicBlock.
OperandBundleUse getOperandBundleAt(unsigned Index) const
Return the operand bundle at a specific index.
unsigned getNumOperandBundles() const
Return the number of operand bundles associated with this User.
CallingConv::ID getCallingConv() const
Value * getCalledOperand() const
Value * getArgOperand(unsigned i) const
FunctionType * getFunctionType() const
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
bool hasOperandBundles() const
Return true if this User has any operand bundles.
BasicBlock * getIndirectDest(unsigned i) const
BasicBlock * getDefaultDest() const
unsigned getNumIndirectDests() const
Return the number of callbr indirect dest labels.
bool isNoTailCall() const
bool isMustTailCall() const
auto getNamesForGUID(GlobalValue::GUID GUID) const
get the name(s) associated with a given ThinLTO GUID.
@ Largest
The linker will choose the largest COMDAT.
@ SameSize
The data referenced by the COMDAT must be the same size.
@ Any
The linker may choose any COMDAT.
@ NoDeduplicate
No deduplication is performed.
@ ExactMatch
The data referenced by the COMDAT must be the same.
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
This class represents a range of values.
const APInt & getLower() const
Return the lower value for this range.
const APInt & getUpper() const
Return the upper value for this range.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
This is an important base class in LLVM.
DebugLoc getDebugLoc() const
LLVM_ABI DIAssignID * getAssignID() const
DIExpression * getExpression() const
DILocalVariable * getVariable() const
bool isDbgDeclareValue() const
Metadata * getRawLocation() const
Returns the metadata operand for the first location description.
bool isDbgDeclare() const
Metadata * getRawAddress() const
DIExpression * getAddressExpression() const
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Lightweight error class with error context and mandatory checking.
Function summary information to aid decisions and implementation of importing.
LLVM_ABI void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
Appends all metadata attached to this value to MDs, sorting by KindID.
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
GVFlags flags() const
Get the flags for this GlobalValue (see struct GVFlags).
StringRef modulePath() const
Get the path to the module containing this function.
ArrayRef< ValueInfo > refs() const
Return the list of values referenced by this global value definition.
VisibilityTypes getVisibility() const
static bool isLocalLinkage(LinkageTypes Linkage)
LinkageTypes getLinkage() const
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
ThreadLocalMode getThreadLocalMode() const
@ DLLExportStorageClass
Function to be accessible from DLL.
@ DLLImportStorageClass
Function to be imported from DLL.
@ DefaultVisibility
The GV is visible.
@ HiddenVisibility
The GV is hidden.
@ ProtectedVisibility
The GV is protected.
UnnamedAddr getUnnamedAddr() const
LinkageTypes
An enumeration for the kinds of linkage for global values.
@ PrivateLinkage
Like Internal, but omit from symbol table.
@ CommonLinkage
Tentative definitions.
@ InternalLinkage
Rename collisions when linking (static functions).
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
@ WeakODRLinkage
Same, but only replaced by something equivalent.
@ ExternalLinkage
Externally visible function.
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
@ AppendingLinkage
Special purpose, only applies to global arrays.
@ AvailableExternallyLinkage
Available for inspection, not emission.
@ ExternalWeakLinkage
ExternalWeak linkage description.
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
DLLStorageClassTypes getDLLStorageClass() const
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
idx_iterator idx_end() const
idx_iterator idx_begin() const
bool isCleanup() const
Return 'true' if this landingpad instruction is a cleanup.
unsigned getNumClauses() const
Get the number of clauses for this landing pad.
bool isCatch(unsigned Idx) const
Return 'true' if the clause and index Idx is a catch clause.
Constant * getClause(unsigned Idx) const
Get the value of the clause at index Idx.
This class implements a map that also provides access to all stored values in a deterministic order.
size_t getBufferSize() const
const char * getBufferStart() const
const char * getBufferEnd() const
Class to hold module path string table and global value map, and encapsulate methods for operating on...
static constexpr uint64_t BitcodeSummaryVersion
A Module instance is used to store all the information related to an LLVM module.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Digest more data.
LLVM_ABI std::array< uint8_t, 20 > result()
Return the current raw 160-bits SHA1 for the digested data since the last call to init().
size_type size() const
Determine the number of elements in the SetVector.
bool empty() const
Determine if the SetVector is empty or not.
bool insert(const value_type &X)
Insert a new element into the SetVector.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void append(StringRef RHS)
Append from a StringRef.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
const ValueTy & getValue() const
Represent a constant reference to a string, i.e.
constexpr bool empty() const
Check if the string is empty.
constexpr size_t size() const
Get the string size.
Utility for building string tables with deduplicated suffixes.
LLVM_ABI size_t add(CachedHashStringRef S, uint8_t Priority=0)
Add a string to the builder.
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
The instances of the Type class are immutable: once they are created, they are never changed.
bool isX86_FP80Ty() const
Return true if this is x86 long double.
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
bool isFP128Ty() const
Return true if this is 'fp128'.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
std::vector< std::pair< const Value *, unsigned > > ValueList
unsigned getTypeID(Type *T) const
unsigned getMetadataID(const Metadata *MD) const
UseListOrderStack UseListOrders
ArrayRef< const Metadata * > getNonMDStrings() const
Get the non-MDString metadata for this block.
unsigned getInstructionID(const Instruction *I) const
unsigned getAttributeListID(AttributeList PAL) const
void incorporateFunction(const Function &F)
incorporateFunction/purgeFunction - If you'd like to deal with a function, use these two methods to g...
void getFunctionConstantRange(unsigned &Start, unsigned &End) const
getFunctionConstantRange - Return the range of values that corresponds to function-local constants.
unsigned getAttributeGroupID(IndexAndAttrSet Group) const
bool hasMDs() const
Check whether the current block has any metadata to emit.
unsigned getComdatID(const Comdat *C) const
uint64_t computeBitsRequiredForTypeIndices() const
unsigned getValueID(const Value *V) const
unsigned getMetadataOrNullID(const Metadata *MD) const
const std::vector< IndexAndAttrSet > & getAttributeGroups() const
const ValueList & getValues() const
unsigned getGlobalBasicBlockID(const BasicBlock *BB) const
getGlobalBasicBlockID - This returns the function-specific ID for the specified basic block.
void setInstructionID(const Instruction *I)
const std::vector< const BasicBlock * > & getBasicBlocks() const
const std::vector< AttributeList > & getAttributeLists() const
bool shouldPreserveUseListOrder() const
const ComdatSetType & getComdats() const
std::vector< Type * > TypeList
ArrayRef< const Metadata * > getMDStrings() const
Get the MDString metadata for this block.
std::pair< unsigned, AttributeSet > IndexAndAttrSet
Attribute groups as encoded in bitcode are almost AttributeSets, but they include the AttributeList i...
const TypeList & getTypes() const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
LLVMContext & getContext() const
All values hold a context through their type.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
std::pair< iterator, bool > insert(const ValueT &V)
void build(llvm::MapVector< CallStackId, llvm::SmallVector< FrameIdTy > > &&MemProfCallStackData, const llvm::DenseMap< FrameIdTy, LinearFrameId > *MemProfFrameIndexes, llvm::DenseMap< FrameIdTy, FrameStat > &FrameHistogram)
This class implements an extremely fast bulk output stream that can only output to a stream.
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
Predicate getPredicate(unsigned Condition, unsigned Hint)
Return predicate consisting of specified condition and hint bits.
@ CE
Windows NT (Windows on ARM)
@ TYPE_CODE_OPAQUE_POINTER
@ METADATA_TEMPLATE_VALUE
@ METADATA_LEXICAL_BLOCK_FILE
@ METADATA_SUBROUTINE_TYPE
@ METADATA_GLOBAL_DECL_ATTACHMENT
@ METADATA_IMPORTED_ENTITY
@ METADATA_GENERIC_SUBRANGE
@ METADATA_COMPOSITE_TYPE
@ METADATA_FIXED_POINT_TYPE
@ METADATA_GLOBAL_VAR_EXPR
GlobalValueSummarySymtabCodes
@ FS_CONTEXT_RADIX_TREE_ARRAY
@ FS_COMBINED_GLOBALVAR_INIT_REFS
@ FS_TYPE_CHECKED_LOAD_VCALLS
@ FS_COMBINED_ORIGINAL_NAME
@ FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_CONST_VCALL
@ FS_PERMODULE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_VCALLS
@ FS_COMBINED_ALLOC_INFO_NO_CONTEXT
@ FS_COMBINED_CALLSITE_INFO
@ FS_PERMODULE_CALLSITE_INFO
@ FS_PERMODULE_ALLOC_INFO
@ FS_TYPE_CHECKED_LOAD_CONST_VCALL
@ IDENTIFICATION_CODE_EPOCH
@ IDENTIFICATION_CODE_STRING
@ CST_CODE_DSO_LOCAL_EQUIVALENT
@ CST_CODE_CE_GEP_WITH_INRANGE
@ COMDAT_SELECTION_KIND_LARGEST
@ COMDAT_SELECTION_KIND_ANY
@ COMDAT_SELECTION_KIND_SAME_SIZE
@ COMDAT_SELECTION_KIND_EXACT_MATCH
@ COMDAT_SELECTION_KIND_NO_DUPLICATES
@ ATTR_KIND_STACK_PROTECT
@ ATTR_KIND_STACK_PROTECT_STRONG
@ ATTR_KIND_SANITIZE_MEMORY
@ ATTR_KIND_OPTIMIZE_FOR_SIZE
@ ATTR_KIND_FNRETTHUNK_EXTERN
@ ATTR_KIND_NO_DIVERGENCE_SOURCE
@ ATTR_KIND_SANITIZE_ADDRESS
@ ATTR_KIND_NO_IMPLICIT_FLOAT
@ ATTR_KIND_DEAD_ON_UNWIND
@ ATTR_KIND_STACK_ALIGNMENT
@ ATTR_KIND_STACK_PROTECT_REQ
@ ATTR_KIND_NULL_POINTER_IS_VALID
@ ATTR_KIND_SANITIZE_HWADDRESS
@ ATTR_KIND_RETURNS_TWICE
@ ATTR_KIND_SHADOWCALLSTACK
@ ATTR_KIND_OPT_FOR_FUZZING
@ ATTR_KIND_DENORMAL_FPENV
@ ATTR_KIND_SANITIZE_NUMERICAL_STABILITY
@ ATTR_KIND_SANITIZE_CONCURRENCY
@ ATTR_KIND_ALLOCATED_POINTER
@ ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION
@ ATTR_KIND_CORO_ELIDE_SAFE
@ ATTR_KIND_NON_LAZY_BIND
@ ATTR_KIND_DEREFERENCEABLE
@ ATTR_KIND_OPTIMIZE_NONE
@ ATTR_KIND_HYBRID_PATCHABLE
@ ATTR_KIND_DEREFERENCEABLE_OR_NULL
@ ATTR_KIND_SANITIZE_REALTIME
@ ATTR_KIND_SPECULATIVE_LOAD_HARDENING
@ ATTR_KIND_ALWAYS_INLINE
@ ATTR_KIND_SANITIZE_TYPE
@ ATTR_KIND_PRESPLIT_COROUTINE
@ ATTR_KIND_SANITIZE_ALLOC_TOKEN
@ ATTR_KIND_NO_SANITIZE_COVERAGE
@ ATTR_KIND_NO_CREATE_UNDEF_OR_POISON
@ ATTR_KIND_DEAD_ON_RETURN
@ ATTR_KIND_SANITIZE_REALTIME_BLOCKING
@ ATTR_KIND_NO_SANITIZE_BOUNDS
@ ATTR_KIND_SANITIZE_MEMTAG
@ ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE
@ ATTR_KIND_SANITIZE_THREAD
@ ATTR_KIND_OPTIMIZE_FOR_DEBUGGING
@ SYNC_SCOPE_NAMES_BLOCK_ID
@ PARAMATTR_GROUP_BLOCK_ID
@ IDENTIFICATION_BLOCK_ID
@ GLOBALVAL_SUMMARY_BLOCK_ID
@ FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID
@ OPERAND_BUNDLE_TAGS_BLOCK_ID
@ MODULE_CODE_SOURCE_FILENAME
@ MODULE_CODE_SECTIONNAME
@ MODULE_CODE_ASM_PROPERTY
@ FUNC_CODE_INST_CATCHRET
@ FUNC_CODE_INST_LANDINGPAD
@ FUNC_CODE_INST_EXTRACTVAL
@ FUNC_CODE_INST_CATCHPAD
@ FUNC_CODE_INST_CATCHSWITCH
@ FUNC_CODE_INST_CLEANUPRET
@ FUNC_CODE_DEBUG_RECORD_VALUE
@ FUNC_CODE_INST_LOADATOMIC
@ FUNC_CODE_DEBUG_RECORD_ASSIGN
@ FUNC_CODE_INST_STOREATOMIC
@ FUNC_CODE_INST_BITEXTRACT
@ FUNC_CODE_INST_ATOMICRMW
@ FUNC_CODE_DEBUG_RECORD_DECLARE_VALUE
@ FUNC_CODE_DEBUG_LOC_AGAIN
@ FUNC_CODE_INST_EXTRACTELT
@ FUNC_CODE_INST_INDIRECTBR
@ FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE
@ FUNC_CODE_INST_INSERTVAL
@ FUNC_CODE_DECLAREBLOCKS
@ FUNC_CODE_DEBUG_RECORD_LABEL
@ FUNC_CODE_INST_INSERTELT
@ FUNC_CODE_BLOCKADDR_USERS
@ FUNC_CODE_INST_CLEANUPPAD
@ FUNC_CODE_INST_SHUFFLEVEC
@ FUNC_CODE_INST_UNREACHABLE
@ FUNC_CODE_INST_BITINSERT
@ FUNC_CODE_DEBUG_RECORD_DECLARE
@ FUNC_CODE_OPERAND_BUNDLE
@ FIRST_APPLICATION_ABBREV
@ PARAMATTR_GRP_CODE_ENTRY
initializer< Ty > init(const Ty &Val)
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
LLVM_ABI Error build(ArrayRef< Module * > Mods, SmallVector< char, 0 > &Symtab, StringTableBuilder &StrtabBuilder, BumpPtrAllocator &Alloc)
Fills in Symtab and StrtabBuilder with a valid symbol and string table for Mods.
llvm::unique_function< void(llvm::Expected< T >)> Callback
A Callback<T> is a void function that accepts Expected<T>.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract_or_null(Y &&MD)
Extract a Value from Metadata, allowing null.
LLVM_ABI bool metadataIncludesAllContextSizeInfo()
Whether the alloc memeprof metadata will include context size info for all MIBs.
template LLVM_ABI llvm::DenseMap< LinearFrameId, FrameStat > computeFrameHistogram< LinearFrameId >(llvm::MapVector< CallStackId, llvm::SmallVector< LinearFrameId > > &MemProfCallStackData)
LLVM_ABI bool metadataMayIncludeContextSizeInfo()
Whether the alloc memprof metadata may include context size info for some MIBs (but possibly not all)...
NodeAddr< CodeNode * > Code
void write32le(void *P, uint32_t V)
uint32_t read32be(const void *P)
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
void stable_sort(R &&Range)
StringMapEntry< Value * > ValueName
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
unsigned encode(MaybeAlign A)
Returns a representation of the alignment that encodes undefined as 0.
LLVM_ABI void WriteBitcodeToFile(const Module &M, raw_ostream &Out, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false, ModuleHash *ModHash=nullptr)
Write the specified module to the specified raw output stream.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
LLVM_ABI void writeThinLinkBitcodeToFile(const Module &M, raw_ostream &Out, const ModuleSummaryIndex &Index, const ModuleHash &ModHash)
Write the specified thin link bitcode file (i.e., the minimized bitcode file) to the given raw output...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI void writeIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out, const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex=nullptr, const GVSummaryPtrSet *DecSummaries=nullptr)
Write the specified module summary index to the given raw output stream, where it will be written in ...
LLVM_ABI void embedBitcodeInModule(Module &M, MemoryBufferRef Buf, bool EmbedBitcode, bool EmbedCmdline, const std::vector< uint8_t > &CmdArgs)
If EmbedBitcode is set, save a copy of the llvm IR as data in the __LLVM,__bitcode section (....
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
std::map< std::string, GVSummaryMapTy, std::less<> > ModuleToSummariesForIndexTy
Map of a module name to the GUIDs and summaries we will import from that module.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
AtomicOrdering
Atomic ordering for LLVM's memory model.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt copy(R &&Range, OutputIt Out)
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
bool isBitcode(const unsigned char *BufPtr, const unsigned char *BufEnd)
isBitcode - Return true if the given bytes are the magic bytes for LLVM IR bitcode,...
SmallPtrSet< GlobalValueSummary *, 0 > GVSummaryPtrSet
A set of global value summary pointers.
void consumeError(Error Err)
Consume a Error without doing anything.
LLVM_ABI Error write(DWPWriter &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue, Dwarf64StrOffsetsPromotion StrOffsetsOptValue, raw_pwrite_stream *OS=nullptr)
LLVM_ABI GlobalVariable * collectUsedGlobalVariables(const Module &M, SmallVectorImpl< GlobalValue * > &Vec, bool CompilerUsed)
Given "llvm.used" or "llvm.compiler.used" as a global name, collect the initializer elements of that ...
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
This struct is a compact representation of a valid (non-zero power of two) alignment.
static void set(StorageType &Packed, typename Bitfield::Type Value)
Sets the typed value in the provided Packed value.
Class to accumulate and hold information about a callee.
Flags specific to function summaries.
static constexpr uint32_t RangeWidth
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
static LLVM_ABI const Target * lookupTarget(const Triple &TheTriple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
Struct that holds a reference to a particular GUID in a global value summary.
uint64_t Info
Additional information for the resolution:
enum llvm::WholeProgramDevirtResolution::ByArg::Kind TheKind
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
std::string SingleImplName