33#include "llvm/Config/llvm-config.h"
95 cl::desc(
"Number of metadatas above which we emit an index "
96 "to enable lazy-loading"));
99 cl::desc(
"The threshold (unit M) for flushing LLVM bitcode."));
119 cl::desc(
"Preserve use-list order when writing LLVM bitcode."));
134 VST_BBENTRY_6_ABBREV,
138 CONSTANTS_INTEGER_ABBREV,
139 CONSTANTS_BYTE_ABBREV,
140 CONSTANTS_CE_CAST_Abbrev,
141 CONSTANTS_NULL_Abbrev,
145 FUNCTION_INST_STORE_ABBREV,
146 FUNCTION_INST_UNOP_ABBREV,
147 FUNCTION_INST_UNOP_FLAGS_ABBREV,
148 FUNCTION_INST_BINOP_ABBREV,
149 FUNCTION_INST_BINOP_FLAGS_ABBREV,
150 FUNCTION_INST_CAST_ABBREV,
151 FUNCTION_INST_CAST_FLAGS_ABBREV,
152 FUNCTION_INST_RET_VOID_ABBREV,
153 FUNCTION_INST_RET_VAL_ABBREV,
154 FUNCTION_INST_BR_UNCOND_ABBREV,
155 FUNCTION_INST_BR_COND_ABBREV,
156 FUNCTION_INST_UNREACHABLE_ABBREV,
157 FUNCTION_INST_GEP_ABBREV,
158 FUNCTION_INST_CMP_ABBREV,
159 FUNCTION_INST_CMP_FLAGS_ABBREV,
160 FUNCTION_DEBUG_RECORD_VALUE_ABBREV,
161 FUNCTION_DEBUG_LOC_ABBREV,
166class BitcodeWriterBase {
169 BitstreamWriter &Stream;
171 StringTableBuilder &StrtabBuilder;
176 BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
177 : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
180 void writeModuleVersion();
183void BitcodeWriterBase::writeModuleVersion() {
190class ModuleBitcodeWriterBase :
public BitcodeWriterBase {
199 const ModuleSummaryIndex *Index;
204 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
207 unsigned GlobalValueId;
211 uint64_t VSTOffsetPlaceholder = 0;
216 ModuleBitcodeWriterBase(
const Module &M, StringTableBuilder &StrtabBuilder,
217 BitstreamWriter &Stream,
218 bool ShouldPreserveUseListOrder,
219 const ModuleSummaryIndex *Index)
220 : BitcodeWriterBase(Stream, StrtabBuilder),
M(
M),
223 : ShouldPreserveUseListOrder),
234 for (
const auto &GUIDSummaryLists :
235 Index->sortedGlobalValueSummariesRange())
237 for (
auto &Summary : GUIDSummaryLists.second.getSummaryList())
243 for (auto &CallEdge : FS->calls())
244 if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())
245 assignValueId(CallEdge.first.getGUID());
251 for (auto &RefEdge : FS->refs())
252 if (!RefEdge.haveGVs() || !RefEdge.getValue())
253 assignValueId(RefEdge.getGUID());
258 void writePerModuleGlobalValueSummary();
259 void writeGUIDList();
262 void writePerModuleFunctionSummaryRecord(
263 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
264 unsigned ValueID,
unsigned FSCallsProfileAbbrev,
unsigned CallsiteAbbrev,
265 unsigned AllocAbbrev,
unsigned ContextIdAbbvId,
const Function &
F,
266 DenseMap<CallStackId, LinearCallStackId> &CallStackPos,
268 void writeModuleLevelReferences(
const GlobalVariable &V,
269 SmallVector<uint64_t, 64> &NameVals,
270 unsigned FSModRefsAbbrev,
271 unsigned FSModVTableRefsAbbrev);
274 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
278 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
281 assert(VMI != GUIDToValueIdMap.end() &&
282 "GUID does not have assigned value Id");
287 unsigned getValueId(ValueInfo VI) {
288 if (!
VI.haveGVs() || !
VI.getValue())
289 return getValueId(
VI.getGUID());
293 std::map<GlobalValue::GUID, unsigned> &valueIds() {
return GUIDToValueIdMap; }
297class ModuleBitcodeWriter :
public ModuleBitcodeWriterBase {
308 uint64_t BitcodeStartBit;
313 ModuleBitcodeWriter(
const Module &M, StringTableBuilder &StrtabBuilder,
314 BitstreamWriter &Stream,
bool ShouldPreserveUseListOrder,
315 const ModuleSummaryIndex *Index,
bool GenerateHash,
317 : ModuleBitcodeWriterBase(
M, StrtabBuilder, Stream,
318 ShouldPreserveUseListOrder,
Index),
319 GenerateHash(GenerateHash), ModHash(ModHash),
320 BitcodeStartBit(Stream.GetCurrentBitNo()) {}
326 uint64_t bitcodeStartBit() {
return BitcodeStartBit; }
328 size_t addToStrtab(StringRef Str);
330 void writeAttributeGroupTable();
331 void writeAttributeTable();
332 void writeTypeTable();
334 void writeValueSymbolTableForwardDecl();
335 void writeModuleInfo();
336 void writeValueAsMetadata(
const ValueAsMetadata *MD,
337 SmallVectorImpl<uint64_t> &Record);
338 void writeMDTuple(
const MDTuple *
N, SmallVectorImpl<uint64_t> &Record,
340 unsigned createDILocationAbbrev();
341 void writeDILocation(
const DILocation *
N, SmallVectorImpl<uint64_t> &Record,
343 unsigned createGenericDINodeAbbrev();
345 SmallVectorImpl<uint64_t> &Record,
unsigned &Abbrev);
346 void writeDISubrange(
const DISubrange *
N, SmallVectorImpl<uint64_t> &Record,
349 SmallVectorImpl<uint64_t> &Record,
352 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
356 SmallVectorImpl<uint64_t> &Record,
359 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
361 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
363 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
365 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
367 SmallVectorImpl<uint64_t> &Record,
369 void writeDIFile(
const DIFile *
N, SmallVectorImpl<uint64_t> &Record,
372 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
374 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
376 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
378 SmallVectorImpl<uint64_t> &Record,
381 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
384 void writeDIMacro(
const DIMacro *
N, SmallVectorImpl<uint64_t> &Record,
388 void writeDIArgList(
const DIArgList *
N, SmallVectorImpl<uint64_t> &Record);
389 void writeDIModule(
const DIModule *
N, SmallVectorImpl<uint64_t> &Record,
391 void writeDIAssignID(
const DIAssignID *
N, SmallVectorImpl<uint64_t> &Record,
394 SmallVectorImpl<uint64_t> &Record,
397 SmallVectorImpl<uint64_t> &Record,
400 SmallVectorImpl<uint64_t> &Record,
403 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
405 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
407 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
409 SmallVectorImpl<uint64_t> &Record,
412 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
414 SmallVectorImpl<uint64_t> &Record,
416 unsigned createNamedMetadataAbbrev();
417 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
418 unsigned createMetadataStringsAbbrev();
420 SmallVectorImpl<uint64_t> &Record);
422 SmallVectorImpl<uint64_t> &Record,
423 std::vector<unsigned> *MDAbbrevs =
nullptr,
424 std::vector<uint64_t> *IndexPos =
nullptr);
425 void writeModuleMetadata();
426 void writeFunctionMetadata(
const Function &
F);
427 void writeFunctionMetadataAttachment(
const Function &
F);
428 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
429 const GlobalObject &GO);
430 void writeModuleMetadataKinds();
431 void writeOperandBundleTags();
432 void writeSyncScopeNames();
433 void writeConstants(
unsigned FirstVal,
unsigned LastVal,
bool isGlobal);
434 void writeModuleConstants();
435 bool pushValueAndType(
const Value *V,
unsigned InstID,
436 SmallVectorImpl<unsigned> &Vals);
437 bool pushValueOrMetadata(
const Value *V,
unsigned InstID,
438 SmallVectorImpl<unsigned> &Vals);
439 void writeOperandBundles(
const CallBase &CB,
unsigned InstID);
440 void pushValue(
const Value *V,
unsigned InstID,
441 SmallVectorImpl<unsigned> &Vals);
442 void pushValueSigned(
const Value *V,
unsigned InstID,
443 SmallVectorImpl<uint64_t> &Vals);
444 void writeInstruction(
const Instruction &
I,
unsigned InstID,
445 SmallVectorImpl<unsigned> &Vals);
446 void writeFunctionLevelValueSymbolTable(
const ValueSymbolTable &VST);
447 void writeGlobalValueSymbolTable(
448 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
449 void writeUseList(UseListOrder &&Order);
450 void writeUseListBlock(
const Function *
F);
452 writeFunction(
const Function &
F,
453 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
454 void writeBlockInfo();
455 void writeModuleHash(StringRef View);
458 return unsigned(SSID);
461 unsigned getEncodedAlign(MaybeAlign Alignment) {
return encode(Alignment); }
465class IndexBitcodeWriter :
public BitcodeWriterBase {
467 const ModuleSummaryIndex &
Index;
480 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
484 std::vector<uint64_t> StackIds;
489 DenseMap<unsigned, unsigned> StackIdIndicesToIndex;
492 unsigned GlobalValueId = 0;
496 DenseMap<StringRef, uint64_t> ModuleIdMap;
506 BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
507 const ModuleSummaryIndex &Index,
510 : BitcodeWriterBase(Stream, StrtabBuilder),
Index(
Index),
511 DecSummaries(DecSummaries),
512 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
516 auto RecordStackIdReference = [&](
unsigned StackIdIndex) {
521 StackIdIndicesToIndex.
insert({StackIdIndex, StackIds.size()});
523 StackIds.push_back(
Index.getStackIdAtIndex(StackIdIndex));
530 forEachSummary([&](GVInfo
I,
bool IsAliasee) {
531 GUIDToValueIdMap[
I.first] = ++GlobalValueId;
543 for (
auto &CI :
FS->callsites()) {
554 if (CI.StackIdIndices.empty()) {
555 GUIDToValueIdMap[CI.Callee.getGUID()] = ++GlobalValueId;
558 for (
auto Idx : CI.StackIdIndices)
559 RecordStackIdReference(Idx);
562 for (
auto &AI :
FS->allocs())
563 for (
auto &MIB : AI.MIBs)
564 for (
auto Idx : MIB.StackIdIndices)
565 RecordStackIdReference(Idx);
571 using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
576 template<
typename Functor>
577 void forEachSummary(Functor Callback) {
578 if (ModuleToSummariesForIndex) {
579 for (
auto &M : *ModuleToSummariesForIndex)
580 for (
auto &Summary :
M.second) {
586 Callback({AS->getAliaseeGUID(), &AS->getAliasee()},
true);
590 for (
const auto &Summaries :
Index.sortedGlobalValueSummariesRange())
591 for (
auto &Summary : Summaries.second.getSummaryList())
600 template <
typename Functor>
void forEachModule(Functor Callback) {
601 if (ModuleToSummariesForIndex) {
602 for (
const auto &M : *ModuleToSummariesForIndex) {
603 const auto &MPI =
Index.modulePaths().find(
M.first);
604 if (MPI ==
Index.modulePaths().end()) {
608 assert(ModuleToSummariesForIndex->size() == 1);
618 std::vector<StringRef> ModulePaths;
619 for (
auto &[ModPath,
_] :
Index.modulePaths())
620 ModulePaths.push_back(ModPath);
622 for (
auto &ModPath : ModulePaths)
631 void writeModStrings();
632 void writeCombinedGlobalValueSummary();
635 auto VMI = GUIDToValueIdMap.find(ValGUID);
636 if (VMI == GUIDToValueIdMap.end())
641 std::map<GlobalValue::GUID, unsigned> &valueIds() {
return GUIDToValueIdMap; }
676 case Instruction::Add:
678 case Instruction::Sub:
680 case Instruction::Mul:
683 case Instruction::FDiv:
686 case Instruction::FRem:
698 unsigned Encoding = 0;
699 switch (
I.getOperation()) {
772 if (
I.isElementwise())
807 case Attribute::Alignment:
809 case Attribute::AllocAlign:
811 case Attribute::AllocSize:
813 case Attribute::AlwaysInline:
815 case Attribute::Builtin:
817 case Attribute::ByVal:
819 case Attribute::Convergent:
821 case Attribute::InAlloca:
823 case Attribute::Cold:
825 case Attribute::DisableSanitizerInstrumentation:
827 case Attribute::FnRetThunkExtern:
829 case Attribute::Flatten:
833 case Attribute::ElementType:
835 case Attribute::HybridPatchable:
837 case Attribute::InlineHint:
839 case Attribute::InReg:
841 case Attribute::JumpTable:
843 case Attribute::MinSize:
845 case Attribute::AllocatedPointer:
847 case Attribute::AllocKind:
849 case Attribute::Memory:
851 case Attribute::NoFPClass:
853 case Attribute::Naked:
855 case Attribute::Nest:
857 case Attribute::NoAlias:
859 case Attribute::NoBuiltin:
861 case Attribute::NoCallback:
863 case Attribute::NoDivergenceSource:
865 case Attribute::NoDuplicate:
867 case Attribute::NoFree:
869 case Attribute::NoImplicitFloat:
871 case Attribute::NoInline:
873 case Attribute::NoRecurse:
875 case Attribute::NoMerge:
877 case Attribute::NonLazyBind:
879 case Attribute::NonNull:
881 case Attribute::Dereferenceable:
883 case Attribute::DereferenceableOrNull:
885 case Attribute::NoRedZone:
887 case Attribute::NoReturn:
889 case Attribute::NoSync:
891 case Attribute::NoCfCheck:
893 case Attribute::NoProfile:
895 case Attribute::SkipProfile:
897 case Attribute::NoUnwind:
899 case Attribute::NoSanitizeBounds:
901 case Attribute::NoSanitizeCoverage:
903 case Attribute::NullPointerIsValid:
905 case Attribute::OptimizeForDebugging:
907 case Attribute::OptForFuzzing:
909 case Attribute::OptimizeForSize:
911 case Attribute::OptimizeNone:
913 case Attribute::ReadNone:
915 case Attribute::ReadOnly:
917 case Attribute::Returned:
919 case Attribute::ReturnsTwice:
921 case Attribute::SExt:
923 case Attribute::Speculatable:
925 case Attribute::StackAlignment:
927 case Attribute::StackProtect:
929 case Attribute::StackProtectReq:
931 case Attribute::StackProtectStrong:
933 case Attribute::SafeStack:
935 case Attribute::ShadowCallStack:
937 case Attribute::StrictFP:
939 case Attribute::StructRet:
941 case Attribute::SanitizeAddress:
943 case Attribute::SanitizeAllocToken:
945 case Attribute::SanitizeHWAddress:
947 case Attribute::SanitizeThread:
949 case Attribute::SanitizeType:
951 case Attribute::SanitizeMemory:
953 case Attribute::SanitizeNumericalStability:
955 case Attribute::SanitizeRealtime:
957 case Attribute::SanitizeRealtimeBlocking:
959 case Attribute::SpeculativeLoadHardening:
961 case Attribute::SwiftError:
963 case Attribute::SwiftSelf:
965 case Attribute::SwiftAsync:
967 case Attribute::UWTable:
969 case Attribute::VScaleRange:
971 case Attribute::WillReturn:
973 case Attribute::WriteOnly:
975 case Attribute::ZExt:
977 case Attribute::ImmArg:
979 case Attribute::SanitizeMemTag:
981 case Attribute::Preallocated:
983 case Attribute::NoUndef:
985 case Attribute::ByRef:
987 case Attribute::MustProgress:
989 case Attribute::PresplitCoroutine:
991 case Attribute::Writable:
993 case Attribute::CoroDestroyOnlyWhenComplete:
995 case Attribute::CoroElideSafe:
997 case Attribute::DeadOnUnwind:
999 case Attribute::Range:
1001 case Attribute::Initializes:
1003 case Attribute::NoExt:
1005 case Attribute::Captures:
1007 case Attribute::DeadOnReturn:
1009 case Attribute::NoCreateUndefOrPoison:
1011 case Attribute::DenormalFPEnv:
1013 case Attribute::NoOutline:
1015 case Attribute::NoIPA:
1030 if ((int64_t)V >= 0)
1041 unsigned NumWords =
A.getActiveWords();
1042 const uint64_t *RawData =
A.getRawData();
1043 for (
unsigned i = 0; i < NumWords; i++)
1063void ModuleBitcodeWriter::writeAttributeGroupTable() {
1064 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
1066 if (AttrGrps.empty())
return;
1070 SmallVector<uint64_t, 64>
Record;
1072 unsigned AttrListIndex = Pair.first;
1073 AttributeSet AS = Pair.second;
1075 Record.push_back(AttrListIndex);
1078 if (Attr.isEnumAttribute()) {
1081 }
else if (Attr.isIntAttribute()) {
1083 Attribute::AttrKind
Kind = Attr.getKindAsEnum();
1085 if (Kind == Attribute::Memory) {
1090 Record.push_back(Attr.getValueAsInt());
1092 }
else if (Attr.isStringAttribute()) {
1093 StringRef
Kind = Attr.getKindAsString();
1094 StringRef Val = Attr.getValueAsString();
1103 }
else if (Attr.isTypeAttribute()) {
1104 Type *Ty = Attr.getValueAsType();
1105 Record.push_back(Ty ? 6 : 5);
1109 }
else if (Attr.isConstantRangeAttribute()) {
1115 assert(Attr.isConstantRangeListAttribute());
1121 for (
auto &CR : Val)
1133void ModuleBitcodeWriter::writeAttributeTable() {
1135 if (
Attrs.empty())
return;
1139 SmallVector<uint64_t, 64>
Record;
1140 for (
const AttributeList &AL : Attrs) {
1141 for (
unsigned i :
AL.indexes()) {
1142 AttributeSet AS =
AL.getAttributes(i);
1155void ModuleBitcodeWriter::writeTypeTable() {
1159 SmallVector<uint64_t, 64> TypeVals;
1164 auto Abbv = std::make_shared<BitCodeAbbrev>();
1166 Abbv->Add(BitCodeAbbrevOp(0));
1167 unsigned OpaquePtrAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1170 Abbv = std::make_shared<BitCodeAbbrev>();
1175 unsigned FunctionAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1178 Abbv = std::make_shared<BitCodeAbbrev>();
1183 unsigned StructAnonAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1186 Abbv = std::make_shared<BitCodeAbbrev>();
1190 unsigned StructNameAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1193 Abbv = std::make_shared<BitCodeAbbrev>();
1198 unsigned StructNamedAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1201 Abbv = std::make_shared<BitCodeAbbrev>();
1205 unsigned ArrayAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1213 for (
Type *
T : TypeList) {
1214 int AbbrevToUse = 0;
1217 switch (
T->getTypeID()) {
1227 case Type::MetadataTyID:
1232 case Type::ByteTyID:
1237 case Type::IntegerTyID:
1242 case Type::PointerTyID: {
1249 AbbrevToUse = OpaquePtrAbbrev;
1252 case Type::FunctionTyID: {
1258 for (
unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
1260 AbbrevToUse = FunctionAbbrev;
1263 case Type::StructTyID: {
1268 for (
Type *ET :
ST->elements())
1271 if (
ST->isLiteral()) {
1273 AbbrevToUse = StructAnonAbbrev;
1275 if (
ST->isOpaque()) {
1279 AbbrevToUse = StructNamedAbbrev;
1283 if (!
ST->getName().empty())
1289 case Type::ArrayTyID: {
1293 TypeVals.
push_back(AT->getNumElements());
1295 AbbrevToUse = ArrayAbbrev;
1298 case Type::FixedVectorTyID:
1299 case Type::ScalableVectorTyID: {
1304 TypeVals.
push_back(VT->getElementCount().getKnownMinValue());
1310 case Type::TargetExtTyID: {
1316 for (
Type *InnerTy :
TET->type_params())
1321 case Type::TypedPointerTyID:
1326 Stream.
EmitRecord(Code, TypeVals, AbbrevToUse);
1367 RawFlags |= Flags.ReadNone;
1368 RawFlags |= (Flags.ReadOnly << 1);
1369 RawFlags |= (Flags.NoRecurse << 2);
1370 RawFlags |= (Flags.ReturnDoesNotAlias << 3);
1371 RawFlags |= (Flags.NoInline << 4);
1372 RawFlags |= (Flags.AlwaysInline << 5);
1373 RawFlags |= (Flags.NoUnwind << 6);
1374 RawFlags |= (Flags.MayThrow << 7);
1375 RawFlags |= (Flags.HasUnknownCall << 8);
1376 RawFlags |= (Flags.MustBeUnreachable << 9);
1383 bool ImportAsDecl =
false) {
1386 RawFlags |= Flags.NotEligibleToImport;
1387 RawFlags |= (Flags.Live << 1);
1388 RawFlags |= (Flags.DSOLocal << 2);
1389 RawFlags |= (Flags.CanAutoHide << 3);
1394 RawFlags = (RawFlags << 4) | Flags.Linkage;
1396 RawFlags |= (Flags.Visibility << 8);
1398 unsigned ImportType = Flags.ImportType | ImportAsDecl;
1399 RawFlags |= (ImportType << 10);
1401 RawFlags |= (Flags.NoRenameOnPromotion << 11);
1407 uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) |
1408 (Flags.Constant << 2) | Flags.VCallVisibility << 3;
1451 switch (
C.getSelectionKind()) {
1475size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1478 return StrtabBuilder.
add(Str);
1481void ModuleBitcodeWriter::writeComdats() {
1496void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
1501 auto Abbv = std::make_shared<BitCodeAbbrev>();
1507 unsigned VSTOffsetAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1523 bool isChar6 =
true;
1524 for (
char C : Str) {
1527 if ((
unsigned char)
C & 128)
1536static_assert(
sizeof(GlobalValue::SanitizerMetadata) <=
sizeof(unsigned),
1537 "Sanitizer Metadata is too large for naive serialization.");
1540 return Meta.NoAddress | (
Meta.NoHWAddress << 1) |
1541 (
Meta.Memtag << 2) | (
Meta.IsDynInit << 3);
1547void ModuleBitcodeWriter::writeModuleInfo() {
1549 if (!
M.getTargetTriple().empty())
1551 M.getTargetTriple().str(), 0 );
1552 const std::string &
DL =
M.getDataLayoutStr();
1556 for (
const Module::GlobalAsmFragment &Frag :
M.getModuleInlineAsm()) {
1558 Frag.Props.getAsStrings();
1571 std::map<std::string, unsigned> SectionMap;
1572 std::map<std::string, unsigned> GCMap;
1573 MaybeAlign MaxGVarAlignment;
1574 unsigned MaxGlobalType = 0;
1575 for (
const GlobalVariable &GV :
M.globals()) {
1576 if (MaybeAlign
A = GV.getAlign())
1577 MaxGVarAlignment = !MaxGVarAlignment ? *
A : std::max(*MaxGVarAlignment, *
A);
1578 MaxGlobalType = std::max(MaxGlobalType, VE.
getTypeID(GV.getValueType()));
1579 if (GV.hasSection()) {
1581 unsigned &
Entry = SectionMap[std::string(GV.getSection())];
1585 Entry = SectionMap.size();
1589 for (
const Function &
F : M) {
1590 if (
F.hasSection()) {
1592 unsigned &
Entry = SectionMap[std::string(
F.getSection())];
1596 Entry = SectionMap.size();
1601 unsigned &
Entry = GCMap[
F.getGC()];
1605 Entry = GCMap.size();
1611 unsigned SimpleGVarAbbrev = 0;
1612 if (!
M.global_empty()) {
1614 auto Abbv = std::make_shared<BitCodeAbbrev>();
1625 if (!MaxGVarAlignment)
1626 Abbv->Add(BitCodeAbbrevOp(0));
1628 unsigned MaxEncAlignment = getEncodedAlign(MaxGVarAlignment);
1632 if (SectionMap.empty())
1633 Abbv->Add(BitCodeAbbrevOp(0));
1638 SimpleGVarAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1652 auto Abbv = std::make_shared<BitCodeAbbrev>();
1655 Abbv->Add(AbbrevOpToUse);
1656 unsigned FilenameAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1658 for (
const auto P :
M.getSourceFileName())
1669 for (
const GlobalVariable &GV :
M.globals()) {
1670 unsigned AbbrevToUse = 0;
1676 Vals.
push_back(addToStrtab(GV.getName()));
1679 Vals.
push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1683 Vals.
push_back(getEncodedAlign(GV.getAlign()));
1684 Vals.
push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]
1686 if (GV.isThreadLocal() ||
1688 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1689 GV.isExternallyInitialized() ||
1691 GV.hasComdat() || GV.hasAttributes() || GV.isDSOLocal() ||
1692 GV.hasPartition() || GV.hasSanitizerMetadata() || GV.getCodeModel()) {
1696 Vals.
push_back(GV.isExternallyInitialized());
1700 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1704 Vals.
push_back(addToStrtab(GV.getPartition()));
1705 Vals.
push_back(GV.getPartition().size());
1708 GV.getSanitizerMetadata())
1712 AbbrevToUse = SimpleGVarAbbrev;
1720 for (
const Function &
F : M) {
1733 Vals.
push_back(getEncodedAlign(
F.getAlign()));
1734 Vals.
push_back(
F.hasSection() ? SectionMap[std::string(
F.getSection())]
1746 F.hasPersonalityFn() ? (VE.
getValueID(
F.getPersonalityFn()) + 1) : 0);
1750 Vals.
push_back(addToStrtab(
F.getPartition()));
1752 Vals.
push_back(getEncodedAlign(
F.getPreferredAlignment()));
1754 unsigned AbbrevToUse = 0;
1760 for (
const GlobalAlias &
A :
M.aliases()) {
1767 Vals.
push_back(
A.getType()->getAddressSpace());
1775 Vals.
push_back(addToStrtab(
A.getPartition()));
1778 unsigned AbbrevToUse = 0;
1784 for (
const GlobalIFunc &
I :
M.ifuncs()) {
1790 Vals.
push_back(
I.getType()->getAddressSpace());
1795 Vals.
push_back(addToStrtab(
I.getPartition()));
1801 writeValueSymbolTableForwardDecl();
1808 if (OBO->hasNoSignedWrap())
1810 if (OBO->hasNoUnsignedWrap())
1816 if (PDI->isDisjoint())
1819 if (FPMO->hasAllowReassoc())
1821 if (FPMO->hasNoNaNs())
1823 if (FPMO->hasNoInfs())
1825 if (FPMO->hasNoSignedZeros())
1827 if (FPMO->hasAllowReciprocal())
1829 if (FPMO->hasAllowContract())
1831 if (FPMO->hasApproxFunc())
1837 if (NNI->hasNonNeg())
1841 if (NNI->hasNonNeg())
1844 if (TI->hasNoSignedWrap())
1846 if (TI->hasNoUnsignedWrap())
1849 if (
GEP->isInBounds())
1851 if (
GEP->hasNoUnsignedSignedWrap())
1853 if (
GEP->hasNoUnsignedWrap())
1856 if (ICmp->hasSameSign())
1863void ModuleBitcodeWriter::writeValueAsMetadata(
1864 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
1873void ModuleBitcodeWriter::writeMDTuple(
const MDTuple *
N,
1874 SmallVectorImpl<uint64_t> &Record,
1876 for (
const MDOperand &MDO :
N->operands()) {
1879 "Unexpected function-local metadata");
1888unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
1891 auto Abbv = std::make_shared<BitCodeAbbrev>();
1904void ModuleBitcodeWriter::writeDILocation(
const DILocation *
N,
1905 SmallVectorImpl<uint64_t> &Record,
1908 Abbrev = createDILocationAbbrev();
1910 Record.push_back(
N->isDistinct());
1911 Record.push_back(
N->getLine());
1912 Record.push_back(
N->getColumn());
1915 Record.push_back(
N->isImplicitCode());
1916 Record.push_back(
N->getAtomGroup());
1917 Record.push_back(
N->getAtomRank());
1922unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1925 auto Abbv = std::make_shared<BitCodeAbbrev>();
1936void ModuleBitcodeWriter::writeGenericDINode(
const GenericDINode *
N,
1937 SmallVectorImpl<uint64_t> &Record,
1940 Abbrev = createGenericDINodeAbbrev();
1942 Record.push_back(
N->isDistinct());
1943 Record.push_back(
N->getTag());
1946 for (
auto &
I :
N->operands())
1953void ModuleBitcodeWriter::writeDISubrange(
const DISubrange *
N,
1954 SmallVectorImpl<uint64_t> &Record,
1956 const uint64_t
Version = 2 << 1;
1967void ModuleBitcodeWriter::writeDIGenericSubrange(
1968 const DIGenericSubrange *
N, SmallVectorImpl<uint64_t> &Record,
1970 Record.push_back((uint64_t)
N->isDistinct());
1980void ModuleBitcodeWriter::writeDIEnumerator(
const DIEnumerator *
N,
1981 SmallVectorImpl<uint64_t> &Record,
1983 const uint64_t IsBigInt = 1 << 2;
1984 Record.push_back(IsBigInt | (
N->isUnsigned() << 1) |
N->isDistinct());
1985 Record.push_back(
N->getValue().getBitWidth());
1993void ModuleBitcodeWriter::writeDIBasicType(
const DIBasicType *
N,
1994 SmallVectorImpl<uint64_t> &Record,
1996 const unsigned SizeIsMetadata = 0x2;
1997 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
1998 Record.push_back(
N->getTag());
2001 Record.push_back(
N->getAlignInBits());
2002 Record.push_back(
N->getEncoding());
2003 Record.push_back(
N->getFlags());
2004 Record.push_back(
N->getNumExtraInhabitants());
2005 Record.push_back(
N->getDataSizeInBits());
2007 Record.push_back(
N->getLine());
2014void ModuleBitcodeWriter::writeDIFixedPointType(
2015 const DIFixedPointType *
N, SmallVectorImpl<uint64_t> &Record,
2017 const unsigned SizeIsMetadata = 0x2;
2018 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2019 Record.push_back(
N->getTag());
2022 Record.push_back(
N->getAlignInBits());
2023 Record.push_back(
N->getEncoding());
2024 Record.push_back(
N->getFlags());
2025 Record.push_back(
N->getKind());
2026 Record.push_back(
N->getFactorRaw());
2028 auto WriteWideInt = [&](
const APInt &
Value) {
2031 uint64_t NumWords =
Value.getActiveWords();
2032 uint64_t
Encoded = (NumWords << 32) |
Value.getBitWidth();
2033 Record.push_back(Encoded);
2037 WriteWideInt(
N->getNumeratorRaw());
2038 WriteWideInt(
N->getDenominatorRaw());
2041 Record.push_back(
N->getLine());
2048void ModuleBitcodeWriter::writeDIStringType(
const DIStringType *
N,
2049 SmallVectorImpl<uint64_t> &Record,
2051 const unsigned SizeIsMetadata = 0x2;
2052 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2053 Record.push_back(
N->getTag());
2059 Record.push_back(
N->getAlignInBits());
2060 Record.push_back(
N->getEncoding());
2066void ModuleBitcodeWriter::writeDIDerivedType(
const DIDerivedType *
N,
2067 SmallVectorImpl<uint64_t> &Record,
2069 const unsigned SizeIsMetadata = 0x2;
2070 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2071 Record.push_back(
N->getTag());
2074 Record.push_back(
N->getLine());
2078 Record.push_back(
N->getAlignInBits());
2080 Record.push_back(
N->getFlags());
2085 if (
const auto &DWARFAddressSpace =
N->getDWARFAddressSpace())
2086 Record.push_back(*DWARFAddressSpace + 1);
2092 if (
auto PtrAuthData =
N->getPtrAuthData())
2093 Record.push_back(PtrAuthData->RawData);
2101void ModuleBitcodeWriter::writeDISubrangeType(
const DISubrangeType *
N,
2102 SmallVectorImpl<uint64_t> &Record,
2104 const unsigned SizeIsMetadata = 0x2;
2105 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2108 Record.push_back(
N->getLine());
2111 Record.push_back(
N->getAlignInBits());
2112 Record.push_back(
N->getFlags());
2123void ModuleBitcodeWriter::writeDICompositeType(
2124 const DICompositeType *
N, SmallVectorImpl<uint64_t> &Record,
2126 const unsigned IsNotUsedInOldTypeRef = 0x2;
2127 const unsigned SizeIsMetadata = 0x4;
2128 Record.push_back(SizeIsMetadata | IsNotUsedInOldTypeRef |
2129 (
unsigned)
N->isDistinct());
2130 Record.push_back(
N->getTag());
2133 Record.push_back(
N->getLine());
2137 Record.push_back(
N->getAlignInBits());
2139 Record.push_back(
N->getFlags());
2141 Record.push_back(
N->getRuntimeLang());
2151 Record.push_back(
N->getNumExtraInhabitants());
2161void ModuleBitcodeWriter::writeDISubroutineType(
2162 const DISubroutineType *
N, SmallVectorImpl<uint64_t> &Record,
2164 const unsigned HasNoOldTypeRefs = 0x2;
2165 Record.push_back(HasNoOldTypeRefs | (
unsigned)
N->isDistinct());
2166 Record.push_back(
N->getFlags());
2174void ModuleBitcodeWriter::writeDIFile(
const DIFile *
N,
2175 SmallVectorImpl<uint64_t> &Record,
2177 Record.push_back(
N->isDistinct());
2180 if (
N->getRawChecksum()) {
2181 Record.push_back(
N->getRawChecksum()->Kind);
2189 auto Source =
N->getRawSource();
2197void ModuleBitcodeWriter::writeDICompileUnit(
const DICompileUnit *
N,
2198 SmallVectorImpl<uint64_t> &Record,
2200 assert(
N->isDistinct() &&
"Expected distinct compile units");
2203 auto Lang =
N->getSourceLanguage();
2204 Record.push_back(Lang.getName());
2207 if (Lang.hasVersionedName())
2208 Record.back() ^= (uint64_t(1) << 63);
2212 Record.push_back(
N->isOptimized());
2214 Record.push_back(
N->getRuntimeVersion());
2216 Record.push_back(
N->getEmissionKind());
2222 Record.push_back(
N->getDWOId());
2224 Record.push_back(
N->getSplitDebugInlining());
2225 Record.push_back(
N->getDebugInfoForProfiling());
2226 Record.push_back((
unsigned)
N->getNameTableKind());
2227 Record.push_back(
N->getRangesBaseAddress());
2230 Record.push_back(Lang.hasVersionedName() ? Lang.getVersion() : 0);
2231 Record.push_back(Lang.getDialect());
2237void ModuleBitcodeWriter::writeDISubprogram(
const DISubprogram *
N,
2238 SmallVectorImpl<uint64_t> &Record,
2240 const uint64_t HasUnitFlag = 1 << 1;
2241 const uint64_t HasSPFlagsFlag = 1 << 2;
2242 Record.push_back(uint64_t(
N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
2247 Record.push_back(
N->getLine());
2249 Record.push_back(
N->getScopeLine());
2251 Record.push_back(
N->getSPFlags());
2252 Record.push_back(
N->getVirtualIndex());
2253 Record.push_back(
N->getFlags());
2258 Record.push_back(
N->getThisAdjustment());
2262 Record.push_back(
N->getKeyInstructionsEnabled());
2268void ModuleBitcodeWriter::writeDILexicalBlock(
const DILexicalBlock *
N,
2269 SmallVectorImpl<uint64_t> &Record,
2271 Record.push_back(
N->isDistinct());
2274 Record.push_back(
N->getLine());
2275 Record.push_back(
N->getColumn());
2281void ModuleBitcodeWriter::writeDILexicalBlockFile(
2282 const DILexicalBlockFile *
N, SmallVectorImpl<uint64_t> &Record,
2284 Record.push_back(
N->isDistinct());
2287 Record.push_back(
N->getDiscriminator());
2293void ModuleBitcodeWriter::writeDICommonBlock(
const DICommonBlock *
N,
2294 SmallVectorImpl<uint64_t> &Record,
2296 Record.push_back(
N->isDistinct());
2301 Record.push_back(
N->getLineNo());
2307void ModuleBitcodeWriter::writeDINamespace(
const DINamespace *
N,
2308 SmallVectorImpl<uint64_t> &Record,
2310 Record.push_back(
N->isDistinct() |
N->getExportSymbols() << 1);
2318void ModuleBitcodeWriter::writeDIMacro(
const DIMacro *
N,
2319 SmallVectorImpl<uint64_t> &Record,
2321 Record.push_back(
N->isDistinct());
2322 Record.push_back(
N->getMacinfoType());
2323 Record.push_back(
N->getLine());
2331void ModuleBitcodeWriter::writeDIMacroFile(
const DIMacroFile *
N,
2332 SmallVectorImpl<uint64_t> &Record,
2334 Record.push_back(
N->isDistinct());
2335 Record.push_back(
N->getMacinfoType());
2336 Record.push_back(
N->getLine());
2344void ModuleBitcodeWriter::writeDIArgList(
const DIArgList *
N,
2345 SmallVectorImpl<uint64_t> &Record) {
2346 Record.reserve(
N->getArgs().size());
2347 for (ValueAsMetadata *MD :
N->getArgs())
2354void ModuleBitcodeWriter::writeDIModule(
const DIModule *
N,
2355 SmallVectorImpl<uint64_t> &Record,
2357 Record.push_back(
N->isDistinct());
2358 for (
auto &
I :
N->operands())
2360 Record.push_back(
N->getLineNo());
2361 Record.push_back(
N->getIsDecl());
2367void ModuleBitcodeWriter::writeDIAssignID(
const DIAssignID *
N,
2368 SmallVectorImpl<uint64_t> &Record,
2371 Record.push_back(
N->isDistinct());
2376void ModuleBitcodeWriter::writeDITemplateTypeParameter(
2377 const DITemplateTypeParameter *
N, SmallVectorImpl<uint64_t> &Record,
2379 Record.push_back(
N->isDistinct());
2382 Record.push_back(
N->isDefault());
2388void ModuleBitcodeWriter::writeDITemplateValueParameter(
2389 const DITemplateValueParameter *
N, SmallVectorImpl<uint64_t> &Record,
2391 Record.push_back(
N->isDistinct());
2392 Record.push_back(
N->getTag());
2395 Record.push_back(
N->isDefault());
2402void ModuleBitcodeWriter::writeDIGlobalVariable(
2403 const DIGlobalVariable *
N, SmallVectorImpl<uint64_t> &Record,
2405 const uint64_t
Version = 2 << 1;
2411 Record.push_back(
N->getLine());
2413 Record.push_back(
N->isLocalToUnit());
2414 Record.push_back(
N->isDefinition());
2417 Record.push_back(
N->getAlignInBits());
2424void ModuleBitcodeWriter::writeDILocalVariable(
2425 const DILocalVariable *
N, SmallVectorImpl<uint64_t> &Record,
2440 const uint64_t HasAlignmentFlag = 1 << 1;
2441 Record.push_back((uint64_t)
N->isDistinct() | HasAlignmentFlag);
2445 Record.push_back(
N->getLine());
2447 Record.push_back(
N->getArg());
2448 Record.push_back(
N->getFlags());
2449 Record.push_back(
N->getAlignInBits());
2456void ModuleBitcodeWriter::writeDILabel(
2457 const DILabel *
N, SmallVectorImpl<uint64_t> &Record,
2459 uint64_t IsArtificialFlag = uint64_t(
N->isArtificial()) << 1;
2460 Record.push_back((uint64_t)
N->isDistinct() | IsArtificialFlag);
2464 Record.push_back(
N->getLine());
2465 Record.push_back(
N->getColumn());
2466 Record.push_back(
N->getCoroSuspendIdx().has_value()
2467 ? (uint64_t)
N->getCoroSuspendIdx().value()
2468 : std::numeric_limits<uint64_t>::max());
2474void ModuleBitcodeWriter::writeDIExpression(
const DIExpression *
N,
2475 SmallVectorImpl<uint64_t> &Record,
2477 Record.reserve(
N->getElements().size() + 1);
2478 const uint64_t
Version = 3 << 1;
2480 Record.append(
N->elements_begin(),
N->elements_end());
2486void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
2487 const DIGlobalVariableExpression *
N, SmallVectorImpl<uint64_t> &Record,
2489 Record.push_back(
N->isDistinct());
2497void ModuleBitcodeWriter::writeDIObjCProperty(
const DIObjCProperty *
N,
2498 SmallVectorImpl<uint64_t> &Record,
2500 Record.push_back(
N->isDistinct());
2503 Record.push_back(
N->getLine());
2506 Record.push_back(
N->getAttributes());
2513void ModuleBitcodeWriter::writeDIImportedEntity(
2514 const DIImportedEntity *
N, SmallVectorImpl<uint64_t> &Record,
2516 Record.push_back(
N->isDistinct());
2517 Record.push_back(
N->getTag());
2520 Record.push_back(
N->getLine());
2529unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
2530 auto Abbv = std::make_shared<BitCodeAbbrev>();
2537void ModuleBitcodeWriter::writeNamedMetadata(
2538 SmallVectorImpl<uint64_t> &Record) {
2539 if (
M.named_metadata_empty())
2542 unsigned Abbrev = createNamedMetadataAbbrev();
2543 for (
const NamedMDNode &NMD :
M.named_metadata()) {
2545 StringRef Str = NMD.getName();
2546 Record.append(Str.bytes_begin(), Str.bytes_end());
2551 for (
const MDNode *
N : NMD.operands())
2558unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
2559 auto Abbv = std::make_shared<BitCodeAbbrev>();
2571void ModuleBitcodeWriter::writeMetadataStrings(
2573 if (Strings.
empty())
2581 SmallString<256> Blob;
2583 BitstreamWriter
W(Blob);
2603#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
2604#include "llvm/IR/Metadata.def"
2608void ModuleBitcodeWriter::writeMetadataRecords(
2610 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
2615#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
2616#include "llvm/IR/Metadata.def"
2622 assert(
N->isResolved() &&
"Expected forward references to be resolved");
2624 switch (
N->getMetadataID()) {
2627#define HANDLE_MDNODE_LEAF(CLASS) \
2628 case Metadata::CLASS##Kind: \
2630 write##CLASS(cast<CLASS>(N), Record, \
2631 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
2633 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
2635#include "llvm/IR/Metadata.def"
2646void ModuleBitcodeWriter::writeModuleMetadata() {
2647 if (!VE.
hasMDs() &&
M.named_metadata_empty())
2651 SmallVector<uint64_t, 64>
Record;
2655 std::vector<unsigned> MDAbbrevs;
2658 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
2659 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
2660 createGenericDINodeAbbrev();
2662 auto Abbv = std::make_shared<BitCodeAbbrev>();
2666 unsigned OffsetAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
2668 Abbv = std::make_shared<BitCodeAbbrev>();
2672 unsigned IndexAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
2684 uint64_t Vals[] = {0, 0};
2694 std::vector<uint64_t> IndexPos;
2698 writeMetadataRecords(VE.
getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2709 uint64_t PreviousValue = IndexOffsetRecordBitPos;
2710 for (
auto &Elt : IndexPos) {
2711 auto EltDelta = Elt - PreviousValue;
2712 PreviousValue = Elt;
2721 writeNamedMetadata(Record);
2723 auto AddDeclAttachedMetadata = [&](
const GlobalObject &GO) {
2724 SmallVector<uint64_t, 4>
Record;
2726 pushGlobalMetadataAttachment(Record, GO);
2729 for (
const Function &
F : M)
2730 if (
F.isDeclaration() &&
F.hasMetadata())
2731 AddDeclAttachedMetadata(
F);
2732 for (
const GlobalIFunc &GI :
M.ifuncs())
2733 if (GI.hasMetadata())
2734 AddDeclAttachedMetadata(GI);
2737 for (
const GlobalVariable &GV :
M.globals())
2738 if (GV.hasMetadata())
2739 AddDeclAttachedMetadata(GV);
2744void ModuleBitcodeWriter::writeFunctionMetadata(
const Function &
F) {
2749 SmallVector<uint64_t, 64>
Record;
2755void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2756 SmallVectorImpl<uint64_t> &Record,
const GlobalObject &GO) {
2760 for (
const auto &
I : MDs) {
2766void ModuleBitcodeWriter::writeFunctionMetadataAttachment(
const Function &
F) {
2769 SmallVector<uint64_t, 64>
Record;
2771 if (
F.hasMetadata()) {
2772 pushGlobalMetadataAttachment(Record,
F);
2780 for (
const BasicBlock &BB :
F)
2781 for (
const Instruction &
I : BB) {
2783 I.getAllMetadataOtherThanDebugLoc(MDs);
2786 if (MDs.
empty())
continue;
2790 for (
const auto &[
ID, MD] : MDs) {
2801void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2802 SmallVector<uint64_t, 64>
Record;
2807 M.getMDKindNames(Names);
2809 if (Names.
empty())
return;
2813 for (
unsigned MDKindID = 0, e = Names.
size(); MDKindID != e; ++MDKindID) {
2814 Record.push_back(MDKindID);
2815 StringRef KName = Names[MDKindID];
2825void ModuleBitcodeWriter::writeOperandBundleTags() {
2833 M.getOperandBundleTags(Tags);
2840 SmallVector<uint64_t, 64>
Record;
2842 for (
auto Tag : Tags) {
2852void ModuleBitcodeWriter::writeSyncScopeNames() {
2854 M.getContext().getSyncScopeNames(SSNs);
2860 SmallVector<uint64_t, 64>
Record;
2861 for (
auto SSN : SSNs) {
2862 Record.append(SSN.begin(), SSN.end());
2870void ModuleBitcodeWriter::writeConstants(
unsigned FirstVal,
unsigned LastVal,
2872 if (FirstVal == LastVal)
return;
2876 unsigned AggregateAbbrev = 0;
2877 unsigned String8Abbrev = 0;
2878 unsigned CString7Abbrev = 0;
2879 unsigned CString6Abbrev = 0;
2883 auto Abbv = std::make_shared<BitCodeAbbrev>();
2887 AggregateAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
2890 Abbv = std::make_shared<BitCodeAbbrev>();
2894 String8Abbrev = Stream.
EmitAbbrev(std::move(Abbv));
2896 Abbv = std::make_shared<BitCodeAbbrev>();
2900 CString7Abbrev = Stream.
EmitAbbrev(std::move(Abbv));
2902 Abbv = std::make_shared<BitCodeAbbrev>();
2906 CString6Abbrev = Stream.
EmitAbbrev(std::move(Abbv));
2909 SmallVector<uint64_t, 64>
Record;
2912 Type *LastTy =
nullptr;
2913 for (
unsigned i = FirstVal; i != LastVal; ++i) {
2914 const Value *
V = Vals[i].first;
2916 if (
V->getType() != LastTy) {
2917 LastTy =
V->getType();
2920 CONSTANTS_SETTYPE_ABBREV);
2927 unsigned(
IA->hasSideEffects()) |
unsigned(
IA->isAlignStack()) << 1 |
2928 unsigned(
IA->getDialect() & 1) << 2 |
unsigned(
IA->canThrow()) << 3);
2931 StringRef AsmStr =
IA->getAsmString();
2936 StringRef ConstraintStr =
IA->getConstraintString();
2944 unsigned Code = -1U;
2945 unsigned AbbrevToUse = 0;
2946 if (
C->isNullValue()) {
2953 if (
IV->getBitWidth() <= 64) {
2954 uint64_t
V =
IV->getSExtValue();
2957 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2963 if (BV->getBitWidth() <= 64) {
2964 uint64_t
V = BV->getSExtValue();
2967 AbbrevToUse = CONSTANTS_BYTE_ABBREV;
2977 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
2981 APInt api = CFP->getValueAPF().bitcastToAPInt();
2983 Record.push_back((p[1] << 48) | (p[0] >> 16));
2984 Record.push_back(p[0] & 0xffffLL);
2986 APInt api = CFP->getValueAPF().bitcastToAPInt();
2991 assert(0 &&
"Unknown FP type!");
2997 uint64_t NumElts = Str->getNumElements();
2999 if (Str->isCString()) {
3004 AbbrevToUse = String8Abbrev;
3008 for (uint64_t i = 0; i != NumElts; ++i) {
3009 unsigned char V = Str->getElementAsInteger(i);
3011 isCStr7 &= (
V & 128) == 0;
3017 AbbrevToUse = CString6Abbrev;
3019 AbbrevToUse = CString7Abbrev;
3020 }
else if (
const ConstantDataSequential *CDS =
3023 Type *EltTy = CDS->getElementType();
3025 for (uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i)
3026 Record.push_back(CDS->getElementAsInteger(i));
3028 for (uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i)
3030 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
3034 for (
const Value *
Op :
C->operands())
3036 AbbrevToUse = AggregateAbbrev;
3038 switch (
CE->getOpcode()) {
3045 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
3047 assert(
CE->getNumOperands() == 2 &&
"Unknown constant expr!");
3057 case Instruction::FNeg: {
3058 assert(
CE->getNumOperands() == 1 &&
"Unknown constant expr!");
3067 case Instruction::GetElementPtr: {
3072 if (std::optional<ConstantRange>
Range = GO->getInRange()) {
3076 for (
const Value *
Op :
CE->operands()) {
3082 case Instruction::ExtractElement:
3089 case Instruction::InsertElement:
3096 case Instruction::ShuffleVector:
3101 if (
C->getType() ==
C->getOperand(0)->getType()) {
3138 Stream.
EmitRecord(Code, Record, AbbrevToUse);
3145void ModuleBitcodeWriter::writeModuleConstants() {
3150 for (
unsigned i = 0, e = Vals.size(); i != e; ++i) {
3152 writeConstants(i, Vals.size(),
true);
3166bool ModuleBitcodeWriter::pushValueAndType(
const Value *V,
unsigned InstID,
3167 SmallVectorImpl<unsigned> &Vals) {
3171 if (ValID >= InstID) {
3178bool ModuleBitcodeWriter::pushValueOrMetadata(
const Value *V,
unsigned InstID,
3179 SmallVectorImpl<unsigned> &Vals) {
3180 bool IsMetadata =
V->getType()->isMetadataTy();
3188 return pushValueAndType(V, InstID, Vals);
3191void ModuleBitcodeWriter::writeOperandBundles(
const CallBase &CS,
3198 Record.push_back(
C.getOperandBundleTagID(Bundle.getTagName()));
3200 for (
auto &Input : Bundle.Inputs)
3201 pushValueOrMetadata(Input, InstID, Record);
3210void ModuleBitcodeWriter::pushValue(
const Value *V,
unsigned InstID,
3211 SmallVectorImpl<unsigned> &Vals) {
3216void ModuleBitcodeWriter::pushValueSigned(
const Value *V,
unsigned InstID,
3217 SmallVectorImpl<uint64_t> &Vals) {
3219 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
3224void ModuleBitcodeWriter::writeInstruction(
const Instruction &
I,
3226 SmallVectorImpl<unsigned> &Vals) {
3228 unsigned AbbrevToUse = 0;
3230 switch (
I.getOpcode()) {
3234 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3235 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
3240 if (AbbrevToUse == FUNCTION_INST_CAST_ABBREV)
3241 AbbrevToUse = FUNCTION_INST_CAST_FLAGS_ABBREV;
3247 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3248 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
3249 pushValue(
I.getOperand(1), InstID, Vals);
3253 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
3254 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
3259 case Instruction::FNeg: {
3261 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3262 AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
3266 if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
3267 AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
3272 case Instruction::GetElementPtr: {
3274 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
3278 for (
const Value *
Op :
I.operands())
3279 pushValueAndType(
Op, InstID, Vals);
3282 case Instruction::ExtractValue: {
3284 pushValueAndType(
I.getOperand(0), InstID, Vals);
3289 case Instruction::InsertValue: {
3291 pushValueAndType(
I.getOperand(0), InstID, Vals);
3292 pushValueAndType(
I.getOperand(1), InstID, Vals);
3297 case Instruction::Select: {
3299 pushValueAndType(
I.getOperand(1), InstID, Vals);
3300 pushValue(
I.getOperand(2), InstID, Vals);
3301 pushValueAndType(
I.getOperand(0), InstID, Vals);
3307 case Instruction::ExtractElement:
3309 pushValueAndType(
I.getOperand(0), InstID, Vals);
3310 pushValueAndType(
I.getOperand(1), InstID, Vals);
3312 case Instruction::InsertElement:
3314 pushValueAndType(
I.getOperand(0), InstID, Vals);
3315 pushValue(
I.getOperand(1), InstID, Vals);
3316 pushValueAndType(
I.getOperand(2), InstID, Vals);
3318 case Instruction::ShuffleVector:
3320 pushValueAndType(
I.getOperand(0), InstID, Vals);
3321 pushValue(
I.getOperand(1), InstID, Vals);
3325 case Instruction::ICmp:
3326 case Instruction::FCmp: {
3329 AbbrevToUse = FUNCTION_INST_CMP_ABBREV;
3330 if (pushValueAndType(
I.getOperand(0), InstID, Vals))
3332 pushValue(
I.getOperand(1), InstID, Vals);
3338 AbbrevToUse = FUNCTION_INST_CMP_FLAGS_ABBREV;
3343 case Instruction::Ret:
3346 unsigned NumOperands =
I.getNumOperands();
3347 if (NumOperands == 0)
3348 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
3349 else if (NumOperands == 1) {
3350 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3351 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
3353 for (
const Value *
Op :
I.operands())
3354 pushValueAndType(
Op, InstID, Vals);
3358 case Instruction::UncondBr: {
3360 AbbrevToUse = FUNCTION_INST_BR_UNCOND_ABBREV;
3364 case Instruction::CondBr: {
3366 AbbrevToUse = FUNCTION_INST_BR_COND_ABBREV;
3370 pushValue(
II.getCondition(), InstID, Vals);
3372 case Instruction::Switch:
3377 pushValue(
SI.getCondition(), InstID, Vals);
3379 for (
auto Case :
SI.cases()) {
3385 case Instruction::IndirectBr:
3389 pushValue(
I.getOperand(0), InstID, Vals);
3394 case Instruction::Invoke: {
3397 FunctionType *FTy =
II->getFunctionType();
3399 if (
II->hasOperandBundles())
3400 writeOperandBundles(*
II, InstID);
3409 pushValueAndType(Callee, InstID, Vals);
3412 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3413 pushValue(
I.getOperand(i), InstID, Vals);
3416 if (FTy->isVarArg()) {
3417 for (
unsigned i = FTy->getNumParams(), e =
II->arg_size(); i != e; ++i)
3418 pushValueAndType(
I.getOperand(i), InstID, Vals);
3422 case Instruction::Resume:
3424 pushValueAndType(
I.getOperand(0), InstID, Vals);
3426 case Instruction::CleanupRet: {
3429 pushValue(CRI.getCleanupPad(), InstID, Vals);
3430 if (CRI.hasUnwindDest())
3434 case Instruction::CatchRet: {
3437 pushValue(CRI.getCatchPad(), InstID, Vals);
3441 case Instruction::CleanupPad:
3442 case Instruction::CatchPad: {
3446 pushValue(FuncletPad.getParentPad(), InstID, Vals);
3448 unsigned NumArgOperands = FuncletPad.arg_size();
3450 for (
unsigned Op = 0;
Op != NumArgOperands; ++
Op)
3451 pushValueAndType(FuncletPad.getArgOperand(
Op), InstID, Vals);
3454 case Instruction::CatchSwitch: {
3458 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
3460 unsigned NumHandlers = CatchSwitch.getNumHandlers();
3462 for (
const BasicBlock *CatchPadBB : CatchSwitch.handlers())
3465 if (CatchSwitch.hasUnwindDest())
3469 case Instruction::CallBr: {
3475 writeOperandBundles(*CBI, InstID);
3490 pushValueAndType(Callee, InstID, Vals);
3493 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3494 pushValue(
I.getOperand(i), InstID, Vals);
3497 if (FTy->isVarArg()) {
3498 for (
unsigned i = FTy->getNumParams(), e = CBI->
arg_size(); i != e; ++i)
3499 pushValueAndType(
I.getOperand(i), InstID, Vals);
3503 case Instruction::Unreachable:
3505 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
3508 case Instruction::PHI: {
3526 Stream.
EmitRecord(Code, Vals64, AbbrevToUse);
3531 case Instruction::LandingPad: {
3542 pushValueAndType(LP.
getClause(
I), InstID, Vals);
3547 case Instruction::Alloca: {
3553 using APV = AllocaPackedValues;
3555 unsigned EncodedAlign = getEncodedAlign(AI.
getAlign());
3557 Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1));
3559 EncodedAlign >> APV::AlignLower::Bits);
3566 if (AS !=
M.getDataLayout().getAllocaAddrSpace())
3571 case Instruction::Load: {
3573 if (LI.isAtomic()) {
3575 pushValueAndType(LI.getOperand(0), InstID, Vals);
3578 if (!pushValueAndType(LI.getOperand(0), InstID, Vals))
3579 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
3582 Vals.
push_back(getEncodedAlign(LI.getAlign()));
3584 if (LI.isAtomic()) {
3586 Vals.
push_back(getEncodedSyncScopeID(LI.getSyncScopeID()));
3587 if (LI.isElementwise())
3593 case Instruction::Store:
3598 AbbrevToUse = FUNCTION_INST_STORE_ABBREV;
3600 if (pushValueAndType(
I.getOperand(1), InstID, Vals))
3602 if (pushValueAndType(
I.getOperand(0), InstID, Vals))
3612 case Instruction::AtomicCmpXchg:
3614 pushValueAndType(
I.getOperand(0), InstID, Vals);
3615 pushValueAndType(
I.getOperand(1), InstID, Vals);
3616 pushValue(
I.getOperand(2), InstID, Vals);
3627 case Instruction::AtomicRMW:
3629 pushValueAndType(
I.getOperand(0), InstID, Vals);
3630 pushValueAndType(
I.getOperand(1), InstID, Vals);
3638 case Instruction::Fence:
3643 case Instruction::Call: {
3648 writeOperandBundles(CI, InstID);
3668 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3672 if (FTy->isVarArg()) {
3673 for (
unsigned i = FTy->getNumParams(), e = CI.
arg_size(); i != e; ++i)
3678 case Instruction::VAArg:
3681 pushValue(
I.getOperand(0), InstID, Vals);
3684 case Instruction::Freeze:
3686 pushValueAndType(
I.getOperand(0), InstID, Vals);
3696void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3697 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3702 VSTOffset -= bitcodeStartBit();
3703 assert((VSTOffset & 31) == 0 &&
"VST block not 32-bit aligned");
3707 Stream.
BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
3711 auto Abbv = std::make_shared<BitCodeAbbrev>();
3715 unsigned FnEntryAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
3717 for (
const Function &
F : M) {
3720 if (
F.isDeclaration())
3727 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&
F] - bitcodeStartBit();
3728 assert((BitcodeIndex & 31) == 0 &&
"function block not 32-bit aligned");
3732 Record[1] = BitcodeIndex / 32 + 1;
3741void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3742 const ValueSymbolTable &VST) {
3750 SmallVector<uint64_t, 64> NameVals;
3756 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3765 AbbrevToUse = VST_BBENTRY_6_ABBREV;
3769 AbbrevToUse = VST_ENTRY_6_ABBREV;
3771 AbbrevToUse = VST_ENTRY_7_ABBREV;
3774 for (
const auto P :
Name.getKey())
3778 Stream.
EmitRecord(Code, NameVals, AbbrevToUse);
3785void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3786 assert(Order.Shuffle.size() >= 2 &&
"Shuffle too small");
3793 SmallVector<uint64_t, 64>
Record(Order.Shuffle.begin(), Order.Shuffle.end());
3798void ModuleBitcodeWriter::writeUseListBlock(
const Function *
F) {
3800 "Expected to be preserving use-list order");
3802 auto hasMore = [&]() {
3818void ModuleBitcodeWriter::writeFunction(
3820 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3837 unsigned CstStart, CstEnd;
3839 writeConstants(CstStart, CstEnd,
false);
3842 writeFunctionMetadata(
F);
3845 unsigned InstID = CstEnd;
3847 bool NeedsMetadataAttachment =
F.hasMetadata();
3849 DILocation *LastDL =
nullptr;
3850 SmallSetVector<Function *, 4> BlockAddressUsers;
3853 for (
const BasicBlock &BB :
F) {
3854 for (
const Instruction &
I : BB) {
3855 writeInstruction(
I, InstID, Vals);
3857 if (!
I.getType()->isVoidTy())
3861 NeedsMetadataAttachment |=
I.hasMetadataOtherThanDebugLoc();
3864 if (DILocation *
DL =
I.getDebugLoc()) {
3877 FUNCTION_DEBUG_LOC_ABBREV);
3887 if (
I.hasDbgRecords()) {
3891 auto PushValueOrMetadata = [&Vals, InstID,
3894 "RawLocation unexpectedly null in DbgVariableRecord");
3896 SmallVector<unsigned, 2> ValAndType;
3900 if (!pushValueAndType(VAM->getValue(), InstID, ValAndType)) {
3914 for (DbgRecord &DR :
I.DebugMarker->getDbgRecordRange()) {
3940 FUNCTION_DEBUG_RECORD_VALUE_ABBREV);
3964 SmallPtrSet<Value *, 8> Visited{BA};
3965 while (!Worklist.
empty()) {
3967 for (User *U :
V->users()) {
3973 Visited.
insert(U).second)
3980 if (!BlockAddressUsers.
empty()) {
3989 if (
auto *Symtab =
F.getValueSymbolTable())
3990 writeFunctionLevelValueSymbolTable(*Symtab);
3992 if (NeedsMetadataAttachment)
3993 writeFunctionMetadataAttachment(
F);
3995 writeUseListBlock(&
F);
4001void ModuleBitcodeWriter::writeBlockInfo() {
4014 auto Abbv = std::make_shared<BitCodeAbbrev>();
4025 auto Abbv = std::make_shared<BitCodeAbbrev>();
4035 auto Abbv = std::make_shared<BitCodeAbbrev>();
4045 auto Abbv = std::make_shared<BitCodeAbbrev>();
4051 VST_BBENTRY_6_ABBREV)
4056 auto Abbv = std::make_shared<BitCodeAbbrev>();
4058 Abbv->Add(TypeAbbrevOp);
4060 CONSTANTS_SETTYPE_ABBREV)
4065 auto Abbv = std::make_shared<BitCodeAbbrev>();
4069 CONSTANTS_INTEGER_ABBREV)
4074 auto Abbv = std::make_shared<BitCodeAbbrev>();
4078 CONSTANTS_BYTE_ABBREV)
4083 auto Abbv = std::make_shared<BitCodeAbbrev>();
4091 CONSTANTS_CE_CAST_Abbrev)
4095 auto Abbv = std::make_shared<BitCodeAbbrev>();
4098 CONSTANTS_NULL_Abbrev)
4105 auto Abbv = std::make_shared<BitCodeAbbrev>();
4107 Abbv->Add(ValAbbrevOp);
4108 Abbv->Add(TypeAbbrevOp);
4112 FUNCTION_INST_LOAD_ABBREV)
4116 auto Abbv = std::make_shared<BitCodeAbbrev>();
4118 Abbv->Add(ValAbbrevOp);
4119 Abbv->Add(ValAbbrevOp);
4123 FUNCTION_INST_STORE_ABBREV)
4127 auto Abbv = std::make_shared<BitCodeAbbrev>();
4129 Abbv->Add(ValAbbrevOp);
4132 FUNCTION_INST_UNOP_ABBREV)
4136 auto Abbv = std::make_shared<BitCodeAbbrev>();
4138 Abbv->Add(ValAbbrevOp);
4142 FUNCTION_INST_UNOP_FLAGS_ABBREV)
4146 auto Abbv = std::make_shared<BitCodeAbbrev>();
4148 Abbv->Add(ValAbbrevOp);
4149 Abbv->Add(ValAbbrevOp);
4152 FUNCTION_INST_BINOP_ABBREV)
4156 auto Abbv = std::make_shared<BitCodeAbbrev>();
4158 Abbv->Add(ValAbbrevOp);
4159 Abbv->Add(ValAbbrevOp);
4163 FUNCTION_INST_BINOP_FLAGS_ABBREV)
4167 auto Abbv = std::make_shared<BitCodeAbbrev>();
4169 Abbv->Add(ValAbbrevOp);
4170 Abbv->Add(TypeAbbrevOp);
4173 FUNCTION_INST_CAST_ABBREV)
4177 auto Abbv = std::make_shared<BitCodeAbbrev>();
4179 Abbv->Add(ValAbbrevOp);
4180 Abbv->Add(TypeAbbrevOp);
4184 FUNCTION_INST_CAST_FLAGS_ABBREV)
4189 auto Abbv = std::make_shared<BitCodeAbbrev>();
4192 FUNCTION_INST_RET_VOID_ABBREV)
4196 auto Abbv = std::make_shared<BitCodeAbbrev>();
4198 Abbv->Add(ValAbbrevOp);
4200 FUNCTION_INST_RET_VAL_ABBREV)
4204 auto Abbv = std::make_shared<BitCodeAbbrev>();
4207 Abbv->Add(ValAbbrevOp);
4209 FUNCTION_INST_BR_UNCOND_ABBREV)
4213 auto Abbv = std::make_shared<BitCodeAbbrev>();
4216 Abbv->Add(ValAbbrevOp);
4217 Abbv->Add(ValAbbrevOp);
4218 Abbv->Add(ValAbbrevOp);
4220 FUNCTION_INST_BR_COND_ABBREV)
4224 auto Abbv = std::make_shared<BitCodeAbbrev>();
4227 FUNCTION_INST_UNREACHABLE_ABBREV)
4231 auto Abbv = std::make_shared<BitCodeAbbrev>();
4234 Abbv->Add(TypeAbbrevOp);
4236 Abbv->Add(ValAbbrevOp);
4238 FUNCTION_INST_GEP_ABBREV)
4242 auto Abbv = std::make_shared<BitCodeAbbrev>();
4244 Abbv->Add(ValAbbrevOp);
4245 Abbv->Add(ValAbbrevOp);
4248 FUNCTION_INST_CMP_ABBREV)
4252 auto Abbv = std::make_shared<BitCodeAbbrev>();
4254 Abbv->Add(ValAbbrevOp);
4255 Abbv->Add(ValAbbrevOp);
4259 FUNCTION_INST_CMP_FLAGS_ABBREV)
4263 auto Abbv = std::make_shared<BitCodeAbbrev>();
4268 Abbv->Add(ValAbbrevOp);
4270 FUNCTION_DEBUG_RECORD_VALUE_ABBREV)
4274 auto Abbv = std::make_shared<BitCodeAbbrev>();
4285 FUNCTION_DEBUG_LOC_ABBREV)
4293void IndexBitcodeWriter::writeModStrings() {
4299 auto Abbv = std::make_shared<BitCodeAbbrev>();
4304 unsigned Abbrev8Bit = Stream.
EmitAbbrev(std::move(Abbv));
4307 Abbv = std::make_shared<BitCodeAbbrev>();
4312 unsigned Abbrev7Bit = Stream.
EmitAbbrev(std::move(Abbv));
4315 Abbv = std::make_shared<BitCodeAbbrev>();
4320 unsigned Abbrev6Bit = Stream.
EmitAbbrev(std::move(Abbv));
4323 Abbv = std::make_shared<BitCodeAbbrev>();
4330 unsigned AbbrevHash = Stream.
EmitAbbrev(std::move(Abbv));
4333 forEachModule([&](
const StringMapEntry<ModuleHash> &MPSE) {
4335 const auto &Hash = MPSE.
getValue();
4337 unsigned AbbrevToUse = Abbrev8Bit;
4339 AbbrevToUse = Abbrev6Bit;
4341 AbbrevToUse = Abbrev7Bit;
4343 auto ModuleId = ModuleIdMap.
size();
4344 ModuleIdMap[
Key] = ModuleId;
4354 Vals.
assign(Hash.begin(), Hash.end());
4366template <
typename Fn>
4370 if (!FS->type_tests().empty())
4375 auto WriteVFuncIdVec = [&](
uint64_t Ty,
4380 for (
auto &VF : VFs) {
4381 Record.push_back(VF.GUID);
4382 Record.push_back(VF.Offset);
4388 FS->type_test_assume_vcalls());
4390 FS->type_checked_load_vcalls());
4392 auto WriteConstVCallVec = [&](
uint64_t Ty,
4394 for (
auto &VC : VCs) {
4396 Record.push_back(VC.VFunc.GUID);
4397 Record.push_back(VC.VFunc.Offset);
4404 FS->type_test_assume_const_vcalls());
4406 FS->type_checked_load_const_vcalls());
4416 if (!FS->paramAccesses().empty()) {
4418 for (
auto &Arg : FS->paramAccesses()) {
4419 size_t UndoSize =
Record.size();
4420 Record.push_back(Arg.ParamNo);
4421 WriteRange(Arg.Use);
4422 Record.push_back(Arg.Calls.size());
4423 for (
auto &
Call : Arg.Calls) {
4425 std::optional<unsigned> ValueID = GetValueID(
Call.Callee);
4432 Record.push_back(*ValueID);
4433 WriteRange(
Call.Offsets);
4444 std::set<GlobalValue::GUID> &ReferencedTypeIds) {
4445 if (!FS->type_tests().empty())
4446 for (
auto &TT : FS->type_tests())
4447 ReferencedTypeIds.insert(TT);
4449 auto GetReferencedTypesFromVFuncIdVec =
4451 for (
auto &VF : VFs)
4452 ReferencedTypeIds.insert(VF.GUID);
4455 GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
4456 GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
4458 auto GetReferencedTypesFromConstVCallVec =
4460 for (
auto &VC : VCs)
4461 ReferencedTypeIds.insert(VC.VFunc.GUID);
4464 GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
4465 GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
4501 NameVals.
push_back(Summary.TTRes.TheKind);
4502 NameVals.
push_back(Summary.TTRes.SizeM1BitWidth);
4503 NameVals.
push_back(Summary.TTRes.AlignLog2);
4504 NameVals.
push_back(Summary.TTRes.SizeM1);
4505 NameVals.
push_back(Summary.TTRes.BitMask);
4506 NameVals.
push_back(Summary.TTRes.InlineBits);
4508 for (
auto &W : Summary.WPDRes)
4520 for (
auto &
P : Summary) {
4522 NameVals.
push_back(
VE.getValueID(
P.VTableVI.getValue()));
4536 static_assert(std::is_same_v<LinearFrameId, unsigned>);
4537 for (
auto &AI : FS->allocs()) {
4538 for (
auto &MIB : AI.MIBs) {
4540 StackIdIndices.
reserve(MIB.StackIdIndices.size());
4541 for (
auto Id : MIB.StackIdIndices)
4542 StackIdIndices.
push_back(GetStackIndex(Id));
4544 CallStacks.insert({CallStacks.size(), StackIdIndices});
4557 assert(!CallStacks.empty());
4563 Builder.
build(std::move(CallStacks),
nullptr,
4567 return Builder.takeCallStackPos();
4572 unsigned AllocAbbrev,
unsigned ContextIdAbbvId,
bool PerModule,
4573 std::function<
unsigned(
const ValueInfo &VI)> GetValueID,
4574 std::function<
unsigned(
unsigned)> GetStackIndex,
4575 bool WriteContextSizeInfoIndex,
4580 for (
auto &CI : FS->callsites()) {
4584 assert(!PerModule || (CI.Clones.size() == 1 && CI.Clones[0] == 0));
4585 Record.push_back(GetValueID(CI.Callee));
4587 Record.push_back(CI.StackIdIndices.size());
4588 Record.push_back(CI.Clones.size());
4590 for (
auto Id : CI.StackIdIndices)
4591 Record.push_back(GetStackIndex(Id));
4599 for (
auto &AI : FS->allocs()) {
4603 assert(!PerModule || (AI.Versions.size() == 1 && AI.Versions[0] == 0));
4604 Record.push_back(AI.MIBs.size());
4606 Record.push_back(AI.Versions.size());
4607 for (
auto &MIB : AI.MIBs) {
4614 assert(CallStackCount <= CallStackPos.
size());
4615 Record.push_back(CallStackPos[CallStackCount++]);
4620 assert(AI.ContextSizeInfos.empty() ||
4621 AI.ContextSizeInfos.size() == AI.MIBs.size());
4623 if (WriteContextSizeInfoIndex && !AI.ContextSizeInfos.empty()) {
4631 ContextIds.
reserve(AI.ContextSizeInfos.size() * 2);
4632 for (
auto &Infos : AI.ContextSizeInfos) {
4633 Record.push_back(Infos.size());
4634 for (
auto [FullStackId, TotalSize] : Infos) {
4641 Record.push_back(TotalSize);
4659void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
4660 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
4661 unsigned ValueID,
unsigned FSCallsProfileAbbrev,
unsigned CallsiteAbbrev,
4662 unsigned AllocAbbrev,
unsigned ContextIdAbbvId,
const Function &
F,
4663 DenseMap<CallStackId, LinearCallStackId> &CallStackPos,
4670 Stream, FS, [&](
const ValueInfo &VI) -> std::optional<unsigned> {
4674 auto SpecialRefCnts =
FS->specialRefCounts();
4679 NameVals.
push_back(SpecialRefCnts.first);
4680 NameVals.
push_back(SpecialRefCnts.second);
4682 for (
auto &RI :
FS->refs())
4685 for (
auto &ECI :
FS->calls()) {
4686 NameVals.
push_back(getValueId(ECI.first));
4695 Stream, FS, CallsiteAbbrev, AllocAbbrev, ContextIdAbbvId,
4697 [&](
const ValueInfo &VI) {
return getValueId(VI); },
4698 [&](
unsigned I) {
return I; },
4699 true, CallStackPos, CallStackCount);
4704void ModuleBitcodeWriterBase::writeModuleLevelReferences(
4705 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
4706 unsigned FSModRefsAbbrev,
unsigned FSModVTableRefsAbbrev) {
4711 auto VI =
Index->getValueInfo(GUID);
4712 if (!VI ||
VI.getSummaryList().empty()) {
4718 auto *
Summary =
VI.getSummaryList()[0].get();
4724 auto VTableFuncs =
VS->vTableFuncs();
4725 if (!VTableFuncs.empty())
4728 unsigned SizeBeforeRefs = NameVals.
size();
4729 for (
auto &RI :
VS->refs())
4735 if (VTableFuncs.empty())
4740 for (
auto &
P : VTableFuncs) {
4746 FSModVTableRefsAbbrev);
4753void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
4756 bool IsThinLTO =
true;
4759 IsThinLTO = MD->getZExtValue();
4771 if (
Index->enableSplitLTOUnit())
4773 if (
Index->hasUnifiedLTO())
4783 auto Abbv = std::make_shared<BitCodeAbbrev>();
4789 unsigned ValueGuidAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4791 for (
const auto &GVI : valueIds()) {
4793 ArrayRef<uint32_t>{GVI.second,
4794 static_cast<uint32_t
>(GVI.first >> 32),
4795 static_cast<uint32_t
>(GVI.first)},
4799 if (!
Index->stackIds().empty()) {
4800 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4807 unsigned StackIdAbbvId = Stream.
EmitAbbrev(std::move(StackIdAbbv));
4808 SmallVector<uint32_t> Vals;
4810 for (
auto Id :
Index->stackIds()) {
4811 Vals.
push_back(
static_cast<uint32_t
>(Id >> 32));
4812 Vals.
push_back(
static_cast<uint32_t
>(Id));
4817 unsigned ContextIdAbbvId = 0;
4820 auto ContextIdAbbv = std::make_shared<BitCodeAbbrev>();
4832 ContextIdAbbvId = Stream.
EmitAbbrev(std::move(ContextIdAbbv));
4836 Abbv = std::make_shared<BitCodeAbbrev>();
4848 unsigned FSCallsProfileAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4851 Abbv = std::make_shared<BitCodeAbbrev>();
4857 unsigned FSModRefsAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4860 Abbv = std::make_shared<BitCodeAbbrev>();
4868 unsigned FSModVTableRefsAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4871 Abbv = std::make_shared<BitCodeAbbrev>();
4876 unsigned FSAliasAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4879 Abbv = std::make_shared<BitCodeAbbrev>();
4886 unsigned TypeIdCompatibleVtableAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4888 Abbv = std::make_shared<BitCodeAbbrev>();
4894 unsigned CallsiteAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4896 Abbv = std::make_shared<BitCodeAbbrev>();
4903 unsigned AllocAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4905 Abbv = std::make_shared<BitCodeAbbrev>();
4910 unsigned RadixAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4917 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks;
4918 for (
const Function &
F : M) {
4928 ValueInfo
VI =
Index->getValueInfo(GUID);
4929 if (!VI ||
VI.getSummaryList().empty()) {
4932 if (!
F.isDeclaration())
4934 " to have an associated value info.");
4937 auto *
Summary =
VI.getSummaryList()[0].get();
4940 FS, [](
unsigned I) {
return I; }, CallStacks);
4944 DenseMap<CallStackId, LinearCallStackId> CallStackPos;
4945 if (!CallStacks.
empty()) {
4953 SmallVector<uint64_t, 64> NameVals;
4956 for (
const Function &
F : M) {
4964 ValueInfo
VI =
Index->getValueInfo(GUID);
4965 if (!VI ||
VI.getSummaryList().empty()) {
4971 auto *
Summary =
VI.getSummaryList()[0].get();
4972 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.
getValueID(&
F),
4973 FSCallsProfileAbbrev, CallsiteAbbrev,
4974 AllocAbbrev, ContextIdAbbvId,
F,
4975 CallStackPos, CallStackCount);
4980 for (
const GlobalVariable &
G :
M.globals())
4981 writeModuleLevelReferences(
G, NameVals, FSModRefsAbbrev,
4982 FSModVTableRefsAbbrev);
4984 for (
const GlobalAlias &
A :
M.aliases()) {
4985 auto *Aliasee =
A.getAliaseeObject();
5001 for (
auto &S :
Index->typeIdCompatibleVtableMap()) {
5005 TypeIdCompatibleVtableAbbrev);
5009 if (
Index->getBlockCount())
5011 ArrayRef<uint64_t>{
Index->getBlockCount()});
5016void ModuleBitcodeWriterBase::writeGUIDList() {
5018 const size_t Max = Vals.size();
5020 std::vector<GlobalValue::GUID> GUIDs(Max, 0);
5021 for (
const GlobalValue &GV :
M.global_values()) {
5022 auto MaybeGUID = GV.getGUIDIfAssigned();
5025 auto GUID = *MaybeGUID;
5028 GUIDs[ValueID] =
GUID;
5031 auto Abbv = std::make_shared<BitCodeAbbrev>();
5035 unsigned GUIDListAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5037 SmallVector<uint32_t> RecordVals;
5039 for (
auto GUID : GUIDs) {
5040 RecordVals.
push_back(
static_cast<uint32_t
>(GUID >> 32));
5041 RecordVals.
push_back(
static_cast<uint32_t
>(GUID));
5048void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
5057 auto Abbv = std::make_shared<BitCodeAbbrev>();
5063 unsigned ValueGuidAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5065 for (
const auto &GVI : valueIds()) {
5067 ArrayRef<uint32_t>{GVI.second,
5068 static_cast<uint32_t
>(GVI.first >> 32),
5069 static_cast<uint32_t
>(GVI.first)},
5075 if (!StackIds.empty()) {
5076 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
5083 unsigned StackIdAbbvId = Stream.
EmitAbbrev(std::move(StackIdAbbv));
5084 SmallVector<uint32_t> Vals;
5085 Vals.
reserve(StackIds.size() * 2);
5086 for (
auto Id : StackIds) {
5087 Vals.
push_back(
static_cast<uint32_t
>(Id >> 32));
5088 Vals.
push_back(
static_cast<uint32_t
>(Id));
5094 Abbv = std::make_shared<BitCodeAbbrev>();
5108 unsigned FSCallsProfileAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5111 Abbv = std::make_shared<BitCodeAbbrev>();
5118 unsigned FSModRefsAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5121 Abbv = std::make_shared<BitCodeAbbrev>();
5127 unsigned FSAliasAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5129 Abbv = std::make_shared<BitCodeAbbrev>();
5137 unsigned CallsiteAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5139 Abbv = std::make_shared<BitCodeAbbrev>();
5150 unsigned AllocAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5152 auto shouldImportValueAsDecl = [&](GlobalValueSummary *GVS) ->
bool {
5153 if (DecSummaries ==
nullptr)
5155 return DecSummaries->
count(GVS);
5163 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
5165 SmallVector<uint64_t, 64> NameVals;
5169 std::set<GlobalValue::GUID> ReferencedTypeIds;
5173 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
5183 NameVals.
push_back(S.getOriginalName());
5188 DenseMap<CallStackId, LinearCallStackId> CallStackPos;
5190 Abbv = std::make_shared<BitCodeAbbrev>();
5195 unsigned RadixAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5202 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks;
5203 forEachSummary([&](GVInfo
I,
bool IsAliasee) {
5209 GlobalValueSummary *S =
I.second;
5222 return StackIdIndicesToIndex[
I];
5228 if (!CallStacks.
empty()) {
5238 DenseSet<GlobalValue::GUID> DefOrUseGUIDs;
5239 forEachSummary([&](GVInfo
I,
bool IsAliasee) {
5240 GlobalValueSummary *S =
I.second;
5242 DefOrUseGUIDs.
insert(
I.first);
5243 for (
const ValueInfo &VI : S->
refs())
5244 DefOrUseGUIDs.
insert(
VI.getGUID());
5246 auto ValueId = getValueId(
I.first);
5248 SummaryToValueIdMap[S] = *ValueId;
5266 NameVals.
push_back(ModuleIdMap[
VS->modulePath()]);
5270 for (
auto &RI :
VS->refs()) {
5271 auto RefValueId = getValueId(RI.getGUID());
5281 MaybeEmitOriginalName(*S);
5285 auto GetValueId = [&](
const ValueInfo &
VI) -> std::optional<unsigned> {
5287 return std::nullopt;
5288 return getValueId(
VI.getGUID());
5297 NameVals.
push_back(ModuleIdMap[
FS->modulePath()]);
5310 unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;
5311 for (
auto &RI :
FS->refs()) {
5312 auto RefValueId = getValueId(RI.getGUID());
5316 if (RI.isReadOnly())
5318 else if (RI.isWriteOnly())
5322 NameVals[6] =
Count;
5323 NameVals[7] = RORefCnt;
5324 NameVals[8] = WORefCnt;
5326 for (
auto &EI :
FS->calls()) {
5329 std::optional<unsigned> CallValueId = GetValueId(EI.first);
5338 FSCallsProfileAbbrev);
5342 Stream, FS, CallsiteAbbrev, AllocAbbrev, 0,
5345 [&](
const ValueInfo &VI) ->
unsigned {
5346 std::optional<unsigned> ValueID = GetValueId(VI);
5361 return StackIdIndicesToIndex[
I];
5363 false, CallStackPos, CallStackCount);
5365 MaybeEmitOriginalName(*S);
5368 for (
auto *AS : Aliases) {
5369 auto AliasValueId = SummaryToValueIdMap[AS];
5378 auto AliaseeValueId =
5385 MaybeEmitOriginalName(*AS);
5393 auto EmitCfiFunctions = [&](
const CfiFunctionIndex &CfiIndex,
5395 if (CfiIndex.
empty())
5399 for (StringRef Name : Names)
5402 if (Functions.
empty())
5405 for (
const auto &Record : Functions) {
5420 for (
auto &
T : ReferencedTypeIds) {
5421 auto TidIter =
Index.typeIds().equal_range(
T);
5422 for (
const auto &[GUID, TypeIdPair] :
make_range(TidIter)) {
5430 if (
Index.getBlockCount())
5432 ArrayRef<uint64_t>{
Index.getBlockCount()});
5443 auto Abbv = std::make_shared<BitCodeAbbrev>();
5447 auto StringAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5449 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
5452 Abbv = std::make_shared<BitCodeAbbrev>();
5455 auto EpochAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5461void ModuleBitcodeWriter::writeModuleHash(StringRef View) {
5466 Hasher.
update(ArrayRef<uint8_t>(
5467 reinterpret_cast<const uint8_t *
>(
View.data()),
View.size()));
5468 std::array<uint8_t, 20> Hash = Hasher.
result();
5469 for (
int Pos = 0; Pos < 20; Pos += 4) {
5482void ModuleBitcodeWriter::write() {
5490 writeModuleVersion();
5499 writeAttributeGroupTable();
5502 writeAttributeTable();
5511 writeModuleConstants();
5514 writeModuleMetadataKinds();
5517 writeModuleMetadata();
5521 writeUseListBlock(
nullptr);
5523 writeOperandBundleTags();
5524 writeSyncScopeNames();
5527 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
5528 for (
const Function &
F : M)
5529 if (!
F.isDeclaration())
5530 writeFunction(
F, FunctionToBitcodeIndex);
5535 writePerModuleGlobalValueSummary();
5537 writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
5565 unsigned CPUType = ~0U;
5572 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
5573 DARWIN_CPU_TYPE_X86 = 7,
5574 DARWIN_CPU_TYPE_ARM = 12,
5575 DARWIN_CPU_TYPE_POWERPC = 18
5580 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
5582 CPUType = DARWIN_CPU_TYPE_X86;
5584 CPUType = DARWIN_CPU_TYPE_POWERPC;
5586 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
5588 CPUType = DARWIN_CPU_TYPE_ARM;
5592 "Expected header size to be reserved");
5597 unsigned Position = 0;
5605 while (Buffer.
size() & 15)
5612 Stream.
Emit((
unsigned)
'B', 8);
5613 Stream.
Emit((
unsigned)
'C', 8);
5614 Stream.
Emit(0x0, 4);
5615 Stream.
Emit(0xC, 4);
5616 Stream.
Emit(0xE, 4);
5617 Stream.
Emit(0xD, 4);
5635 auto Abbv = std::make_shared<BitCodeAbbrev>();
5638 auto AbbrevNo = Stream->
EmitAbbrev(std::move(Abbv));
5646 assert(!WroteStrtab && !WroteSymtab);
5652 if (M->getModuleInlineAsm().empty())
5656 const Triple TT(M->getTargetTriple());
5658 if (!
T || !
T->hasMCAsmParser())
5680 std::vector<char> Strtab;
5681 StrtabBuilder.finalizeInOrder();
5682 Strtab.resize(StrtabBuilder.getSize());
5683 StrtabBuilder.write((
uint8_t *)Strtab.data());
5686 {Strtab.data(), Strtab.size()});
5697 bool ShouldPreserveUseListOrder,
5706 assert(M.isMaterialized());
5707 Mods.push_back(
const_cast<Module *
>(&M));
5709 ModuleBitcodeWriter ModuleWriter(M, StrtabBuilder, *Stream,
5710 ShouldPreserveUseListOrder, Index,
5711 GenerateHash, ModHash);
5712 ModuleWriter.write();
5719 IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index, DecSummaries,
5720 ModuleToSummariesForIndex);
5721 IndexWriter.write();
5726 bool ShouldPreserveUseListOrder,
5730 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
5732 Writer.writeSymtab();
5733 Writer.writeStrtab();
5735 Triple TT(M.getTargetTriple());
5736 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) {
5754void IndexBitcodeWriter::write() {
5757 writeModuleVersion();
5763 writeCombinedGlobalValueSummary();
5780 Writer.
writeIndex(&Index, ModuleToSummariesForIndex, DecSummaries);
5789class ThinLinkBitcodeWriter :
public ModuleBitcodeWriterBase {
5799 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
5801 ModHash(&ModHash) {}
5806 void writeSimplifiedModuleInfo();
5816void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
5828 auto Abbv = std::make_shared<BitCodeAbbrev>();
5831 Abbv->Add(AbbrevOpToUse);
5832 unsigned FilenameAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5834 for (
const auto P :
M.getSourceFileName())
5900void ThinLinkBitcodeWriter::write() {
5903 writeModuleVersion();
5905 writeSimplifiedModuleInfo();
5907 writePerModuleGlobalValueSummary();
5924 assert(M.isMaterialized());
5925 Mods.push_back(
const_cast<Module *
>(&M));
5927 ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
5929 ThinLinkWriter.write();
5950 switch (
T.getObjectFormat()) {
5952 return "__LLVM,__bitcode";
5977 switch (
T.getObjectFormat()) {
5979 return "__LLVM,__cmdline";
6005 const std::vector<uint8_t> &CmdArgs) {
6010 Type *UsedElementType = Used ? Used->getValueType()->getArrayElementType()
6012 for (
auto *GV : UsedGlobals) {
6013 if (GV->getName() !=
"llvm.embedded.module" &&
6014 GV->getName() !=
"llvm.cmdline")
6019 Used->eraseFromParent();
6024 Triple T(M.getTargetTriple());
6053 M.getGlobalVariable(
"llvm.embedded.module",
true)) {
6054 assert(Old->hasZeroLiveUses() &&
6055 "llvm.embedded.module can only be used once in llvm.compiler.used");
6057 Old->eraseFromParent();
6059 GV->
setName(
"llvm.embedded.module");
6077 assert(Old->hasZeroLiveUses() &&
6078 "llvm.cmdline can only be used once in llvm.compiler.used");
6080 Old->eraseFromParent();
6086 if (UsedArray.
empty())
6094 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 writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N, AsmWriterContext &WriterCtx)
static void writeDIBasicType(raw_ostream &Out, const DIBasicType *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 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< 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
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Lightweight error class with error context and mandatory checking.
Function summary information to aid decisions and implementation of importing.
ForceSummaryHotnessType
Types for -force-summary-edges-cold debugging option.
LLVM_ABI void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
Appends all metadata attached to this value to MDs, sorting by KindID.
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
GVFlags flags() const
Get the flags for this GlobalValue (see struct GVFlags).
StringRef modulePath() const
Get the path to the module containing this function.
ArrayRef< ValueInfo > refs() const
Return the list of values referenced by this global value definition.
VisibilityTypes getVisibility() const
static bool isLocalLinkage(LinkageTypes Linkage)
LinkageTypes getLinkage() const
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
ThreadLocalMode getThreadLocalMode() const
@ DLLExportStorageClass
Function to be accessible from DLL.
@ DLLImportStorageClass
Function to be imported from DLL.
@ DefaultVisibility
The GV is visible.
@ HiddenVisibility
The GV is hidden.
@ ProtectedVisibility
The GV is protected.
UnnamedAddr getUnnamedAddr() const
LinkageTypes
An enumeration for the kinds of linkage for global values.
@ PrivateLinkage
Like Internal, but omit from symbol table.
@ CommonLinkage
Tentative definitions.
@ InternalLinkage
Rename collisions when linking (static functions).
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
@ WeakODRLinkage
Same, but only replaced by something equivalent.
@ ExternalLinkage
Externally visible function.
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
@ AppendingLinkage
Special purpose, only applies to global arrays.
@ AvailableExternallyLinkage
Available for inspection, not emission.
@ ExternalWeakLinkage
ExternalWeak linkage description.
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
DLLStorageClassTypes getDLLStorageClass() const
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
idx_iterator idx_end() const
idx_iterator idx_begin() const
bool isCleanup() const
Return 'true' if this landingpad instruction is a cleanup.
unsigned getNumClauses() const
Get the number of clauses for this landing pad.
bool isCatch(unsigned Idx) const
Return 'true' if the clause and index Idx is a catch clause.
Constant * getClause(unsigned Idx) const
Get the value of the clause at index Idx.
This class implements a map that also provides access to all stored values in a deterministic order.
size_t getBufferSize() const
const char * getBufferStart() const
const char * getBufferEnd() const
Class to hold module path string table and global value map, and encapsulate methods for operating on...
static constexpr uint64_t BitcodeSummaryVersion
A Module instance is used to store all the information related to an LLVM module.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
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.
raw_ostream & write(unsigned char C)
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.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ C
The default llvm calling convention, compatible with C.
Predicate getPredicate(unsigned Condition, unsigned Hint)
Return predicate consisting of specified condition and hint bits.
constexpr bool isAtomic(const T &...O)
@ CE
Windows NT (Windows on ARM)
@ TYPE_CODE_OPAQUE_POINTER
@ METADATA_TEMPLATE_VALUE
@ METADATA_LEXICAL_BLOCK_FILE
@ METADATA_SUBROUTINE_TYPE
@ METADATA_GLOBAL_DECL_ATTACHMENT
@ METADATA_IMPORTED_ENTITY
@ METADATA_GENERIC_SUBRANGE
@ METADATA_COMPOSITE_TYPE
@ METADATA_FIXED_POINT_TYPE
@ METADATA_GLOBAL_VAR_EXPR
GlobalValueSummarySymtabCodes
@ FS_CONTEXT_RADIX_TREE_ARRAY
@ FS_COMBINED_GLOBALVAR_INIT_REFS
@ FS_TYPE_CHECKED_LOAD_VCALLS
@ FS_COMBINED_ORIGINAL_NAME
@ FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_CONST_VCALL
@ FS_PERMODULE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_VCALLS
@ FS_COMBINED_ALLOC_INFO_NO_CONTEXT
@ FS_COMBINED_CALLSITE_INFO
@ FS_PERMODULE_CALLSITE_INFO
@ FS_PERMODULE_ALLOC_INFO
@ FS_TYPE_CHECKED_LOAD_CONST_VCALL
@ IDENTIFICATION_CODE_EPOCH
@ IDENTIFICATION_CODE_STRING
@ CST_CODE_DSO_LOCAL_EQUIVALENT
@ CST_CODE_CE_GEP_WITH_INRANGE
@ COMDAT_SELECTION_KIND_LARGEST
@ COMDAT_SELECTION_KIND_ANY
@ COMDAT_SELECTION_KIND_SAME_SIZE
@ COMDAT_SELECTION_KIND_EXACT_MATCH
@ COMDAT_SELECTION_KIND_NO_DUPLICATES
@ ATTR_KIND_STACK_PROTECT
@ ATTR_KIND_STACK_PROTECT_STRONG
@ ATTR_KIND_SANITIZE_MEMORY
@ ATTR_KIND_OPTIMIZE_FOR_SIZE
@ ATTR_KIND_FNRETTHUNK_EXTERN
@ ATTR_KIND_NO_DIVERGENCE_SOURCE
@ ATTR_KIND_SANITIZE_ADDRESS
@ ATTR_KIND_NO_IMPLICIT_FLOAT
@ ATTR_KIND_DEAD_ON_UNWIND
@ ATTR_KIND_STACK_ALIGNMENT
@ ATTR_KIND_STACK_PROTECT_REQ
@ ATTR_KIND_NULL_POINTER_IS_VALID
@ ATTR_KIND_SANITIZE_HWADDRESS
@ ATTR_KIND_RETURNS_TWICE
@ ATTR_KIND_SHADOWCALLSTACK
@ ATTR_KIND_OPT_FOR_FUZZING
@ ATTR_KIND_DENORMAL_FPENV
@ ATTR_KIND_SANITIZE_NUMERICAL_STABILITY
@ ATTR_KIND_ALLOCATED_POINTER
@ ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION
@ ATTR_KIND_CORO_ELIDE_SAFE
@ ATTR_KIND_NON_LAZY_BIND
@ ATTR_KIND_DEREFERENCEABLE
@ ATTR_KIND_OPTIMIZE_NONE
@ ATTR_KIND_HYBRID_PATCHABLE
@ ATTR_KIND_DEREFERENCEABLE_OR_NULL
@ ATTR_KIND_SANITIZE_REALTIME
@ ATTR_KIND_SPECULATIVE_LOAD_HARDENING
@ ATTR_KIND_ALWAYS_INLINE
@ ATTR_KIND_SANITIZE_TYPE
@ ATTR_KIND_PRESPLIT_COROUTINE
@ ATTR_KIND_SANITIZE_ALLOC_TOKEN
@ ATTR_KIND_NO_SANITIZE_COVERAGE
@ ATTR_KIND_NO_CREATE_UNDEF_OR_POISON
@ ATTR_KIND_DEAD_ON_RETURN
@ ATTR_KIND_SANITIZE_REALTIME_BLOCKING
@ ATTR_KIND_NO_SANITIZE_BOUNDS
@ ATTR_KIND_SANITIZE_MEMTAG
@ ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE
@ ATTR_KIND_SANITIZE_THREAD
@ ATTR_KIND_OPTIMIZE_FOR_DEBUGGING
@ SYNC_SCOPE_NAMES_BLOCK_ID
@ PARAMATTR_GROUP_BLOCK_ID
@ IDENTIFICATION_BLOCK_ID
@ GLOBALVAL_SUMMARY_BLOCK_ID
@ FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID
@ OPERAND_BUNDLE_TAGS_BLOCK_ID
@ MODULE_CODE_SOURCE_FILENAME
@ MODULE_CODE_SECTIONNAME
@ MODULE_CODE_ASM_PROPERTY
@ FUNC_CODE_INST_CATCHRET
@ FUNC_CODE_INST_LANDINGPAD
@ FUNC_CODE_INST_EXTRACTVAL
@ FUNC_CODE_INST_CATCHPAD
@ FUNC_CODE_INST_CATCHSWITCH
@ FUNC_CODE_INST_CLEANUPRET
@ FUNC_CODE_DEBUG_RECORD_VALUE
@ FUNC_CODE_INST_LOADATOMIC
@ FUNC_CODE_DEBUG_RECORD_ASSIGN
@ FUNC_CODE_INST_STOREATOMIC
@ FUNC_CODE_INST_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_DEBUG_RECORD_DECLARE
@ FUNC_CODE_OPERAND_BUNDLE
@ FIRST_APPLICATION_ABBREV
@ PARAMATTR_GRP_CODE_ENTRY
initializer< Ty > init(const Ty &Val)
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
LLVM_ABI Error build(ArrayRef< Module * > Mods, SmallVector< char, 0 > &Symtab, StringTableBuilder &StrtabBuilder, BumpPtrAllocator &Alloc)
Fills in Symtab and StrtabBuilder with a valid symbol and string table for Mods.
llvm::unique_function< void(llvm::Expected< T >)> Callback
A Callback<T> is a void function that accepts Expected<T>.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract_or_null(Y &&MD)
Extract a Value from Metadata, allowing null.
LLVM_ABI bool metadataIncludesAllContextSizeInfo()
Whether the alloc memeprof metadata will include context size info for all MIBs.
template LLVM_ABI llvm::DenseMap< LinearFrameId, FrameStat > computeFrameHistogram< LinearFrameId >(llvm::MapVector< CallStackId, llvm::SmallVector< LinearFrameId > > &MemProfCallStackData)
LLVM_ABI bool metadataMayIncludeContextSizeInfo()
Whether the alloc memprof metadata may include context size info for some MIBs (but possibly not all)...
NodeAddr< CodeNode * > Code
void write32le(void *P, uint32_t V)
uint32_t read32be(const void *P)
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
StringMapEntry< Value * > ValueName
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
unsigned encode(MaybeAlign A)
Returns a representation of the alignment that encodes undefined as 0.
LLVM_ABI void WriteBitcodeToFile(const Module &M, raw_ostream &Out, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false, ModuleHash *ModHash=nullptr)
Write the specified module to the specified raw output stream.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
LLVM_ABI void writeThinLinkBitcodeToFile(const Module &M, raw_ostream &Out, const ModuleSummaryIndex &Index, const ModuleHash &ModHash)
Write the specified thin link bitcode file (i.e., the minimized bitcode file) to the given raw output...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI void writeIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out, const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex=nullptr, const GVSummaryPtrSet *DecSummaries=nullptr)
Write the specified module summary index to the given raw output stream, where it will be written in ...
LLVM_ABI void embedBitcodeInModule(Module &M, MemoryBufferRef Buf, bool EmbedBitcode, bool EmbedCmdline, const std::vector< uint8_t > &CmdArgs)
If EmbedBitcode is set, save a copy of the llvm IR as data in the __LLVM,__bitcode section (....
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
std::map< std::string, GVSummaryMapTy, std::less<> > ModuleToSummariesForIndexTy
Map of a module name to the GUIDs and summaries we will import from that module.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
AtomicOrdering
Atomic ordering for LLVM's memory model.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt copy(R &&Range, OutputIt Out)
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
bool isBitcode(const unsigned char *BufPtr, const unsigned char *BufEnd)
isBitcode - Return true if the given bytes are the magic bytes for LLVM IR bitcode,...
SmallPtrSet< GlobalValueSummary *, 0 > GVSummaryPtrSet
A set of global value summary pointers.
void consumeError(Error Err)
Consume a Error without doing anything.
LLVM_ABI Error write(DWPWriter &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue, Dwarf64StrOffsetsPromotion StrOffsetsOptValue, raw_pwrite_stream *OS=nullptr)
LLVM_ABI GlobalVariable * collectUsedGlobalVariables(const Module &M, SmallVectorImpl< GlobalValue * > &Vec, bool CompilerUsed)
Given "llvm.used" or "llvm.compiler.used" as a global name, collect the initializer elements of that ...
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
This struct is a compact representation of a valid (non-zero power of two) alignment.
static void set(StorageType &Packed, typename Bitfield::Type Value)
Sets the typed value in the provided Packed value.
Class to accumulate and hold information about a callee.
Flags specific to function summaries.
static constexpr uint32_t RangeWidth
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
static LLVM_ABI const Target * lookupTarget(const Triple &TheTriple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
Struct that holds a reference to a particular GUID in a global value summary.
uint64_t Info
Additional information for the resolution:
enum llvm::WholeProgramDevirtResolution::ByArg::Kind TheKind
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
std::string SingleImplName