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();
261 void writePerModuleFunctionSummaryRecord(
262 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
263 unsigned ValueID,
unsigned FSCallsProfileAbbrev,
unsigned CallsiteAbbrev,
264 unsigned AllocAbbrev,
unsigned ContextIdAbbvId,
const Function &
F,
265 DenseMap<CallStackId, LinearCallStackId> &CallStackPos,
267 void writeModuleLevelReferences(
const GlobalVariable &V,
268 SmallVector<uint64_t, 64> &NameVals,
269 unsigned FSModRefsAbbrev,
270 unsigned FSModVTableRefsAbbrev);
273 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
277 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
280 assert(VMI != GUIDToValueIdMap.end() &&
281 "GUID does not have assigned value Id");
286 unsigned getValueId(ValueInfo VI) {
287 if (!
VI.haveGVs() || !
VI.getValue())
288 return getValueId(
VI.getGUID());
292 std::map<GlobalValue::GUID, unsigned> &valueIds() {
return GUIDToValueIdMap; }
296class ModuleBitcodeWriter :
public ModuleBitcodeWriterBase {
307 uint64_t BitcodeStartBit;
312 ModuleBitcodeWriter(
const Module &M, StringTableBuilder &StrtabBuilder,
313 BitstreamWriter &Stream,
bool ShouldPreserveUseListOrder,
314 const ModuleSummaryIndex *Index,
bool GenerateHash,
316 : ModuleBitcodeWriterBase(
M, StrtabBuilder, Stream,
317 ShouldPreserveUseListOrder,
Index),
318 GenerateHash(GenerateHash), ModHash(ModHash),
319 BitcodeStartBit(Stream.GetCurrentBitNo()) {}
325 uint64_t bitcodeStartBit() {
return BitcodeStartBit; }
327 size_t addToStrtab(StringRef Str);
329 void writeAttributeGroupTable();
330 void writeAttributeTable();
331 void writeTypeTable();
333 void writeValueSymbolTableForwardDecl();
334 void writeModuleInfo();
335 void writeValueAsMetadata(
const ValueAsMetadata *MD,
336 SmallVectorImpl<uint64_t> &Record);
337 void writeMDTuple(
const MDTuple *
N, SmallVectorImpl<uint64_t> &Record,
339 unsigned createDILocationAbbrev();
340 void writeDILocation(
const DILocation *
N, SmallVectorImpl<uint64_t> &Record,
342 unsigned createGenericDINodeAbbrev();
344 SmallVectorImpl<uint64_t> &Record,
unsigned &Abbrev);
345 void writeDISubrange(
const DISubrange *
N, SmallVectorImpl<uint64_t> &Record,
348 SmallVectorImpl<uint64_t> &Record,
351 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
355 SmallVectorImpl<uint64_t> &Record,
358 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
360 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
362 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
364 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
366 SmallVectorImpl<uint64_t> &Record,
368 void writeDIFile(
const DIFile *
N, SmallVectorImpl<uint64_t> &Record,
371 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
373 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
375 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
377 SmallVectorImpl<uint64_t> &Record,
380 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
383 void writeDIMacro(
const DIMacro *
N, SmallVectorImpl<uint64_t> &Record,
387 void writeDIArgList(
const DIArgList *
N, SmallVectorImpl<uint64_t> &Record);
388 void writeDIModule(
const DIModule *
N, SmallVectorImpl<uint64_t> &Record,
390 void writeDIAssignID(
const DIAssignID *
N, SmallVectorImpl<uint64_t> &Record,
393 SmallVectorImpl<uint64_t> &Record,
396 SmallVectorImpl<uint64_t> &Record,
399 SmallVectorImpl<uint64_t> &Record,
402 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
404 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
406 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
408 SmallVectorImpl<uint64_t> &Record,
411 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
413 SmallVectorImpl<uint64_t> &Record,
415 unsigned createNamedMetadataAbbrev();
416 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
417 unsigned createMetadataStringsAbbrev();
419 SmallVectorImpl<uint64_t> &Record);
421 SmallVectorImpl<uint64_t> &Record,
422 std::vector<unsigned> *MDAbbrevs =
nullptr,
423 std::vector<uint64_t> *IndexPos =
nullptr);
424 void writeModuleMetadata();
425 void writeFunctionMetadata(
const Function &
F);
426 void writeFunctionMetadataAttachment(
const Function &
F);
427 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
428 const GlobalObject &GO);
429 void writeModuleMetadataKinds();
430 void writeOperandBundleTags();
431 void writeSyncScopeNames();
432 void writeConstants(
unsigned FirstVal,
unsigned LastVal,
bool isGlobal);
433 void writeModuleConstants();
434 bool pushValueAndType(
const Value *V,
unsigned InstID,
435 SmallVectorImpl<unsigned> &Vals);
436 bool pushValueOrMetadata(
const Value *V,
unsigned InstID,
437 SmallVectorImpl<unsigned> &Vals);
438 void writeOperandBundles(
const CallBase &CB,
unsigned InstID);
439 void pushValue(
const Value *V,
unsigned InstID,
440 SmallVectorImpl<unsigned> &Vals);
441 void pushValueSigned(
const Value *V,
unsigned InstID,
442 SmallVectorImpl<uint64_t> &Vals);
443 void writeInstruction(
const Instruction &
I,
unsigned InstID,
444 SmallVectorImpl<unsigned> &Vals);
445 void writeFunctionLevelValueSymbolTable(
const ValueSymbolTable &VST);
446 void writeGlobalValueSymbolTable(
447 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
448 void writeUseList(UseListOrder &&Order);
449 void writeUseListBlock(
const Function *
F);
451 writeFunction(
const Function &
F,
452 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
453 void writeBlockInfo();
454 void writeModuleHash(StringRef View);
457 return unsigned(SSID);
460 unsigned getEncodedAlign(MaybeAlign Alignment) {
return encode(Alignment); }
464class IndexBitcodeWriter :
public BitcodeWriterBase {
466 const ModuleSummaryIndex &
Index;
479 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
483 std::vector<uint64_t> StackIds;
488 DenseMap<unsigned, unsigned> StackIdIndicesToIndex;
491 unsigned GlobalValueId = 0;
495 DenseMap<StringRef, uint64_t> ModuleIdMap;
505 BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
506 const ModuleSummaryIndex &Index,
509 : BitcodeWriterBase(Stream, StrtabBuilder),
Index(
Index),
510 DecSummaries(DecSummaries),
511 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
515 auto RecordStackIdReference = [&](
unsigned StackIdIndex) {
520 StackIdIndicesToIndex.
insert({StackIdIndex, StackIds.size()});
522 StackIds.push_back(
Index.getStackIdAtIndex(StackIdIndex));
529 forEachSummary([&](GVInfo
I,
bool IsAliasee) {
530 GUIDToValueIdMap[
I.first] = ++GlobalValueId;
542 for (
auto &CI :
FS->callsites()) {
553 if (CI.StackIdIndices.empty()) {
554 GUIDToValueIdMap[CI.Callee.getGUID()] = ++GlobalValueId;
557 for (
auto Idx : CI.StackIdIndices)
558 RecordStackIdReference(Idx);
561 for (
auto &AI :
FS->allocs())
562 for (
auto &MIB : AI.MIBs)
563 for (
auto Idx : MIB.StackIdIndices)
564 RecordStackIdReference(Idx);
570 using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
575 template<
typename Functor>
576 void forEachSummary(Functor Callback) {
577 if (ModuleToSummariesForIndex) {
578 for (
auto &M : *ModuleToSummariesForIndex)
579 for (
auto &Summary :
M.second) {
585 Callback({AS->getAliaseeGUID(), &AS->getAliasee()},
true);
589 for (
const auto &Summaries :
Index.sortedGlobalValueSummariesRange())
590 for (
auto &Summary : Summaries.second.getSummaryList())
599 template <
typename Functor>
void forEachModule(Functor Callback) {
600 if (ModuleToSummariesForIndex) {
601 for (
const auto &M : *ModuleToSummariesForIndex) {
602 const auto &MPI =
Index.modulePaths().find(
M.first);
603 if (MPI ==
Index.modulePaths().end()) {
607 assert(ModuleToSummariesForIndex->size() == 1);
617 std::vector<StringRef> ModulePaths;
618 for (
auto &[ModPath,
_] :
Index.modulePaths())
619 ModulePaths.push_back(ModPath);
621 for (
auto &ModPath : ModulePaths)
630 void writeModStrings();
631 void writeCombinedGlobalValueSummary();
634 auto VMI = GUIDToValueIdMap.find(ValGUID);
635 if (VMI == GUIDToValueIdMap.end())
640 std::map<GlobalValue::GUID, unsigned> &valueIds() {
return GUIDToValueIdMap; }
675 case Instruction::Add:
677 case Instruction::Sub:
679 case Instruction::Mul:
682 case Instruction::FDiv:
685 case Instruction::FRem:
697 unsigned Encoding = 0;
698 switch (
I.getOperation()) {
771 if (
I.isElementwise())
806 case Attribute::Alignment:
808 case Attribute::AllocAlign:
810 case Attribute::AllocSize:
812 case Attribute::AlwaysInline:
814 case Attribute::Builtin:
816 case Attribute::ByVal:
818 case Attribute::Convergent:
820 case Attribute::InAlloca:
822 case Attribute::Cold:
824 case Attribute::DisableSanitizerInstrumentation:
826 case Attribute::FnRetThunkExtern:
828 case Attribute::Flatten:
832 case Attribute::ElementType:
834 case Attribute::HybridPatchable:
836 case Attribute::InlineHint:
838 case Attribute::InReg:
840 case Attribute::JumpTable:
842 case Attribute::MinSize:
844 case Attribute::AllocatedPointer:
846 case Attribute::AllocKind:
848 case Attribute::Memory:
850 case Attribute::NoFPClass:
852 case Attribute::Naked:
854 case Attribute::Nest:
856 case Attribute::NoAlias:
858 case Attribute::NoBuiltin:
860 case Attribute::NoCallback:
862 case Attribute::NoDivergenceSource:
864 case Attribute::NoDuplicate:
866 case Attribute::NoFree:
868 case Attribute::NoImplicitFloat:
870 case Attribute::NoInline:
872 case Attribute::NoRecurse:
874 case Attribute::NoMerge:
876 case Attribute::NonLazyBind:
878 case Attribute::NonNull:
880 case Attribute::Dereferenceable:
882 case Attribute::DereferenceableOrNull:
884 case Attribute::NoRedZone:
886 case Attribute::NoReturn:
888 case Attribute::NoSync:
890 case Attribute::NoCfCheck:
892 case Attribute::NoProfile:
894 case Attribute::SkipProfile:
896 case Attribute::NoUnwind:
898 case Attribute::NoSanitizeBounds:
900 case Attribute::NoSanitizeCoverage:
902 case Attribute::NullPointerIsValid:
904 case Attribute::OptimizeForDebugging:
906 case Attribute::OptForFuzzing:
908 case Attribute::OptimizeForSize:
910 case Attribute::OptimizeNone:
912 case Attribute::ReadNone:
914 case Attribute::ReadOnly:
916 case Attribute::Returned:
918 case Attribute::ReturnsTwice:
920 case Attribute::SExt:
922 case Attribute::Speculatable:
924 case Attribute::StackAlignment:
926 case Attribute::StackProtect:
928 case Attribute::StackProtectReq:
930 case Attribute::StackProtectStrong:
932 case Attribute::SafeStack:
934 case Attribute::ShadowCallStack:
936 case Attribute::StrictFP:
938 case Attribute::StructRet:
940 case Attribute::SanitizeAddress:
942 case Attribute::SanitizeAllocToken:
944 case Attribute::SanitizeHWAddress:
946 case Attribute::SanitizeThread:
948 case Attribute::SanitizeType:
950 case Attribute::SanitizeMemory:
952 case Attribute::SanitizeNumericalStability:
954 case Attribute::SanitizeRealtime:
956 case Attribute::SanitizeRealtimeBlocking:
958 case Attribute::SpeculativeLoadHardening:
960 case Attribute::SwiftError:
962 case Attribute::SwiftSelf:
964 case Attribute::SwiftAsync:
966 case Attribute::UWTable:
968 case Attribute::VScaleRange:
970 case Attribute::WillReturn:
972 case Attribute::WriteOnly:
974 case Attribute::ZExt:
976 case Attribute::ImmArg:
978 case Attribute::SanitizeMemTag:
980 case Attribute::Preallocated:
982 case Attribute::NoUndef:
984 case Attribute::ByRef:
986 case Attribute::MustProgress:
988 case Attribute::PresplitCoroutine:
990 case Attribute::Writable:
992 case Attribute::CoroDestroyOnlyWhenComplete:
994 case Attribute::CoroElideSafe:
996 case Attribute::DeadOnUnwind:
998 case Attribute::Range:
1000 case Attribute::Initializes:
1002 case Attribute::NoExt:
1004 case Attribute::Captures:
1006 case Attribute::DeadOnReturn:
1008 case Attribute::NoCreateUndefOrPoison:
1010 case Attribute::DenormalFPEnv:
1012 case Attribute::NoOutline:
1014 case Attribute::NoIPA:
1029 if ((int64_t)V >= 0)
1040 unsigned NumWords =
A.getActiveWords();
1041 const uint64_t *RawData =
A.getRawData();
1042 for (
unsigned i = 0; i < NumWords; i++)
1062void ModuleBitcodeWriter::writeAttributeGroupTable() {
1063 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
1065 if (AttrGrps.empty())
return;
1069 SmallVector<uint64_t, 64>
Record;
1071 unsigned AttrListIndex = Pair.first;
1072 AttributeSet AS = Pair.second;
1074 Record.push_back(AttrListIndex);
1077 if (Attr.isEnumAttribute()) {
1080 }
else if (Attr.isIntAttribute()) {
1082 Attribute::AttrKind
Kind = Attr.getKindAsEnum();
1084 if (Kind == Attribute::Memory) {
1089 Record.push_back(Attr.getValueAsInt());
1091 }
else if (Attr.isStringAttribute()) {
1092 StringRef
Kind = Attr.getKindAsString();
1093 StringRef Val = Attr.getValueAsString();
1102 }
else if (Attr.isTypeAttribute()) {
1103 Type *Ty = Attr.getValueAsType();
1104 Record.push_back(Ty ? 6 : 5);
1108 }
else if (Attr.isConstantRangeAttribute()) {
1114 assert(Attr.isConstantRangeListAttribute());
1120 for (
auto &CR : Val)
1132void ModuleBitcodeWriter::writeAttributeTable() {
1134 if (
Attrs.empty())
return;
1138 SmallVector<uint64_t, 64>
Record;
1139 for (
const AttributeList &AL : Attrs) {
1140 for (
unsigned i :
AL.indexes()) {
1141 AttributeSet AS =
AL.getAttributes(i);
1154void ModuleBitcodeWriter::writeTypeTable() {
1158 SmallVector<uint64_t, 64> TypeVals;
1163 auto Abbv = std::make_shared<BitCodeAbbrev>();
1165 Abbv->Add(BitCodeAbbrevOp(0));
1166 unsigned OpaquePtrAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1169 Abbv = std::make_shared<BitCodeAbbrev>();
1174 unsigned FunctionAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1177 Abbv = std::make_shared<BitCodeAbbrev>();
1182 unsigned StructAnonAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1185 Abbv = std::make_shared<BitCodeAbbrev>();
1189 unsigned StructNameAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1192 Abbv = std::make_shared<BitCodeAbbrev>();
1197 unsigned StructNamedAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1200 Abbv = std::make_shared<BitCodeAbbrev>();
1204 unsigned ArrayAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1212 for (
Type *
T : TypeList) {
1213 int AbbrevToUse = 0;
1216 switch (
T->getTypeID()) {
1226 case Type::MetadataTyID:
1231 case Type::ByteTyID:
1236 case Type::IntegerTyID:
1241 case Type::PointerTyID: {
1248 AbbrevToUse = OpaquePtrAbbrev;
1251 case Type::FunctionTyID: {
1257 for (
unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
1259 AbbrevToUse = FunctionAbbrev;
1262 case Type::StructTyID: {
1267 for (
Type *ET :
ST->elements())
1270 if (
ST->isLiteral()) {
1272 AbbrevToUse = StructAnonAbbrev;
1274 if (
ST->isOpaque()) {
1278 AbbrevToUse = StructNamedAbbrev;
1282 if (!
ST->getName().empty())
1288 case Type::ArrayTyID: {
1292 TypeVals.
push_back(AT->getNumElements());
1294 AbbrevToUse = ArrayAbbrev;
1297 case Type::FixedVectorTyID:
1298 case Type::ScalableVectorTyID: {
1303 TypeVals.
push_back(VT->getElementCount().getKnownMinValue());
1309 case Type::TargetExtTyID: {
1315 for (
Type *InnerTy :
TET->type_params())
1320 case Type::TypedPointerTyID:
1325 Stream.
EmitRecord(Code, TypeVals, AbbrevToUse);
1366 RawFlags |= Flags.ReadNone;
1367 RawFlags |= (Flags.ReadOnly << 1);
1368 RawFlags |= (Flags.NoRecurse << 2);
1369 RawFlags |= (Flags.ReturnDoesNotAlias << 3);
1370 RawFlags |= (Flags.NoInline << 4);
1371 RawFlags |= (Flags.AlwaysInline << 5);
1372 RawFlags |= (Flags.NoUnwind << 6);
1373 RawFlags |= (Flags.MayThrow << 7);
1374 RawFlags |= (Flags.HasUnknownCall << 8);
1375 RawFlags |= (Flags.MustBeUnreachable << 9);
1382 bool ImportAsDecl =
false) {
1385 RawFlags |= Flags.NotEligibleToImport;
1386 RawFlags |= (Flags.Live << 1);
1387 RawFlags |= (Flags.DSOLocal << 2);
1388 RawFlags |= (Flags.CanAutoHide << 3);
1393 RawFlags = (RawFlags << 4) | Flags.Linkage;
1395 RawFlags |= (Flags.Visibility << 8);
1397 unsigned ImportType = Flags.ImportType | ImportAsDecl;
1398 RawFlags |= (ImportType << 10);
1400 RawFlags |= (Flags.NoRenameOnPromotion << 11);
1406 uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) |
1407 (Flags.Constant << 2) | Flags.VCallVisibility << 3;
1450 switch (
C.getSelectionKind()) {
1474size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1477 return StrtabBuilder.
add(Str);
1480void ModuleBitcodeWriter::writeComdats() {
1495void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
1500 auto Abbv = std::make_shared<BitCodeAbbrev>();
1506 unsigned VSTOffsetAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1522 bool isChar6 =
true;
1523 for (
char C : Str) {
1526 if ((
unsigned char)
C & 128)
1535static_assert(
sizeof(GlobalValue::SanitizerMetadata) <=
sizeof(unsigned),
1536 "Sanitizer Metadata is too large for naive serialization.");
1539 return Meta.NoAddress | (
Meta.NoHWAddress << 1) |
1540 (
Meta.Memtag << 2) | (
Meta.IsDynInit << 3);
1546void ModuleBitcodeWriter::writeModuleInfo() {
1548 if (!
M.getTargetTriple().empty())
1550 M.getTargetTriple().str(), 0 );
1551 const std::string &
DL =
M.getDataLayoutStr();
1554 if (!
M.getModuleInlineAsm().empty())
1560 std::map<std::string, unsigned> SectionMap;
1561 std::map<std::string, unsigned> GCMap;
1562 MaybeAlign MaxGVarAlignment;
1563 unsigned MaxGlobalType = 0;
1564 for (
const GlobalVariable &GV :
M.globals()) {
1565 if (MaybeAlign
A = GV.getAlign())
1566 MaxGVarAlignment = !MaxGVarAlignment ? *
A : std::max(*MaxGVarAlignment, *
A);
1567 MaxGlobalType = std::max(MaxGlobalType, VE.
getTypeID(GV.getValueType()));
1568 if (GV.hasSection()) {
1570 unsigned &
Entry = SectionMap[std::string(GV.getSection())];
1574 Entry = SectionMap.size();
1578 for (
const Function &
F : M) {
1579 if (
F.hasSection()) {
1581 unsigned &
Entry = SectionMap[std::string(
F.getSection())];
1585 Entry = SectionMap.size();
1590 unsigned &
Entry = GCMap[
F.getGC()];
1594 Entry = GCMap.size();
1600 unsigned SimpleGVarAbbrev = 0;
1601 if (!
M.global_empty()) {
1603 auto Abbv = std::make_shared<BitCodeAbbrev>();
1614 if (!MaxGVarAlignment)
1615 Abbv->Add(BitCodeAbbrevOp(0));
1617 unsigned MaxEncAlignment = getEncodedAlign(MaxGVarAlignment);
1621 if (SectionMap.empty())
1622 Abbv->Add(BitCodeAbbrevOp(0));
1627 SimpleGVarAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1641 auto Abbv = std::make_shared<BitCodeAbbrev>();
1644 Abbv->Add(AbbrevOpToUse);
1645 unsigned FilenameAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1647 for (
const auto P :
M.getSourceFileName())
1656 for (
const GlobalVariable &GV :
M.globals()) {
1657 unsigned AbbrevToUse = 0;
1663 Vals.
push_back(addToStrtab(GV.getName()));
1666 Vals.
push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1670 Vals.
push_back(getEncodedAlign(GV.getAlign()));
1671 Vals.
push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]
1673 if (GV.isThreadLocal() ||
1675 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1676 GV.isExternallyInitialized() ||
1678 GV.hasComdat() || GV.hasAttributes() || GV.isDSOLocal() ||
1679 GV.hasPartition() || GV.hasSanitizerMetadata() || GV.getCodeModel()) {
1683 Vals.
push_back(GV.isExternallyInitialized());
1687 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1691 Vals.
push_back(addToStrtab(GV.getPartition()));
1692 Vals.
push_back(GV.getPartition().size());
1695 GV.getSanitizerMetadata())
1699 AbbrevToUse = SimpleGVarAbbrev;
1707 for (
const Function &
F : M) {
1720 Vals.
push_back(getEncodedAlign(
F.getAlign()));
1721 Vals.
push_back(
F.hasSection() ? SectionMap[std::string(
F.getSection())]
1733 F.hasPersonalityFn() ? (VE.
getValueID(
F.getPersonalityFn()) + 1) : 0);
1737 Vals.
push_back(addToStrtab(
F.getPartition()));
1739 Vals.
push_back(getEncodedAlign(
F.getPreferredAlignment()));
1741 unsigned AbbrevToUse = 0;
1747 for (
const GlobalAlias &
A :
M.aliases()) {
1754 Vals.
push_back(
A.getType()->getAddressSpace());
1762 Vals.
push_back(addToStrtab(
A.getPartition()));
1765 unsigned AbbrevToUse = 0;
1771 for (
const GlobalIFunc &
I :
M.ifuncs()) {
1777 Vals.
push_back(
I.getType()->getAddressSpace());
1782 Vals.
push_back(addToStrtab(
I.getPartition()));
1788 writeValueSymbolTableForwardDecl();
1795 if (OBO->hasNoSignedWrap())
1797 if (OBO->hasNoUnsignedWrap())
1803 if (PDI->isDisjoint())
1806 if (FPMO->hasAllowReassoc())
1808 if (FPMO->hasNoNaNs())
1810 if (FPMO->hasNoInfs())
1812 if (FPMO->hasNoSignedZeros())
1814 if (FPMO->hasAllowReciprocal())
1816 if (FPMO->hasAllowContract())
1818 if (FPMO->hasApproxFunc())
1824 if (NNI->hasNonNeg())
1828 if (NNI->hasNonNeg())
1831 if (TI->hasNoSignedWrap())
1833 if (TI->hasNoUnsignedWrap())
1836 if (
GEP->isInBounds())
1838 if (
GEP->hasNoUnsignedSignedWrap())
1840 if (
GEP->hasNoUnsignedWrap())
1843 if (ICmp->hasSameSign())
1850void ModuleBitcodeWriter::writeValueAsMetadata(
1851 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
1860void ModuleBitcodeWriter::writeMDTuple(
const MDTuple *
N,
1861 SmallVectorImpl<uint64_t> &Record,
1863 for (
const MDOperand &MDO :
N->operands()) {
1866 "Unexpected function-local metadata");
1875unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
1878 auto Abbv = std::make_shared<BitCodeAbbrev>();
1891void ModuleBitcodeWriter::writeDILocation(
const DILocation *
N,
1892 SmallVectorImpl<uint64_t> &Record,
1895 Abbrev = createDILocationAbbrev();
1897 Record.push_back(
N->isDistinct());
1898 Record.push_back(
N->getLine());
1899 Record.push_back(
N->getColumn());
1902 Record.push_back(
N->isImplicitCode());
1903 Record.push_back(
N->getAtomGroup());
1904 Record.push_back(
N->getAtomRank());
1909unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1912 auto Abbv = std::make_shared<BitCodeAbbrev>();
1923void ModuleBitcodeWriter::writeGenericDINode(
const GenericDINode *
N,
1924 SmallVectorImpl<uint64_t> &Record,
1927 Abbrev = createGenericDINodeAbbrev();
1929 Record.push_back(
N->isDistinct());
1930 Record.push_back(
N->getTag());
1933 for (
auto &
I :
N->operands())
1940void ModuleBitcodeWriter::writeDISubrange(
const DISubrange *
N,
1941 SmallVectorImpl<uint64_t> &Record,
1943 const uint64_t
Version = 2 << 1;
1954void ModuleBitcodeWriter::writeDIGenericSubrange(
1955 const DIGenericSubrange *
N, SmallVectorImpl<uint64_t> &Record,
1957 Record.push_back((uint64_t)
N->isDistinct());
1967void ModuleBitcodeWriter::writeDIEnumerator(
const DIEnumerator *
N,
1968 SmallVectorImpl<uint64_t> &Record,
1970 const uint64_t IsBigInt = 1 << 2;
1971 Record.push_back(IsBigInt | (
N->isUnsigned() << 1) |
N->isDistinct());
1972 Record.push_back(
N->getValue().getBitWidth());
1980void ModuleBitcodeWriter::writeDIBasicType(
const DIBasicType *
N,
1981 SmallVectorImpl<uint64_t> &Record,
1983 const unsigned SizeIsMetadata = 0x2;
1984 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
1985 Record.push_back(
N->getTag());
1988 Record.push_back(
N->getAlignInBits());
1989 Record.push_back(
N->getEncoding());
1990 Record.push_back(
N->getFlags());
1991 Record.push_back(
N->getNumExtraInhabitants());
1992 Record.push_back(
N->getDataSizeInBits());
1994 Record.push_back(
N->getLine());
2001void ModuleBitcodeWriter::writeDIFixedPointType(
2002 const DIFixedPointType *
N, SmallVectorImpl<uint64_t> &Record,
2004 const unsigned SizeIsMetadata = 0x2;
2005 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2006 Record.push_back(
N->getTag());
2009 Record.push_back(
N->getAlignInBits());
2010 Record.push_back(
N->getEncoding());
2011 Record.push_back(
N->getFlags());
2012 Record.push_back(
N->getKind());
2013 Record.push_back(
N->getFactorRaw());
2015 auto WriteWideInt = [&](
const APInt &
Value) {
2018 uint64_t NumWords =
Value.getActiveWords();
2019 uint64_t
Encoded = (NumWords << 32) |
Value.getBitWidth();
2020 Record.push_back(Encoded);
2024 WriteWideInt(
N->getNumeratorRaw());
2025 WriteWideInt(
N->getDenominatorRaw());
2028 Record.push_back(
N->getLine());
2035void ModuleBitcodeWriter::writeDIStringType(
const DIStringType *
N,
2036 SmallVectorImpl<uint64_t> &Record,
2038 const unsigned SizeIsMetadata = 0x2;
2039 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2040 Record.push_back(
N->getTag());
2046 Record.push_back(
N->getAlignInBits());
2047 Record.push_back(
N->getEncoding());
2053void ModuleBitcodeWriter::writeDIDerivedType(
const DIDerivedType *
N,
2054 SmallVectorImpl<uint64_t> &Record,
2056 const unsigned SizeIsMetadata = 0x2;
2057 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2058 Record.push_back(
N->getTag());
2061 Record.push_back(
N->getLine());
2065 Record.push_back(
N->getAlignInBits());
2067 Record.push_back(
N->getFlags());
2072 if (
const auto &DWARFAddressSpace =
N->getDWARFAddressSpace())
2073 Record.push_back(*DWARFAddressSpace + 1);
2079 if (
auto PtrAuthData =
N->getPtrAuthData())
2080 Record.push_back(PtrAuthData->RawData);
2088void ModuleBitcodeWriter::writeDISubrangeType(
const DISubrangeType *
N,
2089 SmallVectorImpl<uint64_t> &Record,
2091 const unsigned SizeIsMetadata = 0x2;
2092 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2095 Record.push_back(
N->getLine());
2098 Record.push_back(
N->getAlignInBits());
2099 Record.push_back(
N->getFlags());
2110void ModuleBitcodeWriter::writeDICompositeType(
2111 const DICompositeType *
N, SmallVectorImpl<uint64_t> &Record,
2113 const unsigned IsNotUsedInOldTypeRef = 0x2;
2114 const unsigned SizeIsMetadata = 0x4;
2115 Record.push_back(SizeIsMetadata | IsNotUsedInOldTypeRef |
2116 (
unsigned)
N->isDistinct());
2117 Record.push_back(
N->getTag());
2120 Record.push_back(
N->getLine());
2124 Record.push_back(
N->getAlignInBits());
2126 Record.push_back(
N->getFlags());
2128 Record.push_back(
N->getRuntimeLang());
2138 Record.push_back(
N->getNumExtraInhabitants());
2148void ModuleBitcodeWriter::writeDISubroutineType(
2149 const DISubroutineType *
N, SmallVectorImpl<uint64_t> &Record,
2151 const unsigned HasNoOldTypeRefs = 0x2;
2152 Record.push_back(HasNoOldTypeRefs | (
unsigned)
N->isDistinct());
2153 Record.push_back(
N->getFlags());
2161void ModuleBitcodeWriter::writeDIFile(
const DIFile *
N,
2162 SmallVectorImpl<uint64_t> &Record,
2164 Record.push_back(
N->isDistinct());
2167 if (
N->getRawChecksum()) {
2168 Record.push_back(
N->getRawChecksum()->Kind);
2176 auto Source =
N->getRawSource();
2184void ModuleBitcodeWriter::writeDICompileUnit(
const DICompileUnit *
N,
2185 SmallVectorImpl<uint64_t> &Record,
2187 assert(
N->isDistinct() &&
"Expected distinct compile units");
2190 auto Lang =
N->getSourceLanguage();
2191 Record.push_back(Lang.getName());
2194 if (Lang.hasVersionedName())
2195 Record.back() ^= (uint64_t(1) << 63);
2199 Record.push_back(
N->isOptimized());
2201 Record.push_back(
N->getRuntimeVersion());
2203 Record.push_back(
N->getEmissionKind());
2209 Record.push_back(
N->getDWOId());
2211 Record.push_back(
N->getSplitDebugInlining());
2212 Record.push_back(
N->getDebugInfoForProfiling());
2213 Record.push_back((
unsigned)
N->getNameTableKind());
2214 Record.push_back(
N->getRangesBaseAddress());
2217 Record.push_back(Lang.hasVersionedName() ? Lang.getVersion() : 0);
2218 Record.push_back(Lang.getDialect());
2224void ModuleBitcodeWriter::writeDISubprogram(
const DISubprogram *
N,
2225 SmallVectorImpl<uint64_t> &Record,
2227 const uint64_t HasUnitFlag = 1 << 1;
2228 const uint64_t HasSPFlagsFlag = 1 << 2;
2229 Record.push_back(uint64_t(
N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
2234 Record.push_back(
N->getLine());
2236 Record.push_back(
N->getScopeLine());
2238 Record.push_back(
N->getSPFlags());
2239 Record.push_back(
N->getVirtualIndex());
2240 Record.push_back(
N->getFlags());
2245 Record.push_back(
N->getThisAdjustment());
2249 Record.push_back(
N->getKeyInstructionsEnabled());
2255void ModuleBitcodeWriter::writeDILexicalBlock(
const DILexicalBlock *
N,
2256 SmallVectorImpl<uint64_t> &Record,
2258 Record.push_back(
N->isDistinct());
2261 Record.push_back(
N->getLine());
2262 Record.push_back(
N->getColumn());
2268void ModuleBitcodeWriter::writeDILexicalBlockFile(
2269 const DILexicalBlockFile *
N, SmallVectorImpl<uint64_t> &Record,
2271 Record.push_back(
N->isDistinct());
2274 Record.push_back(
N->getDiscriminator());
2280void ModuleBitcodeWriter::writeDICommonBlock(
const DICommonBlock *
N,
2281 SmallVectorImpl<uint64_t> &Record,
2283 Record.push_back(
N->isDistinct());
2288 Record.push_back(
N->getLineNo());
2294void ModuleBitcodeWriter::writeDINamespace(
const DINamespace *
N,
2295 SmallVectorImpl<uint64_t> &Record,
2297 Record.push_back(
N->isDistinct() |
N->getExportSymbols() << 1);
2305void ModuleBitcodeWriter::writeDIMacro(
const DIMacro *
N,
2306 SmallVectorImpl<uint64_t> &Record,
2308 Record.push_back(
N->isDistinct());
2309 Record.push_back(
N->getMacinfoType());
2310 Record.push_back(
N->getLine());
2318void ModuleBitcodeWriter::writeDIMacroFile(
const DIMacroFile *
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::writeDIArgList(
const DIArgList *
N,
2332 SmallVectorImpl<uint64_t> &Record) {
2333 Record.reserve(
N->getArgs().size());
2334 for (ValueAsMetadata *MD :
N->getArgs())
2341void ModuleBitcodeWriter::writeDIModule(
const DIModule *
N,
2342 SmallVectorImpl<uint64_t> &Record,
2344 Record.push_back(
N->isDistinct());
2345 for (
auto &
I :
N->operands())
2347 Record.push_back(
N->getLineNo());
2348 Record.push_back(
N->getIsDecl());
2354void ModuleBitcodeWriter::writeDIAssignID(
const DIAssignID *
N,
2355 SmallVectorImpl<uint64_t> &Record,
2358 Record.push_back(
N->isDistinct());
2363void ModuleBitcodeWriter::writeDITemplateTypeParameter(
2364 const DITemplateTypeParameter *
N, SmallVectorImpl<uint64_t> &Record,
2366 Record.push_back(
N->isDistinct());
2369 Record.push_back(
N->isDefault());
2375void ModuleBitcodeWriter::writeDITemplateValueParameter(
2376 const DITemplateValueParameter *
N, SmallVectorImpl<uint64_t> &Record,
2378 Record.push_back(
N->isDistinct());
2379 Record.push_back(
N->getTag());
2382 Record.push_back(
N->isDefault());
2389void ModuleBitcodeWriter::writeDIGlobalVariable(
2390 const DIGlobalVariable *
N, SmallVectorImpl<uint64_t> &Record,
2392 const uint64_t
Version = 2 << 1;
2398 Record.push_back(
N->getLine());
2400 Record.push_back(
N->isLocalToUnit());
2401 Record.push_back(
N->isDefinition());
2404 Record.push_back(
N->getAlignInBits());
2411void ModuleBitcodeWriter::writeDILocalVariable(
2412 const DILocalVariable *
N, SmallVectorImpl<uint64_t> &Record,
2427 const uint64_t HasAlignmentFlag = 1 << 1;
2428 Record.push_back((uint64_t)
N->isDistinct() | HasAlignmentFlag);
2432 Record.push_back(
N->getLine());
2434 Record.push_back(
N->getArg());
2435 Record.push_back(
N->getFlags());
2436 Record.push_back(
N->getAlignInBits());
2443void ModuleBitcodeWriter::writeDILabel(
2444 const DILabel *
N, SmallVectorImpl<uint64_t> &Record,
2446 uint64_t IsArtificialFlag = uint64_t(
N->isArtificial()) << 1;
2447 Record.push_back((uint64_t)
N->isDistinct() | IsArtificialFlag);
2451 Record.push_back(
N->getLine());
2452 Record.push_back(
N->getColumn());
2453 Record.push_back(
N->getCoroSuspendIdx().has_value()
2454 ? (uint64_t)
N->getCoroSuspendIdx().value()
2455 : std::numeric_limits<uint64_t>::max());
2461void ModuleBitcodeWriter::writeDIExpression(
const DIExpression *
N,
2462 SmallVectorImpl<uint64_t> &Record,
2464 Record.reserve(
N->getElements().size() + 1);
2465 const uint64_t
Version = 3 << 1;
2467 Record.append(
N->elements_begin(),
N->elements_end());
2473void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
2474 const DIGlobalVariableExpression *
N, SmallVectorImpl<uint64_t> &Record,
2476 Record.push_back(
N->isDistinct());
2484void ModuleBitcodeWriter::writeDIObjCProperty(
const DIObjCProperty *
N,
2485 SmallVectorImpl<uint64_t> &Record,
2487 Record.push_back(
N->isDistinct());
2490 Record.push_back(
N->getLine());
2493 Record.push_back(
N->getAttributes());
2500void ModuleBitcodeWriter::writeDIImportedEntity(
2501 const DIImportedEntity *
N, SmallVectorImpl<uint64_t> &Record,
2503 Record.push_back(
N->isDistinct());
2504 Record.push_back(
N->getTag());
2507 Record.push_back(
N->getLine());
2516unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
2517 auto Abbv = std::make_shared<BitCodeAbbrev>();
2524void ModuleBitcodeWriter::writeNamedMetadata(
2525 SmallVectorImpl<uint64_t> &Record) {
2526 if (
M.named_metadata_empty())
2529 unsigned Abbrev = createNamedMetadataAbbrev();
2530 for (
const NamedMDNode &NMD :
M.named_metadata()) {
2532 StringRef Str = NMD.getName();
2533 Record.append(Str.bytes_begin(), Str.bytes_end());
2538 for (
const MDNode *
N : NMD.operands())
2545unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
2546 auto Abbv = std::make_shared<BitCodeAbbrev>();
2558void ModuleBitcodeWriter::writeMetadataStrings(
2560 if (Strings.
empty())
2568 SmallString<256> Blob;
2570 BitstreamWriter
W(Blob);
2590#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
2591#include "llvm/IR/Metadata.def"
2595void ModuleBitcodeWriter::writeMetadataRecords(
2597 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
2602#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
2603#include "llvm/IR/Metadata.def"
2609 assert(
N->isResolved() &&
"Expected forward references to be resolved");
2611 switch (
N->getMetadataID()) {
2614#define HANDLE_MDNODE_LEAF(CLASS) \
2615 case Metadata::CLASS##Kind: \
2617 write##CLASS(cast<CLASS>(N), Record, \
2618 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
2620 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
2622#include "llvm/IR/Metadata.def"
2633void ModuleBitcodeWriter::writeModuleMetadata() {
2634 if (!VE.
hasMDs() &&
M.named_metadata_empty())
2638 SmallVector<uint64_t, 64>
Record;
2642 std::vector<unsigned> MDAbbrevs;
2645 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
2646 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
2647 createGenericDINodeAbbrev();
2649 auto Abbv = std::make_shared<BitCodeAbbrev>();
2653 unsigned OffsetAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
2655 Abbv = std::make_shared<BitCodeAbbrev>();
2659 unsigned IndexAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
2671 uint64_t Vals[] = {0, 0};
2681 std::vector<uint64_t> IndexPos;
2685 writeMetadataRecords(VE.
getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2696 uint64_t PreviousValue = IndexOffsetRecordBitPos;
2697 for (
auto &Elt : IndexPos) {
2698 auto EltDelta = Elt - PreviousValue;
2699 PreviousValue = Elt;
2708 writeNamedMetadata(Record);
2710 auto AddDeclAttachedMetadata = [&](
const GlobalObject &GO) {
2711 SmallVector<uint64_t, 4>
Record;
2713 pushGlobalMetadataAttachment(Record, GO);
2716 for (
const Function &
F : M)
2717 if (
F.isDeclaration() &&
F.hasMetadata())
2718 AddDeclAttachedMetadata(
F);
2719 for (
const GlobalIFunc &GI :
M.ifuncs())
2720 if (GI.hasMetadata())
2721 AddDeclAttachedMetadata(GI);
2724 for (
const GlobalVariable &GV :
M.globals())
2725 if (GV.hasMetadata())
2726 AddDeclAttachedMetadata(GV);
2731void ModuleBitcodeWriter::writeFunctionMetadata(
const Function &
F) {
2736 SmallVector<uint64_t, 64>
Record;
2742void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2743 SmallVectorImpl<uint64_t> &Record,
const GlobalObject &GO) {
2747 for (
const auto &
I : MDs) {
2753void ModuleBitcodeWriter::writeFunctionMetadataAttachment(
const Function &
F) {
2756 SmallVector<uint64_t, 64>
Record;
2758 if (
F.hasMetadata()) {
2759 pushGlobalMetadataAttachment(Record,
F);
2767 for (
const BasicBlock &BB :
F)
2768 for (
const Instruction &
I : BB) {
2770 I.getAllMetadataOtherThanDebugLoc(MDs);
2773 if (MDs.
empty())
continue;
2777 for (
const auto &[
ID, MD] : MDs) {
2788void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2789 SmallVector<uint64_t, 64>
Record;
2794 M.getMDKindNames(Names);
2796 if (Names.
empty())
return;
2800 for (
unsigned MDKindID = 0, e = Names.
size(); MDKindID != e; ++MDKindID) {
2801 Record.push_back(MDKindID);
2802 StringRef KName = Names[MDKindID];
2812void ModuleBitcodeWriter::writeOperandBundleTags() {
2820 M.getOperandBundleTags(Tags);
2827 SmallVector<uint64_t, 64>
Record;
2829 for (
auto Tag : Tags) {
2839void ModuleBitcodeWriter::writeSyncScopeNames() {
2841 M.getContext().getSyncScopeNames(SSNs);
2847 SmallVector<uint64_t, 64>
Record;
2848 for (
auto SSN : SSNs) {
2849 Record.append(SSN.begin(), SSN.end());
2857void ModuleBitcodeWriter::writeConstants(
unsigned FirstVal,
unsigned LastVal,
2859 if (FirstVal == LastVal)
return;
2863 unsigned AggregateAbbrev = 0;
2864 unsigned String8Abbrev = 0;
2865 unsigned CString7Abbrev = 0;
2866 unsigned CString6Abbrev = 0;
2870 auto Abbv = std::make_shared<BitCodeAbbrev>();
2874 AggregateAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
2877 Abbv = std::make_shared<BitCodeAbbrev>();
2881 String8Abbrev = Stream.
EmitAbbrev(std::move(Abbv));
2883 Abbv = std::make_shared<BitCodeAbbrev>();
2887 CString7Abbrev = Stream.
EmitAbbrev(std::move(Abbv));
2889 Abbv = std::make_shared<BitCodeAbbrev>();
2893 CString6Abbrev = Stream.
EmitAbbrev(std::move(Abbv));
2896 SmallVector<uint64_t, 64>
Record;
2899 Type *LastTy =
nullptr;
2900 for (
unsigned i = FirstVal; i != LastVal; ++i) {
2901 const Value *
V = Vals[i].first;
2903 if (
V->getType() != LastTy) {
2904 LastTy =
V->getType();
2907 CONSTANTS_SETTYPE_ABBREV);
2914 unsigned(
IA->hasSideEffects()) |
unsigned(
IA->isAlignStack()) << 1 |
2915 unsigned(
IA->getDialect() & 1) << 2 |
unsigned(
IA->canThrow()) << 3);
2918 StringRef AsmStr =
IA->getAsmString();
2923 StringRef ConstraintStr =
IA->getConstraintString();
2931 unsigned Code = -1U;
2932 unsigned AbbrevToUse = 0;
2933 if (
C->isNullValue()) {
2940 if (
IV->getBitWidth() <= 64) {
2941 uint64_t
V =
IV->getSExtValue();
2944 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2950 if (BV->getBitWidth() <= 64) {
2951 uint64_t
V = BV->getSExtValue();
2954 AbbrevToUse = CONSTANTS_BYTE_ABBREV;
2964 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
2968 APInt api = CFP->getValueAPF().bitcastToAPInt();
2970 Record.push_back((p[1] << 48) | (p[0] >> 16));
2971 Record.push_back(p[0] & 0xffffLL);
2973 APInt api = CFP->getValueAPF().bitcastToAPInt();
2978 assert(0 &&
"Unknown FP type!");
2984 uint64_t NumElts = Str->getNumElements();
2986 if (Str->isCString()) {
2991 AbbrevToUse = String8Abbrev;
2995 for (uint64_t i = 0; i != NumElts; ++i) {
2996 unsigned char V = Str->getElementAsInteger(i);
2998 isCStr7 &= (
V & 128) == 0;
3004 AbbrevToUse = CString6Abbrev;
3006 AbbrevToUse = CString7Abbrev;
3007 }
else if (
const ConstantDataSequential *CDS =
3010 Type *EltTy = CDS->getElementType();
3012 for (uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i)
3013 Record.push_back(CDS->getElementAsInteger(i));
3015 for (uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i)
3017 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
3021 for (
const Value *
Op :
C->operands())
3023 AbbrevToUse = AggregateAbbrev;
3025 switch (
CE->getOpcode()) {
3032 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
3034 assert(
CE->getNumOperands() == 2 &&
"Unknown constant expr!");
3044 case Instruction::FNeg: {
3045 assert(
CE->getNumOperands() == 1 &&
"Unknown constant expr!");
3054 case Instruction::GetElementPtr: {
3059 if (std::optional<ConstantRange>
Range = GO->getInRange()) {
3063 for (
const Value *
Op :
CE->operands()) {
3069 case Instruction::ExtractElement:
3076 case Instruction::InsertElement:
3083 case Instruction::ShuffleVector:
3088 if (
C->getType() ==
C->getOperand(0)->getType()) {
3125 Stream.
EmitRecord(Code, Record, AbbrevToUse);
3132void ModuleBitcodeWriter::writeModuleConstants() {
3137 for (
unsigned i = 0, e = Vals.size(); i != e; ++i) {
3139 writeConstants(i, Vals.size(),
true);
3153bool ModuleBitcodeWriter::pushValueAndType(
const Value *V,
unsigned InstID,
3154 SmallVectorImpl<unsigned> &Vals) {
3158 if (ValID >= InstID) {
3165bool ModuleBitcodeWriter::pushValueOrMetadata(
const Value *V,
unsigned InstID,
3166 SmallVectorImpl<unsigned> &Vals) {
3167 bool IsMetadata =
V->getType()->isMetadataTy();
3175 return pushValueAndType(V, InstID, Vals);
3178void ModuleBitcodeWriter::writeOperandBundles(
const CallBase &CS,
3185 Record.push_back(
C.getOperandBundleTagID(Bundle.getTagName()));
3187 for (
auto &Input : Bundle.Inputs)
3188 pushValueOrMetadata(Input, InstID, Record);
3197void ModuleBitcodeWriter::pushValue(
const Value *V,
unsigned InstID,
3198 SmallVectorImpl<unsigned> &Vals) {
3203void ModuleBitcodeWriter::pushValueSigned(
const Value *V,
unsigned InstID,
3204 SmallVectorImpl<uint64_t> &Vals) {
3206 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
3211void ModuleBitcodeWriter::writeInstruction(
const Instruction &
I,
3213 SmallVectorImpl<unsigned> &Vals) {
3215 unsigned AbbrevToUse = 0;
3217 switch (
I.getOpcode()) {
3221 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3222 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
3227 if (AbbrevToUse == FUNCTION_INST_CAST_ABBREV)
3228 AbbrevToUse = FUNCTION_INST_CAST_FLAGS_ABBREV;
3234 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3235 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
3236 pushValue(
I.getOperand(1), InstID, Vals);
3240 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
3241 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
3246 case Instruction::FNeg: {
3248 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3249 AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
3253 if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
3254 AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
3259 case Instruction::GetElementPtr: {
3261 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
3265 for (
const Value *
Op :
I.operands())
3266 pushValueAndType(
Op, InstID, Vals);
3269 case Instruction::ExtractValue: {
3271 pushValueAndType(
I.getOperand(0), InstID, Vals);
3276 case Instruction::InsertValue: {
3278 pushValueAndType(
I.getOperand(0), InstID, Vals);
3279 pushValueAndType(
I.getOperand(1), InstID, Vals);
3284 case Instruction::Select: {
3286 pushValueAndType(
I.getOperand(1), InstID, Vals);
3287 pushValue(
I.getOperand(2), InstID, Vals);
3288 pushValueAndType(
I.getOperand(0), InstID, Vals);
3294 case Instruction::ExtractElement:
3296 pushValueAndType(
I.getOperand(0), InstID, Vals);
3297 pushValueAndType(
I.getOperand(1), InstID, Vals);
3299 case Instruction::InsertElement:
3301 pushValueAndType(
I.getOperand(0), InstID, Vals);
3302 pushValue(
I.getOperand(1), InstID, Vals);
3303 pushValueAndType(
I.getOperand(2), InstID, Vals);
3305 case Instruction::ShuffleVector:
3307 pushValueAndType(
I.getOperand(0), InstID, Vals);
3308 pushValue(
I.getOperand(1), InstID, Vals);
3312 case Instruction::ICmp:
3313 case Instruction::FCmp: {
3316 AbbrevToUse = FUNCTION_INST_CMP_ABBREV;
3317 if (pushValueAndType(
I.getOperand(0), InstID, Vals))
3319 pushValue(
I.getOperand(1), InstID, Vals);
3325 AbbrevToUse = FUNCTION_INST_CMP_FLAGS_ABBREV;
3330 case Instruction::Ret:
3333 unsigned NumOperands =
I.getNumOperands();
3334 if (NumOperands == 0)
3335 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
3336 else if (NumOperands == 1) {
3337 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3338 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
3340 for (
const Value *
Op :
I.operands())
3341 pushValueAndType(
Op, InstID, Vals);
3345 case Instruction::UncondBr: {
3347 AbbrevToUse = FUNCTION_INST_BR_UNCOND_ABBREV;
3351 case Instruction::CondBr: {
3353 AbbrevToUse = FUNCTION_INST_BR_COND_ABBREV;
3357 pushValue(
II.getCondition(), InstID, Vals);
3359 case Instruction::Switch:
3364 pushValue(
SI.getCondition(), InstID, Vals);
3366 for (
auto Case :
SI.cases()) {
3372 case Instruction::IndirectBr:
3376 pushValue(
I.getOperand(0), InstID, Vals);
3381 case Instruction::Invoke: {
3384 FunctionType *FTy =
II->getFunctionType();
3386 if (
II->hasOperandBundles())
3387 writeOperandBundles(*
II, InstID);
3396 pushValueAndType(Callee, InstID, Vals);
3399 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3400 pushValue(
I.getOperand(i), InstID, Vals);
3403 if (FTy->isVarArg()) {
3404 for (
unsigned i = FTy->getNumParams(), e =
II->arg_size(); i != e; ++i)
3405 pushValueAndType(
I.getOperand(i), InstID, Vals);
3409 case Instruction::Resume:
3411 pushValueAndType(
I.getOperand(0), InstID, Vals);
3413 case Instruction::CleanupRet: {
3416 pushValue(CRI.getCleanupPad(), InstID, Vals);
3417 if (CRI.hasUnwindDest())
3421 case Instruction::CatchRet: {
3424 pushValue(CRI.getCatchPad(), InstID, Vals);
3428 case Instruction::CleanupPad:
3429 case Instruction::CatchPad: {
3433 pushValue(FuncletPad.getParentPad(), InstID, Vals);
3435 unsigned NumArgOperands = FuncletPad.arg_size();
3437 for (
unsigned Op = 0;
Op != NumArgOperands; ++
Op)
3438 pushValueAndType(FuncletPad.getArgOperand(
Op), InstID, Vals);
3441 case Instruction::CatchSwitch: {
3445 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
3447 unsigned NumHandlers = CatchSwitch.getNumHandlers();
3449 for (
const BasicBlock *CatchPadBB : CatchSwitch.handlers())
3452 if (CatchSwitch.hasUnwindDest())
3456 case Instruction::CallBr: {
3462 writeOperandBundles(*CBI, InstID);
3477 pushValueAndType(Callee, InstID, Vals);
3480 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3481 pushValue(
I.getOperand(i), InstID, Vals);
3484 if (FTy->isVarArg()) {
3485 for (
unsigned i = FTy->getNumParams(), e = CBI->
arg_size(); i != e; ++i)
3486 pushValueAndType(
I.getOperand(i), InstID, Vals);
3490 case Instruction::Unreachable:
3492 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
3495 case Instruction::PHI: {
3513 Stream.
EmitRecord(Code, Vals64, AbbrevToUse);
3518 case Instruction::LandingPad: {
3529 pushValueAndType(LP.
getClause(
I), InstID, Vals);
3534 case Instruction::Alloca: {
3540 using APV = AllocaPackedValues;
3542 unsigned EncodedAlign = getEncodedAlign(AI.
getAlign());
3544 Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1));
3546 EncodedAlign >> APV::AlignLower::Bits);
3553 if (AS !=
M.getDataLayout().getAllocaAddrSpace())
3558 case Instruction::Load:
3561 pushValueAndType(
I.getOperand(0), InstID, Vals);
3564 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3565 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
3575 case Instruction::Store:
3580 AbbrevToUse = FUNCTION_INST_STORE_ABBREV;
3582 if (pushValueAndType(
I.getOperand(1), InstID, Vals))
3584 if (pushValueAndType(
I.getOperand(0), InstID, Vals))
3594 case Instruction::AtomicCmpXchg:
3596 pushValueAndType(
I.getOperand(0), InstID, Vals);
3597 pushValueAndType(
I.getOperand(1), InstID, Vals);
3598 pushValue(
I.getOperand(2), InstID, Vals);
3609 case Instruction::AtomicRMW:
3611 pushValueAndType(
I.getOperand(0), InstID, Vals);
3612 pushValueAndType(
I.getOperand(1), InstID, Vals);
3620 case Instruction::Fence:
3625 case Instruction::Call: {
3630 writeOperandBundles(CI, InstID);
3650 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3654 if (FTy->isVarArg()) {
3655 for (
unsigned i = FTy->getNumParams(), e = CI.
arg_size(); i != e; ++i)
3660 case Instruction::VAArg:
3663 pushValue(
I.getOperand(0), InstID, Vals);
3666 case Instruction::Freeze:
3668 pushValueAndType(
I.getOperand(0), InstID, Vals);
3678void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3679 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3684 VSTOffset -= bitcodeStartBit();
3685 assert((VSTOffset & 31) == 0 &&
"VST block not 32-bit aligned");
3689 Stream.
BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
3693 auto Abbv = std::make_shared<BitCodeAbbrev>();
3697 unsigned FnEntryAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
3699 for (
const Function &
F : M) {
3702 if (
F.isDeclaration())
3709 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&
F] - bitcodeStartBit();
3710 assert((BitcodeIndex & 31) == 0 &&
"function block not 32-bit aligned");
3714 Record[1] = BitcodeIndex / 32 + 1;
3723void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3724 const ValueSymbolTable &VST) {
3732 SmallVector<uint64_t, 64> NameVals;
3738 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3747 AbbrevToUse = VST_BBENTRY_6_ABBREV;
3751 AbbrevToUse = VST_ENTRY_6_ABBREV;
3753 AbbrevToUse = VST_ENTRY_7_ABBREV;
3756 for (
const auto P :
Name.getKey())
3760 Stream.
EmitRecord(Code, NameVals, AbbrevToUse);
3767void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3768 assert(Order.Shuffle.size() >= 2 &&
"Shuffle too small");
3775 SmallVector<uint64_t, 64>
Record(Order.Shuffle.begin(), Order.Shuffle.end());
3780void ModuleBitcodeWriter::writeUseListBlock(
const Function *
F) {
3782 "Expected to be preserving use-list order");
3784 auto hasMore = [&]() {
3800void ModuleBitcodeWriter::writeFunction(
3802 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3819 unsigned CstStart, CstEnd;
3821 writeConstants(CstStart, CstEnd,
false);
3824 writeFunctionMetadata(
F);
3827 unsigned InstID = CstEnd;
3829 bool NeedsMetadataAttachment =
F.hasMetadata();
3831 DILocation *LastDL =
nullptr;
3832 SmallSetVector<Function *, 4> BlockAddressUsers;
3835 for (
const BasicBlock &BB :
F) {
3836 for (
const Instruction &
I : BB) {
3837 writeInstruction(
I, InstID, Vals);
3839 if (!
I.getType()->isVoidTy())
3843 NeedsMetadataAttachment |=
I.hasMetadataOtherThanDebugLoc();
3846 if (DILocation *
DL =
I.getDebugLoc()) {
3859 FUNCTION_DEBUG_LOC_ABBREV);
3869 if (
I.hasDbgRecords()) {
3873 auto PushValueOrMetadata = [&Vals, InstID,
3876 "RawLocation unexpectedly null in DbgVariableRecord");
3878 SmallVector<unsigned, 2> ValAndType;
3882 if (!pushValueAndType(VAM->getValue(), InstID, ValAndType)) {
3896 for (DbgRecord &DR :
I.DebugMarker->getDbgRecordRange()) {
3922 FUNCTION_DEBUG_RECORD_VALUE_ABBREV);
3946 SmallPtrSet<Value *, 8> Visited{BA};
3947 while (!Worklist.
empty()) {
3949 for (User *U :
V->users()) {
3955 Visited.
insert(U).second)
3962 if (!BlockAddressUsers.
empty()) {
3971 if (
auto *Symtab =
F.getValueSymbolTable())
3972 writeFunctionLevelValueSymbolTable(*Symtab);
3974 if (NeedsMetadataAttachment)
3975 writeFunctionMetadataAttachment(
F);
3977 writeUseListBlock(&
F);
3983void ModuleBitcodeWriter::writeBlockInfo() {
3996 auto Abbv = std::make_shared<BitCodeAbbrev>();
4007 auto Abbv = std::make_shared<BitCodeAbbrev>();
4017 auto Abbv = std::make_shared<BitCodeAbbrev>();
4027 auto Abbv = std::make_shared<BitCodeAbbrev>();
4033 VST_BBENTRY_6_ABBREV)
4038 auto Abbv = std::make_shared<BitCodeAbbrev>();
4040 Abbv->Add(TypeAbbrevOp);
4042 CONSTANTS_SETTYPE_ABBREV)
4047 auto Abbv = std::make_shared<BitCodeAbbrev>();
4051 CONSTANTS_INTEGER_ABBREV)
4056 auto Abbv = std::make_shared<BitCodeAbbrev>();
4060 CONSTANTS_BYTE_ABBREV)
4065 auto Abbv = std::make_shared<BitCodeAbbrev>();
4073 CONSTANTS_CE_CAST_Abbrev)
4077 auto Abbv = std::make_shared<BitCodeAbbrev>();
4080 CONSTANTS_NULL_Abbrev)
4087 auto Abbv = std::make_shared<BitCodeAbbrev>();
4089 Abbv->Add(ValAbbrevOp);
4090 Abbv->Add(TypeAbbrevOp);
4094 FUNCTION_INST_LOAD_ABBREV)
4098 auto Abbv = std::make_shared<BitCodeAbbrev>();
4100 Abbv->Add(ValAbbrevOp);
4101 Abbv->Add(ValAbbrevOp);
4105 FUNCTION_INST_STORE_ABBREV)
4109 auto Abbv = std::make_shared<BitCodeAbbrev>();
4111 Abbv->Add(ValAbbrevOp);
4114 FUNCTION_INST_UNOP_ABBREV)
4118 auto Abbv = std::make_shared<BitCodeAbbrev>();
4120 Abbv->Add(ValAbbrevOp);
4124 FUNCTION_INST_UNOP_FLAGS_ABBREV)
4128 auto Abbv = std::make_shared<BitCodeAbbrev>();
4130 Abbv->Add(ValAbbrevOp);
4131 Abbv->Add(ValAbbrevOp);
4134 FUNCTION_INST_BINOP_ABBREV)
4138 auto Abbv = std::make_shared<BitCodeAbbrev>();
4140 Abbv->Add(ValAbbrevOp);
4141 Abbv->Add(ValAbbrevOp);
4145 FUNCTION_INST_BINOP_FLAGS_ABBREV)
4149 auto Abbv = std::make_shared<BitCodeAbbrev>();
4151 Abbv->Add(ValAbbrevOp);
4152 Abbv->Add(TypeAbbrevOp);
4155 FUNCTION_INST_CAST_ABBREV)
4159 auto Abbv = std::make_shared<BitCodeAbbrev>();
4161 Abbv->Add(ValAbbrevOp);
4162 Abbv->Add(TypeAbbrevOp);
4166 FUNCTION_INST_CAST_FLAGS_ABBREV)
4171 auto Abbv = std::make_shared<BitCodeAbbrev>();
4174 FUNCTION_INST_RET_VOID_ABBREV)
4178 auto Abbv = std::make_shared<BitCodeAbbrev>();
4180 Abbv->Add(ValAbbrevOp);
4182 FUNCTION_INST_RET_VAL_ABBREV)
4186 auto Abbv = std::make_shared<BitCodeAbbrev>();
4189 Abbv->Add(ValAbbrevOp);
4191 FUNCTION_INST_BR_UNCOND_ABBREV)
4195 auto Abbv = std::make_shared<BitCodeAbbrev>();
4198 Abbv->Add(ValAbbrevOp);
4199 Abbv->Add(ValAbbrevOp);
4200 Abbv->Add(ValAbbrevOp);
4202 FUNCTION_INST_BR_COND_ABBREV)
4206 auto Abbv = std::make_shared<BitCodeAbbrev>();
4209 FUNCTION_INST_UNREACHABLE_ABBREV)
4213 auto Abbv = std::make_shared<BitCodeAbbrev>();
4216 Abbv->Add(TypeAbbrevOp);
4218 Abbv->Add(ValAbbrevOp);
4220 FUNCTION_INST_GEP_ABBREV)
4224 auto Abbv = std::make_shared<BitCodeAbbrev>();
4226 Abbv->Add(ValAbbrevOp);
4227 Abbv->Add(ValAbbrevOp);
4230 FUNCTION_INST_CMP_ABBREV)
4234 auto Abbv = std::make_shared<BitCodeAbbrev>();
4236 Abbv->Add(ValAbbrevOp);
4237 Abbv->Add(ValAbbrevOp);
4241 FUNCTION_INST_CMP_FLAGS_ABBREV)
4245 auto Abbv = std::make_shared<BitCodeAbbrev>();
4250 Abbv->Add(ValAbbrevOp);
4252 FUNCTION_DEBUG_RECORD_VALUE_ABBREV)
4256 auto Abbv = std::make_shared<BitCodeAbbrev>();
4267 FUNCTION_DEBUG_LOC_ABBREV)
4275void IndexBitcodeWriter::writeModStrings() {
4281 auto Abbv = std::make_shared<BitCodeAbbrev>();
4286 unsigned Abbrev8Bit = Stream.
EmitAbbrev(std::move(Abbv));
4289 Abbv = std::make_shared<BitCodeAbbrev>();
4294 unsigned Abbrev7Bit = Stream.
EmitAbbrev(std::move(Abbv));
4297 Abbv = std::make_shared<BitCodeAbbrev>();
4302 unsigned Abbrev6Bit = Stream.
EmitAbbrev(std::move(Abbv));
4305 Abbv = std::make_shared<BitCodeAbbrev>();
4312 unsigned AbbrevHash = Stream.
EmitAbbrev(std::move(Abbv));
4315 forEachModule([&](
const StringMapEntry<ModuleHash> &MPSE) {
4317 const auto &Hash = MPSE.
getValue();
4319 unsigned AbbrevToUse = Abbrev8Bit;
4321 AbbrevToUse = Abbrev6Bit;
4323 AbbrevToUse = Abbrev7Bit;
4325 auto ModuleId = ModuleIdMap.
size();
4326 ModuleIdMap[
Key] = ModuleId;
4336 Vals.
assign(Hash.begin(), Hash.end());
4348template <
typename Fn>
4352 if (!FS->type_tests().empty())
4357 auto WriteVFuncIdVec = [&](
uint64_t Ty,
4362 for (
auto &VF : VFs) {
4363 Record.push_back(VF.GUID);
4364 Record.push_back(VF.Offset);
4370 FS->type_test_assume_vcalls());
4372 FS->type_checked_load_vcalls());
4374 auto WriteConstVCallVec = [&](
uint64_t Ty,
4376 for (
auto &VC : VCs) {
4378 Record.push_back(VC.VFunc.GUID);
4379 Record.push_back(VC.VFunc.Offset);
4386 FS->type_test_assume_const_vcalls());
4388 FS->type_checked_load_const_vcalls());
4398 if (!FS->paramAccesses().empty()) {
4400 for (
auto &Arg : FS->paramAccesses()) {
4401 size_t UndoSize =
Record.size();
4402 Record.push_back(Arg.ParamNo);
4403 WriteRange(Arg.Use);
4404 Record.push_back(Arg.Calls.size());
4405 for (
auto &
Call : Arg.Calls) {
4407 std::optional<unsigned> ValueID = GetValueID(
Call.Callee);
4414 Record.push_back(*ValueID);
4415 WriteRange(
Call.Offsets);
4426 std::set<GlobalValue::GUID> &ReferencedTypeIds) {
4427 if (!FS->type_tests().empty())
4428 for (
auto &TT : FS->type_tests())
4429 ReferencedTypeIds.insert(TT);
4431 auto GetReferencedTypesFromVFuncIdVec =
4433 for (
auto &VF : VFs)
4434 ReferencedTypeIds.insert(VF.GUID);
4437 GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
4438 GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
4440 auto GetReferencedTypesFromConstVCallVec =
4442 for (
auto &VC : VCs)
4443 ReferencedTypeIds.insert(VC.VFunc.GUID);
4446 GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
4447 GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
4483 NameVals.
push_back(Summary.TTRes.TheKind);
4484 NameVals.
push_back(Summary.TTRes.SizeM1BitWidth);
4485 NameVals.
push_back(Summary.TTRes.AlignLog2);
4486 NameVals.
push_back(Summary.TTRes.SizeM1);
4487 NameVals.
push_back(Summary.TTRes.BitMask);
4488 NameVals.
push_back(Summary.TTRes.InlineBits);
4490 for (
auto &W : Summary.WPDRes)
4502 for (
auto &
P : Summary) {
4504 NameVals.
push_back(
VE.getValueID(
P.VTableVI.getValue()));
4518 static_assert(std::is_same_v<LinearFrameId, unsigned>);
4519 for (
auto &AI : FS->allocs()) {
4520 for (
auto &MIB : AI.MIBs) {
4522 StackIdIndices.
reserve(MIB.StackIdIndices.size());
4523 for (
auto Id : MIB.StackIdIndices)
4524 StackIdIndices.
push_back(GetStackIndex(Id));
4526 CallStacks.insert({CallStacks.size(), StackIdIndices});
4539 assert(!CallStacks.empty());
4545 Builder.
build(std::move(CallStacks),
nullptr,
4549 return Builder.takeCallStackPos();
4554 unsigned AllocAbbrev,
unsigned ContextIdAbbvId,
bool PerModule,
4555 std::function<
unsigned(
const ValueInfo &VI)> GetValueID,
4556 std::function<
unsigned(
unsigned)> GetStackIndex,
4557 bool WriteContextSizeInfoIndex,
4562 for (
auto &CI : FS->callsites()) {
4566 assert(!PerModule || (CI.Clones.size() == 1 && CI.Clones[0] == 0));
4567 Record.push_back(GetValueID(CI.Callee));
4569 Record.push_back(CI.StackIdIndices.size());
4570 Record.push_back(CI.Clones.size());
4572 for (
auto Id : CI.StackIdIndices)
4573 Record.push_back(GetStackIndex(Id));
4581 for (
auto &AI : FS->allocs()) {
4585 assert(!PerModule || (AI.Versions.size() == 1 && AI.Versions[0] == 0));
4586 Record.push_back(AI.MIBs.size());
4588 Record.push_back(AI.Versions.size());
4589 for (
auto &MIB : AI.MIBs) {
4596 assert(CallStackCount <= CallStackPos.
size());
4597 Record.push_back(CallStackPos[CallStackCount++]);
4602 assert(AI.ContextSizeInfos.empty() ||
4603 AI.ContextSizeInfos.size() == AI.MIBs.size());
4605 if (WriteContextSizeInfoIndex && !AI.ContextSizeInfos.empty()) {
4613 ContextIds.
reserve(AI.ContextSizeInfos.size() * 2);
4614 for (
auto &Infos : AI.ContextSizeInfos) {
4615 Record.push_back(Infos.size());
4616 for (
auto [FullStackId, TotalSize] : Infos) {
4623 Record.push_back(TotalSize);
4641void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
4642 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
4643 unsigned ValueID,
unsigned FSCallsProfileAbbrev,
unsigned CallsiteAbbrev,
4644 unsigned AllocAbbrev,
unsigned ContextIdAbbvId,
const Function &
F,
4645 DenseMap<CallStackId, LinearCallStackId> &CallStackPos,
4652 Stream, FS, [&](
const ValueInfo &VI) -> std::optional<unsigned> {
4656 auto SpecialRefCnts =
FS->specialRefCounts();
4661 NameVals.
push_back(SpecialRefCnts.first);
4662 NameVals.
push_back(SpecialRefCnts.second);
4664 for (
auto &RI :
FS->refs())
4667 for (
auto &ECI :
FS->calls()) {
4668 NameVals.
push_back(getValueId(ECI.first));
4677 Stream, FS, CallsiteAbbrev, AllocAbbrev, ContextIdAbbvId,
4679 [&](
const ValueInfo &VI) {
return getValueId(VI); },
4680 [&](
unsigned I) {
return I; },
4681 true, CallStackPos, CallStackCount);
4686void ModuleBitcodeWriterBase::writeModuleLevelReferences(
4687 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
4688 unsigned FSModRefsAbbrev,
unsigned FSModVTableRefsAbbrev) {
4689 auto VI =
Index->getValueInfo(
V.getGUID());
4690 if (!VI ||
VI.getSummaryList().empty()) {
4696 auto *
Summary =
VI.getSummaryList()[0].get();
4702 auto VTableFuncs =
VS->vTableFuncs();
4703 if (!VTableFuncs.empty())
4706 unsigned SizeBeforeRefs = NameVals.
size();
4707 for (
auto &RI :
VS->refs())
4713 if (VTableFuncs.empty())
4718 for (
auto &
P : VTableFuncs) {
4724 FSModVTableRefsAbbrev);
4731void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
4734 bool IsThinLTO =
true;
4737 IsThinLTO = MD->getZExtValue();
4749 if (
Index->enableSplitLTOUnit())
4751 if (
Index->hasUnifiedLTO())
4761 auto Abbv = std::make_shared<BitCodeAbbrev>();
4767 unsigned ValueGuidAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4769 for (
const auto &GVI : valueIds()) {
4771 ArrayRef<uint32_t>{GVI.second,
4772 static_cast<uint32_t
>(GVI.first >> 32),
4773 static_cast<uint32_t
>(GVI.first)},
4777 if (!
Index->stackIds().empty()) {
4778 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4785 unsigned StackIdAbbvId = Stream.
EmitAbbrev(std::move(StackIdAbbv));
4786 SmallVector<uint32_t> Vals;
4788 for (
auto Id :
Index->stackIds()) {
4789 Vals.
push_back(
static_cast<uint32_t
>(Id >> 32));
4790 Vals.
push_back(
static_cast<uint32_t
>(Id));
4795 unsigned ContextIdAbbvId = 0;
4798 auto ContextIdAbbv = std::make_shared<BitCodeAbbrev>();
4810 ContextIdAbbvId = Stream.
EmitAbbrev(std::move(ContextIdAbbv));
4814 Abbv = std::make_shared<BitCodeAbbrev>();
4826 unsigned FSCallsProfileAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4829 Abbv = std::make_shared<BitCodeAbbrev>();
4835 unsigned FSModRefsAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4838 Abbv = std::make_shared<BitCodeAbbrev>();
4846 unsigned FSModVTableRefsAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4849 Abbv = std::make_shared<BitCodeAbbrev>();
4854 unsigned FSAliasAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4857 Abbv = std::make_shared<BitCodeAbbrev>();
4864 unsigned TypeIdCompatibleVtableAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4866 Abbv = std::make_shared<BitCodeAbbrev>();
4872 unsigned CallsiteAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4874 Abbv = std::make_shared<BitCodeAbbrev>();
4881 unsigned AllocAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4883 Abbv = std::make_shared<BitCodeAbbrev>();
4888 unsigned RadixAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4895 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks;
4896 for (
const Function &
F : M) {
4902 ValueInfo
VI =
Index->getValueInfo(
F.getGUID());
4903 if (!VI ||
VI.getSummaryList().empty()) {
4909 auto *
Summary =
VI.getSummaryList()[0].get();
4912 FS, [](
unsigned I) {
return I; }, CallStacks);
4916 DenseMap<CallStackId, LinearCallStackId> CallStackPos;
4917 if (!CallStacks.
empty()) {
4925 SmallVector<uint64_t, 64> NameVals;
4928 for (
const Function &
F : M) {
4934 ValueInfo
VI =
Index->getValueInfo(
F.getGUID());
4935 if (!VI ||
VI.getSummaryList().empty()) {
4941 auto *
Summary =
VI.getSummaryList()[0].get();
4942 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.
getValueID(&
F),
4943 FSCallsProfileAbbrev, CallsiteAbbrev,
4944 AllocAbbrev, ContextIdAbbvId,
F,
4945 CallStackPos, CallStackCount);
4950 for (
const GlobalVariable &
G :
M.globals())
4951 writeModuleLevelReferences(
G, NameVals, FSModRefsAbbrev,
4952 FSModVTableRefsAbbrev);
4954 for (
const GlobalAlias &
A :
M.aliases()) {
4955 auto *Aliasee =
A.getAliaseeObject();
4971 for (
auto &S :
Index->typeIdCompatibleVtableMap()) {
4975 TypeIdCompatibleVtableAbbrev);
4979 if (
Index->getBlockCount())
4981 ArrayRef<uint64_t>{
Index->getBlockCount()});
4987void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
4996 auto Abbv = std::make_shared<BitCodeAbbrev>();
5002 unsigned ValueGuidAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5004 for (
const auto &GVI : valueIds()) {
5006 ArrayRef<uint32_t>{GVI.second,
5007 static_cast<uint32_t
>(GVI.first >> 32),
5008 static_cast<uint32_t
>(GVI.first)},
5014 if (!StackIds.empty()) {
5015 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
5022 unsigned StackIdAbbvId = Stream.
EmitAbbrev(std::move(StackIdAbbv));
5023 SmallVector<uint32_t> Vals;
5024 Vals.
reserve(StackIds.size() * 2);
5025 for (
auto Id : StackIds) {
5026 Vals.
push_back(
static_cast<uint32_t
>(Id >> 32));
5027 Vals.
push_back(
static_cast<uint32_t
>(Id));
5033 Abbv = std::make_shared<BitCodeAbbrev>();
5047 unsigned FSCallsProfileAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5050 Abbv = std::make_shared<BitCodeAbbrev>();
5057 unsigned FSModRefsAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5060 Abbv = std::make_shared<BitCodeAbbrev>();
5066 unsigned FSAliasAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5068 Abbv = std::make_shared<BitCodeAbbrev>();
5076 unsigned CallsiteAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5078 Abbv = std::make_shared<BitCodeAbbrev>();
5089 unsigned AllocAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5091 auto shouldImportValueAsDecl = [&](GlobalValueSummary *GVS) ->
bool {
5092 if (DecSummaries ==
nullptr)
5094 return DecSummaries->
count(GVS);
5102 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
5104 SmallVector<uint64_t, 64> NameVals;
5108 std::set<GlobalValue::GUID> ReferencedTypeIds;
5112 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
5122 NameVals.
push_back(S.getOriginalName());
5127 DenseMap<CallStackId, LinearCallStackId> CallStackPos;
5129 Abbv = std::make_shared<BitCodeAbbrev>();
5134 unsigned RadixAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5141 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks;
5142 forEachSummary([&](GVInfo
I,
bool IsAliasee) {
5148 GlobalValueSummary *S =
I.second;
5161 return StackIdIndicesToIndex[
I];
5167 if (!CallStacks.
empty()) {
5177 DenseSet<GlobalValue::GUID> DefOrUseGUIDs;
5178 forEachSummary([&](GVInfo
I,
bool IsAliasee) {
5179 GlobalValueSummary *S =
I.second;
5181 DefOrUseGUIDs.
insert(
I.first);
5182 for (
const ValueInfo &VI : S->
refs())
5183 DefOrUseGUIDs.
insert(
VI.getGUID());
5185 auto ValueId = getValueId(
I.first);
5187 SummaryToValueIdMap[S] = *ValueId;
5205 NameVals.
push_back(ModuleIdMap[
VS->modulePath()]);
5209 for (
auto &RI :
VS->refs()) {
5210 auto RefValueId = getValueId(RI.getGUID());
5220 MaybeEmitOriginalName(*S);
5224 auto GetValueId = [&](
const ValueInfo &
VI) -> std::optional<unsigned> {
5226 return std::nullopt;
5227 return getValueId(
VI.getGUID());
5236 NameVals.
push_back(ModuleIdMap[
FS->modulePath()]);
5249 unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;
5250 for (
auto &RI :
FS->refs()) {
5251 auto RefValueId = getValueId(RI.getGUID());
5255 if (RI.isReadOnly())
5257 else if (RI.isWriteOnly())
5261 NameVals[6] =
Count;
5262 NameVals[7] = RORefCnt;
5263 NameVals[8] = WORefCnt;
5265 for (
auto &EI :
FS->calls()) {
5268 std::optional<unsigned> CallValueId = GetValueId(EI.first);
5277 FSCallsProfileAbbrev);
5281 Stream, FS, CallsiteAbbrev, AllocAbbrev, 0,
5284 [&](
const ValueInfo &VI) ->
unsigned {
5285 std::optional<unsigned> ValueID = GetValueId(VI);
5300 return StackIdIndicesToIndex[
I];
5302 false, CallStackPos, CallStackCount);
5304 MaybeEmitOriginalName(*S);
5307 for (
auto *AS : Aliases) {
5308 auto AliasValueId = SummaryToValueIdMap[AS];
5317 auto AliaseeValueId =
5324 MaybeEmitOriginalName(*AS);
5332 auto EmitCfiFunctions = [&](
const CfiFunctionIndex &CfiIndex,
5334 if (CfiIndex.
empty())
5338 for (StringRef Name : Names)
5341 if (Functions.
empty())
5344 for (
const auto &Record : Functions) {
5359 for (
auto &
T : ReferencedTypeIds) {
5360 auto TidIter =
Index.typeIds().equal_range(
T);
5361 for (
const auto &[GUID, TypeIdPair] :
make_range(TidIter)) {
5369 if (
Index.getBlockCount())
5371 ArrayRef<uint64_t>{
Index.getBlockCount()});
5382 auto Abbv = std::make_shared<BitCodeAbbrev>();
5386 auto StringAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5388 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
5391 Abbv = std::make_shared<BitCodeAbbrev>();
5394 auto EpochAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5400void ModuleBitcodeWriter::writeModuleHash(StringRef View) {
5405 Hasher.
update(ArrayRef<uint8_t>(
5406 reinterpret_cast<const uint8_t *
>(
View.data()),
View.size()));
5407 std::array<uint8_t, 20> Hash = Hasher.
result();
5408 for (
int Pos = 0; Pos < 20; Pos += 4) {
5421void ModuleBitcodeWriter::write() {
5429 writeModuleVersion();
5438 writeAttributeGroupTable();
5441 writeAttributeTable();
5450 writeModuleConstants();
5453 writeModuleMetadataKinds();
5456 writeModuleMetadata();
5460 writeUseListBlock(
nullptr);
5462 writeOperandBundleTags();
5463 writeSyncScopeNames();
5466 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
5467 for (
const Function &
F : M)
5468 if (!
F.isDeclaration())
5469 writeFunction(
F, FunctionToBitcodeIndex);
5474 writePerModuleGlobalValueSummary();
5476 writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
5504 unsigned CPUType = ~0U;
5511 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
5512 DARWIN_CPU_TYPE_X86 = 7,
5513 DARWIN_CPU_TYPE_ARM = 12,
5514 DARWIN_CPU_TYPE_POWERPC = 18
5519 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
5521 CPUType = DARWIN_CPU_TYPE_X86;
5523 CPUType = DARWIN_CPU_TYPE_POWERPC;
5525 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
5527 CPUType = DARWIN_CPU_TYPE_ARM;
5531 "Expected header size to be reserved");
5536 unsigned Position = 0;
5544 while (Buffer.
size() & 15)
5551 Stream.
Emit((
unsigned)
'B', 8);
5552 Stream.
Emit((
unsigned)
'C', 8);
5553 Stream.
Emit(0x0, 4);
5554 Stream.
Emit(0xC, 4);
5555 Stream.
Emit(0xE, 4);
5556 Stream.
Emit(0xD, 4);
5574 auto Abbv = std::make_shared<BitCodeAbbrev>();
5577 auto AbbrevNo = Stream->
EmitAbbrev(std::move(Abbv));
5585 assert(!WroteStrtab && !WroteSymtab);
5591 if (M->getModuleInlineAsm().empty())
5595 const Triple TT(M->getTargetTriple());
5597 if (!
T || !
T->hasMCAsmParser())
5619 std::vector<char> Strtab;
5620 StrtabBuilder.finalizeInOrder();
5621 Strtab.resize(StrtabBuilder.getSize());
5622 StrtabBuilder.write((
uint8_t *)Strtab.data());
5625 {Strtab.data(), Strtab.size()});
5636 bool ShouldPreserveUseListOrder,
5645 assert(M.isMaterialized());
5646 Mods.push_back(
const_cast<Module *
>(&M));
5648 ModuleBitcodeWriter ModuleWriter(M, StrtabBuilder, *Stream,
5649 ShouldPreserveUseListOrder, Index,
5650 GenerateHash, ModHash);
5651 ModuleWriter.write();
5658 IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index, DecSummaries,
5659 ModuleToSummariesForIndex);
5660 IndexWriter.write();
5665 bool ShouldPreserveUseListOrder,
5669 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
5671 Writer.writeSymtab();
5672 Writer.writeStrtab();
5674 Triple TT(M.getTargetTriple());
5675 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) {
5693void IndexBitcodeWriter::write() {
5696 writeModuleVersion();
5702 writeCombinedGlobalValueSummary();
5719 Writer.
writeIndex(&Index, ModuleToSummariesForIndex, DecSummaries);
5728class ThinLinkBitcodeWriter :
public ModuleBitcodeWriterBase {
5738 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
5740 ModHash(&ModHash) {}
5745 void writeSimplifiedModuleInfo();
5755void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
5767 auto Abbv = std::make_shared<BitCodeAbbrev>();
5770 Abbv->Add(AbbrevOpToUse);
5771 unsigned FilenameAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5773 for (
const auto P :
M.getSourceFileName())
5837void ThinLinkBitcodeWriter::write() {
5840 writeModuleVersion();
5842 writeSimplifiedModuleInfo();
5844 writePerModuleGlobalValueSummary();
5861 assert(M.isMaterialized());
5862 Mods.push_back(
const_cast<Module *
>(&M));
5864 ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
5866 ThinLinkWriter.write();
5887 switch (
T.getObjectFormat()) {
5889 return "__LLVM,__bitcode";
5914 switch (
T.getObjectFormat()) {
5916 return "__LLVM,__cmdline";
5942 const std::vector<uint8_t> &CmdArgs) {
5947 Type *UsedElementType = Used ? Used->getValueType()->getArrayElementType()
5949 for (
auto *GV : UsedGlobals) {
5950 if (GV->getName() !=
"llvm.embedded.module" &&
5951 GV->getName() !=
"llvm.cmdline")
5956 Used->eraseFromParent();
5961 Triple T(M.getTargetTriple());
5990 M.getGlobalVariable(
"llvm.embedded.module",
true)) {
5991 assert(Old->hasZeroLiveUses() &&
5992 "llvm.embedded.module can only be used once in llvm.compiler.used");
5994 Old->eraseFromParent();
5996 GV->
setName(
"llvm.embedded.module");
6014 assert(Old->hasZeroLiveUses() &&
6015 "llvm.cmdline can only be used once in llvm.compiler.used");
6017 Old->eraseFromParent();
6023 if (UsedArray.
empty())
6031 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
@ 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 ...
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