34#include "llvm/Config/llvm-config.h"
119 VST_BBENTRY_6_ABBREV,
123 CONSTANTS_INTEGER_ABBREV,
124 CONSTANTS_BYTE_ABBREV,
125 CONSTANTS_CE_CAST_Abbrev,
126 CONSTANTS_NULL_Abbrev,
130 FUNCTION_INST_STORE_ABBREV,
131 FUNCTION_INST_UNOP_ABBREV,
132 FUNCTION_INST_UNOP_FLAGS_ABBREV,
133 FUNCTION_INST_BINOP_ABBREV,
134 FUNCTION_INST_BINOP_FLAGS_ABBREV,
135 FUNCTION_INST_CAST_ABBREV,
136 FUNCTION_INST_CAST_FLAGS_ABBREV,
137 FUNCTION_INST_RET_VOID_ABBREV,
138 FUNCTION_INST_RET_VAL_ABBREV,
139 FUNCTION_INST_BR_UNCOND_ABBREV,
140 FUNCTION_INST_BR_COND_ABBREV,
141 FUNCTION_INST_UNREACHABLE_ABBREV,
142 FUNCTION_INST_GEP_ABBREV,
143 FUNCTION_INST_CMP_ABBREV,
144 FUNCTION_INST_CMP_FLAGS_ABBREV,
145 FUNCTION_DEBUG_RECORD_VALUE_ABBREV,
146 FUNCTION_DEBUG_LOC_ABBREV,
147 FUNCTION_DEBUG_LOC_LAYERS_ABBREV,
152class BitcodeWriterBase {
155 BitstreamWriter &Stream;
157 StringTableBuilder &StrtabBuilder;
162 BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
163 : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
166 void writeModuleVersion();
169void BitcodeWriterBase::writeModuleVersion() {
176class ModuleBitcodeWriterBase :
public BitcodeWriterBase {
178 const BitWriterOptions &Opts;
187 const ModuleSummaryIndex *Index;
192 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
195 unsigned GlobalValueId;
204 ModuleBitcodeWriterBase(
const Module &M, StringTableBuilder &StrtabBuilder,
205 BitstreamWriter &Stream,
206 bool ShouldPreserveUseListOrder,
207 const ModuleSummaryIndex *Index)
208 : BitcodeWriterBase(Stream, StrtabBuilder),
211 valueOr(Opts.preserve_bc_uselistorder, ShouldPreserveUseListOrder)),
222 for (
const auto &GUIDSummaryLists :
223 Index->sortedGlobalValueSummariesRange())
225 for (
auto &Summary : GUIDSummaryLists.second.getSummaryList())
231 for (auto &CallEdge : FS->calls())
232 if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())
233 assignValueId(CallEdge.first.getGUID());
239 for (auto &RefEdge : FS->refs())
240 if (!RefEdge.haveGVs() || !RefEdge.getValue())
241 assignValueId(RefEdge.getGUID());
246 void writePerModuleGlobalValueSummary();
247 void writeGUIDList();
250 void writePerModuleFunctionSummaryRecord(
251 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
252 unsigned ValueID,
unsigned FSCallsProfileAbbrev,
unsigned CallsiteAbbrev,
253 unsigned AllocAbbrev,
unsigned ContextIdAbbvId,
const Function &
F,
254 DenseMap<CallStackId, LinearCallStackId> &CallStackPos,
256 void writeModuleLevelReferences(
const GlobalVariable &
V,
257 SmallVector<uint64_t, 64> &NameVals,
258 unsigned FSModRefsAbbrev,
259 unsigned FSModVTableRefsAbbrev);
262 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
266 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
269 assert(VMI != GUIDToValueIdMap.end() &&
270 "GUID does not have assigned value Id");
275 unsigned getValueId(ValueInfo VI) {
276 if (!
VI.haveGVs() || !
VI.getValue())
277 return getValueId(
VI.getGUID());
281 std::map<GlobalValue::GUID, unsigned> &valueIds() {
return GUIDToValueIdMap; }
285class ModuleBitcodeWriter :
public ModuleBitcodeWriterBase {
301 unsigned DILocationLayersAbbrev = 0;
306 ModuleBitcodeWriter(
const Module &M, StringTableBuilder &StrtabBuilder,
307 BitstreamWriter &Stream,
bool ShouldPreserveUseListOrder,
308 const ModuleSummaryIndex *Index,
bool GenerateHash,
310 : ModuleBitcodeWriterBase(
M, StrtabBuilder, Stream,
311 ShouldPreserveUseListOrder,
Index),
312 GenerateHash(GenerateHash), ModHash(ModHash),
313 BitcodeStartBit(Stream.GetCurrentBitNo()) {}
319 uint64_t bitcodeStartBit() {
return BitcodeStartBit; }
321 size_t addToStrtab(StringRef Str);
323 void writeAttributeGroupTable();
324 void writeAttributeTable();
325 void writeTypeTable();
327 void writeValueSymbolTableForwardDecl();
328 void writeModuleInfo();
329 void writeValueAsMetadata(
const ValueAsMetadata *MD,
330 SmallVectorImpl<uint64_t> &Record);
331 void writeMDTuple(
const MDTuple *
N, SmallVectorImpl<uint64_t> &Record,
333 unsigned createDILocationAbbrev(
bool WithIRLayers);
334 void writeDILocation(
const DILocation *
N, SmallVectorImpl<uint64_t> &Record,
336 void writeDILayerLoc(
const DILayerLoc *
N, SmallVectorImpl<uint64_t> &Record,
339 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
341 SmallVectorImpl<uint64_t> &Record,
343 unsigned createGenericDINodeAbbrev();
345 SmallVectorImpl<uint64_t> &Record,
unsigned &Abbrev);
346 void writeDISubrange(
const DISubrange *
N, SmallVectorImpl<uint64_t> &Record,
349 SmallVectorImpl<uint64_t> &Record,
352 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
356 SmallVectorImpl<uint64_t> &Record,
359 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
361 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
363 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
365 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
367 SmallVectorImpl<uint64_t> &Record,
369 void writeDIFile(
const DIFile *
N, SmallVectorImpl<uint64_t> &Record,
372 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
374 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
376 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
378 SmallVectorImpl<uint64_t> &Record,
381 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
384 void writeDIMacro(
const DIMacro *
N, SmallVectorImpl<uint64_t> &Record,
388 void writeDIArgList(
const DIArgList *
N, SmallVectorImpl<uint64_t> &Record);
389 void writeDIModule(
const DIModule *
N, SmallVectorImpl<uint64_t> &Record,
391 void writeDIAssignID(
const DIAssignID *
N, SmallVectorImpl<uint64_t> &Record,
394 SmallVectorImpl<uint64_t> &Record,
397 SmallVectorImpl<uint64_t> &Record,
400 SmallVectorImpl<uint64_t> &Record,
403 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
405 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
407 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
409 SmallVectorImpl<uint64_t> &Record,
412 SmallVectorImpl<uint64_t> &Record,
unsigned Abbrev);
413 void writeDIProperty(
const DIProperty *
N, SmallVectorImpl<uint64_t> &Record,
416 SmallVectorImpl<uint64_t> &Record,
418 unsigned createNamedMetadataAbbrev();
419 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
420 unsigned createMetadataStringsAbbrev();
422 SmallVectorImpl<uint64_t> &Record);
424 SmallVectorImpl<uint64_t> &Record,
425 std::vector<unsigned> *MDAbbrevs =
nullptr,
426 std::vector<uint64_t> *IndexPos =
nullptr);
427 void writeModuleMetadata();
428 void writeFunctionMetadata(
const Function &
F);
429 void writeFunctionMetadataAttachment(
const Function &
F);
430 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
431 const GlobalObject &GO);
432 void writeModuleMetadataKinds();
433 void writeOperandBundleTags();
434 void writeSyncScopeNames();
435 void writeConstants(
unsigned FirstVal,
unsigned LastVal,
bool isGlobal);
436 void writeModuleConstants();
437 bool pushValueAndType(
const Value *
V,
unsigned InstID,
438 SmallVectorImpl<unsigned> &Vals);
439 bool pushValueOrMetadata(
const Value *
V,
unsigned InstID,
440 SmallVectorImpl<unsigned> &Vals);
441 void writeOperandBundles(
const CallBase &CB,
unsigned InstID);
442 void pushValue(
const Value *
V,
unsigned InstID,
443 SmallVectorImpl<unsigned> &Vals);
444 void pushValueSigned(
const Value *
V,
unsigned InstID,
445 SmallVectorImpl<uint64_t> &Vals);
446 void writeInstruction(
const Instruction &
I,
unsigned InstID,
447 SmallVectorImpl<unsigned> &Vals);
448 void writeFunctionLevelValueSymbolTable(
const ValueSymbolTable &VST);
449 void writeGlobalValueSymbolTable(
450 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
451 void writeUseList(UseListOrder &&Order);
452 void writeUseListBlock(
const Function *
F);
455 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
456 void writeBlockInfo();
457 void writeModuleHash(StringRef View);
460 return unsigned(SSID);
463 unsigned getEncodedAlign(MaybeAlign Alignment) {
return encode(Alignment); }
467class IndexBitcodeWriter :
public BitcodeWriterBase {
469 const ModuleSummaryIndex &
Index;
485 SortedSummariesForIndex;
489 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
493 std::vector<uint64_t> StackIds;
498 DenseMap<unsigned, unsigned> StackIdIndicesToIndex;
501 unsigned GlobalValueId = 0;
505 DenseMap<StringRef, uint64_t> ModuleIdMap;
515 BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
516 const ModuleSummaryIndex &Index,
519 : BitcodeWriterBase(Stream, StrtabBuilder),
Index(
Index),
520 DecSummaries(DecSummaries),
521 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
522 if (ModuleToSummariesForIndex) {
523 for (
const auto &[ModPath, Summaries] : *ModuleToSummariesForIndex)
534 auto RecordStackIdReference = [&](
unsigned StackIdIndex) {
539 StackIdIndicesToIndex.
insert({StackIdIndex, StackIds.size()});
541 StackIds.push_back(
Index.getStackIdAtIndex(StackIdIndex));
548 forEachSummary([&](GVInfo
I,
bool IsAliasee) {
549 GUIDToValueIdMap[
I.first] = ++GlobalValueId;
561 for (
auto &CI :
FS->callsites()) {
572 if (CI.StackIdIndices.empty()) {
573 GUIDToValueIdMap[CI.Callee.getGUID()] = ++GlobalValueId;
576 for (
auto Idx : CI.StackIdIndices)
577 RecordStackIdReference(Idx);
580 for (
auto &AI :
FS->allocs())
581 for (
auto &MIB : AI.MIBs)
582 for (
auto Idx : MIB.StackIdIndices)
583 RecordStackIdReference(Idx);
589 using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
594 template<
typename Functor>
595 void forEachSummary(Functor Callback) {
596 if (ModuleToSummariesForIndex) {
597 for (
auto &[GUID, GVS] : SortedSummariesForIndex) {
603 Callback({AS->getAliaseeGUID(), &AS->getAliasee()},
true);
607 for (
const auto &Summaries :
Index.sortedGlobalValueSummariesRange())
608 for (
auto &Summary : Summaries.second.getSummaryList())
617 template <
typename Functor>
void forEachModule(Functor Callback) {
618 if (ModuleToSummariesForIndex) {
619 for (
const auto &M : *ModuleToSummariesForIndex) {
620 const auto &MPI =
Index.modulePaths().find(
M.first);
621 if (MPI ==
Index.modulePaths().end()) {
625 assert(ModuleToSummariesForIndex->size() == 1);
635 std::vector<StringRef> ModulePaths;
636 for (
auto &[ModPath,
_] :
Index.modulePaths())
637 ModulePaths.push_back(ModPath);
639 for (
auto &ModPath : ModulePaths)
648 void writeModStrings();
649 void writeCombinedGlobalValueSummary();
652 auto VMI = GUIDToValueIdMap.find(ValGUID);
653 if (VMI == GUIDToValueIdMap.end())
658 std::map<GlobalValue::GUID, unsigned> &valueIds() {
return GUIDToValueIdMap; }
693 case Instruction::Add:
695 case Instruction::Sub:
697 case Instruction::Mul:
700 case Instruction::FDiv:
703 case Instruction::FRem:
715 unsigned Encoding = 0;
716 switch (
I.getOperation()) {
789 if (
I.isElementwise())
824 case Attribute::Alignment:
826 case Attribute::AllocAlign:
828 case Attribute::AllocSize:
830 case Attribute::AlwaysInline:
832 case Attribute::Builtin:
834 case Attribute::ByVal:
836 case Attribute::Convergent:
838 case Attribute::InAlloca:
840 case Attribute::Cold:
842 case Attribute::DisableSanitizerInstrumentation:
844 case Attribute::FnRetThunkExtern:
846 case Attribute::Flatten:
850 case Attribute::ElementType:
852 case Attribute::HybridPatchable:
854 case Attribute::InlineHint:
856 case Attribute::InReg:
858 case Attribute::JumpTable:
860 case Attribute::MinSize:
862 case Attribute::AllocatedPointer:
864 case Attribute::AllocKind:
866 case Attribute::Memory:
868 case Attribute::NoFPClass:
870 case Attribute::Naked:
872 case Attribute::Nest:
874 case Attribute::NoAlias:
876 case Attribute::NoBuiltin:
878 case Attribute::NoCallback:
880 case Attribute::NoDivergenceSource:
882 case Attribute::AlwaysUniform:
884 case Attribute::NoDuplicate:
886 case Attribute::NoFree:
888 case Attribute::NoFreeObj:
890 case Attribute::NoImplicitFloat:
892 case Attribute::NoInline:
894 case Attribute::NoRecurse:
896 case Attribute::NoMerge:
898 case Attribute::NonLazyBind:
900 case Attribute::NonNull:
902 case Attribute::Dereferenceable:
904 case Attribute::DereferenceableOrNull:
906 case Attribute::NoRedZone:
908 case Attribute::NoReturn:
910 case Attribute::NoSync:
912 case Attribute::NoCfCheck:
914 case Attribute::NoProfile:
916 case Attribute::SkipProfile:
918 case Attribute::NoUnwind:
920 case Attribute::NoSanitizeBounds:
922 case Attribute::NoSanitizeCoverage:
924 case Attribute::NullPointerIsValid:
926 case Attribute::OptimizeForDebugging:
928 case Attribute::OptForFuzzing:
930 case Attribute::OptimizeForSize:
932 case Attribute::OptimizeNone:
934 case Attribute::ReadNone:
936 case Attribute::ReadOnly:
938 case Attribute::Returned:
940 case Attribute::ReturnsTwice:
942 case Attribute::SExt:
944 case Attribute::Speculatable:
946 case Attribute::StackAlignment:
948 case Attribute::StackProtect:
950 case Attribute::StackProtectReq:
952 case Attribute::StackProtectStrong:
954 case Attribute::SafeStack:
956 case Attribute::ShadowCallStack:
958 case Attribute::StrictFP:
960 case Attribute::StructRet:
962 case Attribute::SanitizeAddress:
964 case Attribute::SanitizeAllocToken:
966 case Attribute::SanitizeHWAddress:
968 case Attribute::SanitizeThread:
970 case Attribute::SanitizeConcurrency:
972 case Attribute::SanitizeType:
974 case Attribute::SanitizeMemory:
976 case Attribute::SanitizeNumericalStability:
978 case Attribute::SanitizeRealtime:
980 case Attribute::SanitizeRealtimeBlocking:
982 case Attribute::SpeculativeLoadHardening:
984 case Attribute::SwiftError:
986 case Attribute::SwiftSelf:
988 case Attribute::SwiftAsync:
990 case Attribute::UWTable:
992 case Attribute::VScaleRange:
994 case Attribute::WillReturn:
996 case Attribute::WriteOnly:
998 case Attribute::ZExt:
1000 case Attribute::ImmArg:
1002 case Attribute::SanitizeMemTag:
1004 case Attribute::Preallocated:
1006 case Attribute::NoUndef:
1008 case Attribute::ByRef:
1010 case Attribute::MustProgress:
1012 case Attribute::PresplitCoroutine:
1014 case Attribute::Writable:
1016 case Attribute::CoroDestroyOnlyWhenComplete:
1018 case Attribute::CoroElideSafe:
1020 case Attribute::DeadOnUnwind:
1022 case Attribute::Range:
1024 case Attribute::Initializes:
1026 case Attribute::NoExt:
1028 case Attribute::Captures:
1030 case Attribute::DeadOnReturn:
1032 case Attribute::NoCreateUndefOrPoison:
1034 case Attribute::DenormalFPEnv:
1036 case Attribute::NoOutline:
1038 case Attribute::NoIPA:
1040 case Attribute::LikelyModuleLocal:
1052 if ((int64_t)
V >= 0)
1063 unsigned NumWords =
A.getActiveWords();
1064 const uint64_t *RawData =
A.getRawData();
1065 for (
unsigned i = 0; i < NumWords; i++)
1085void ModuleBitcodeWriter::writeAttributeGroupTable() {
1086 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
1088 if (AttrGrps.empty())
return;
1092 SmallVector<uint64_t, 64>
Record;
1094 unsigned AttrListIndex = Pair.first;
1095 AttributeSet AS = Pair.second;
1097 Record.push_back(AttrListIndex);
1100 if (Attr.isEnumAttribute()) {
1103 }
else if (Attr.isIntAttribute()) {
1105 Attribute::AttrKind
Kind = Attr.getKindAsEnum();
1107 if (Kind == Attribute::Memory) {
1112 Record.push_back(Attr.getValueAsInt());
1114 }
else if (Attr.isStringAttribute()) {
1115 StringRef
Kind = Attr.getKindAsString();
1116 StringRef Val = Attr.getValueAsString();
1125 }
else if (Attr.isTypeAttribute()) {
1126 Type *Ty = Attr.getValueAsType();
1127 Record.push_back(Ty ? 6 : 5);
1131 }
else if (Attr.isConstantRangeAttribute()) {
1137 assert(Attr.isConstantRangeListAttribute());
1143 for (
auto &CR : Val)
1155void ModuleBitcodeWriter::writeAttributeTable() {
1157 if (
Attrs.empty())
return;
1161 SmallVector<uint64_t, 64>
Record;
1162 for (
const AttributeList &AL : Attrs) {
1163 for (
unsigned i :
AL.indexes()) {
1164 AttributeSet AS =
AL.getAttributes(i);
1177void ModuleBitcodeWriter::writeTypeTable() {
1181 SmallVector<uint64_t, 64> TypeVals;
1186 auto Abbv = std::make_shared<BitCodeAbbrev>();
1188 Abbv->Add(BitCodeAbbrevOp(0));
1189 unsigned OpaquePtrAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1192 Abbv = std::make_shared<BitCodeAbbrev>();
1197 unsigned FunctionAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1200 Abbv = std::make_shared<BitCodeAbbrev>();
1205 unsigned StructAnonAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1208 Abbv = std::make_shared<BitCodeAbbrev>();
1212 unsigned StructNameAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1215 Abbv = std::make_shared<BitCodeAbbrev>();
1220 unsigned StructNamedAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1223 Abbv = std::make_shared<BitCodeAbbrev>();
1227 unsigned ArrayAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1235 for (
Type *
T : TypeList) {
1236 int AbbrevToUse = 0;
1239 switch (
T->getTypeID()) {
1249 case Type::MetadataTyID:
1254 case Type::ByteTyID:
1259 case Type::IntegerTyID:
1264 case Type::PointerTyID: {
1271 AbbrevToUse = OpaquePtrAbbrev;
1274 case Type::FunctionTyID: {
1280 for (
unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
1282 AbbrevToUse = FunctionAbbrev;
1285 case Type::StructTyID: {
1290 for (
Type *ET :
ST->elements())
1293 if (
ST->isLiteral()) {
1295 AbbrevToUse = StructAnonAbbrev;
1297 if (
ST->isOpaque()) {
1301 AbbrevToUse = StructNamedAbbrev;
1305 if (!
ST->getName().empty())
1311 case Type::ArrayTyID: {
1315 TypeVals.
push_back(AT->getNumElements());
1317 AbbrevToUse = ArrayAbbrev;
1320 case Type::FixedVectorTyID:
1321 case Type::ScalableVectorTyID: {
1326 TypeVals.
push_back(VT->getElementCount().getKnownMinValue());
1332 case Type::TargetExtTyID: {
1338 for (
Type *InnerTy :
TET->type_params())
1343 case Type::TypedPointerTyID:
1348 Stream.
EmitRecord(Code, TypeVals, AbbrevToUse);
1389 RawFlags |= Flags.ReadNone;
1390 RawFlags |= (Flags.ReadOnly << 1);
1391 RawFlags |= (Flags.NoRecurse << 2);
1392 RawFlags |= (Flags.ReturnDoesNotAlias << 3);
1393 RawFlags |= (Flags.NoInline << 4);
1394 RawFlags |= (Flags.AlwaysInline << 5);
1395 RawFlags |= (Flags.NoUnwind << 6);
1396 RawFlags |= (Flags.MayThrow << 7);
1397 RawFlags |= (Flags.HasUnknownCall << 8);
1398 RawFlags |= (Flags.MustBeUnreachable << 9);
1399 RawFlags |= (Flags.HasEscapingBlockAddress << 10);
1406 bool ImportAsDecl =
false) {
1409 RawFlags |= Flags.NotEligibleToImport;
1410 RawFlags |= (Flags.Live << 1);
1411 RawFlags |= (Flags.DSOLocal << 2);
1412 RawFlags |= (Flags.CanAutoHide << 3);
1417 RawFlags = (RawFlags << 4) | Flags.Linkage;
1419 RawFlags |= (Flags.Visibility << 8);
1421 unsigned ImportType = Flags.ImportType | ImportAsDecl;
1422 RawFlags |= (ImportType << 10);
1424 RawFlags |= (Flags.NoRenameOnPromotion << 11);
1430 uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) |
1431 (Flags.Constant << 2) | Flags.VCallVisibility << 3;
1475 switch (
C.getSelectionKind()) {
1499size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1502 return StrtabBuilder.
add(Str);
1505void ModuleBitcodeWriter::writeComdats() {
1520void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
1525 auto Abbv = std::make_shared<BitCodeAbbrev>();
1531 unsigned VSTOffsetAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1547 bool isChar6 =
true;
1548 for (
char C : Str) {
1551 if ((
unsigned char)
C & 128)
1560static_assert(
sizeof(GlobalValue::SanitizerMetadata) <=
sizeof(unsigned),
1561 "Sanitizer Metadata is too large for naive serialization.");
1564 return Meta.NoAddress | (
Meta.NoHWAddress << 1) |
1565 (
Meta.Memtag << 2) | (
Meta.IsDynInit << 3);
1571void ModuleBitcodeWriter::writeModuleInfo() {
1573 if (!
M.getTargetTriple().empty())
1575 M.getTargetTriple().str(), 0 );
1576 const std::string &
DL =
M.getDataLayoutStr();
1580 for (
const Module::GlobalAsmFragment &Frag :
M.getModuleInlineAsm()) {
1582 Frag.Props.getAsStrings();
1595 std::map<std::string, unsigned> SectionMap;
1596 std::map<std::string, unsigned> GCMap;
1597 MaybeAlign MaxGVarAlignment;
1598 unsigned MaxGlobalType = 0;
1599 for (
const GlobalVariable &GV :
M.globals()) {
1600 if (MaybeAlign
A = GV.getAlign())
1601 MaxGVarAlignment = !MaxGVarAlignment ? *
A : std::max(*MaxGVarAlignment, *
A);
1602 MaxGlobalType = std::max(MaxGlobalType, VE.
getTypeID(GV.getValueType()));
1603 if (GV.hasSection()) {
1605 unsigned &
Entry = SectionMap[std::string(GV.getSection())];
1609 Entry = SectionMap.size();
1614 if (
F.hasSection()) {
1616 unsigned &
Entry = SectionMap[std::string(
F.getSection())];
1620 Entry = SectionMap.size();
1625 unsigned &
Entry = GCMap[
F.getGC()];
1629 Entry = GCMap.size();
1635 unsigned SimpleGVarAbbrev = 0;
1636 if (!
M.global_empty()) {
1638 auto Abbv = std::make_shared<BitCodeAbbrev>();
1649 if (!MaxGVarAlignment)
1650 Abbv->Add(BitCodeAbbrevOp(0));
1652 unsigned MaxEncAlignment = getEncodedAlign(MaxGVarAlignment);
1656 if (SectionMap.empty())
1657 Abbv->Add(BitCodeAbbrevOp(0));
1662 SimpleGVarAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1676 auto Abbv = std::make_shared<BitCodeAbbrev>();
1679 Abbv->Add(AbbrevOpToUse);
1680 unsigned FilenameAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
1682 for (
const auto P :
M.getSourceFileName())
1693 for (
const GlobalVariable &GV :
M.globals()) {
1694 unsigned AbbrevToUse = 0;
1700 Vals.
push_back(addToStrtab(GV.getName()));
1703 Vals.
push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1707 Vals.
push_back(getEncodedAlign(GV.getAlign()));
1708 Vals.
push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]
1710 if (GV.isThreadLocal() ||
1712 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1713 GV.isExternallyInitialized() ||
1715 GV.hasComdat() || GV.hasAttributes() || GV.isDSOLocal() ||
1716 GV.hasPartition() || GV.hasSanitizerMetadata() || GV.getCodeModel()) {
1720 Vals.
push_back(GV.isExternallyInitialized());
1724 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1728 Vals.
push_back(addToStrtab(GV.getPartition()));
1729 Vals.
push_back(GV.getPartition().size());
1732 GV.getSanitizerMetadata())
1736 AbbrevToUse = SimpleGVarAbbrev;
1757 Vals.
push_back(getEncodedAlign(
F.getAlign()));
1758 Vals.
push_back(
F.hasSection() ? SectionMap[std::string(
F.getSection())]
1770 F.hasPersonalityFn() ? (VE.
getValueID(
F.getPersonalityFn()) + 1) : 0);
1774 Vals.
push_back(addToStrtab(
F.getPartition()));
1776 Vals.
push_back(getEncodedAlign(
F.getPreferredAlignment()));
1778 unsigned AbbrevToUse = 0;
1784 for (
const GlobalAlias &
A :
M.aliases()) {
1791 Vals.
push_back(
A.getType()->getAddressSpace());
1799 Vals.
push_back(addToStrtab(
A.getPartition()));
1802 unsigned AbbrevToUse = 0;
1808 for (
const GlobalIFunc &
I :
M.ifuncs()) {
1814 Vals.
push_back(
I.getType()->getAddressSpace());
1819 Vals.
push_back(addToStrtab(
I.getPartition()));
1825 writeValueSymbolTableForwardDecl();
1832 if (OBO->hasNoSignedWrap())
1834 if (OBO->hasNoUnsignedWrap())
1840 if (PDI->isDisjoint())
1843 if (FPMO->hasAllowReassoc())
1845 if (FPMO->hasNoNaNs())
1847 if (FPMO->hasNoInfs())
1849 if (FPMO->hasNoSignedZeros())
1851 if (FPMO->hasAllowReciprocal())
1853 if (FPMO->hasAllowContract())
1855 if (FPMO->hasApproxFunc())
1861 if (NNI->hasNonNeg())
1865 if (NNI->hasNonNeg())
1868 if (TI->hasNoSignedWrap())
1870 if (TI->hasNoUnsignedWrap())
1873 if (
GEP->isInBounds())
1875 if (
GEP->hasNoUnsignedSignedWrap())
1877 if (
GEP->hasNoUnsignedWrap())
1880 if (ICmp->hasSameSign())
1883 if (ASC->hasNonNull())
1890void ModuleBitcodeWriter::writeValueAsMetadata(
1891 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
1900void ModuleBitcodeWriter::writeMDTuple(
const MDTuple *
N,
1901 SmallVectorImpl<uint64_t> &Record,
1903 for (
const MDOperand &MDO :
N->operands()) {
1906 "Unexpected function-local metadata");
1915void ModuleBitcodeWriter::writeMDFunctionLocalContext(
1916 const MDFunctionLocalContext *
N, SmallVectorImpl<uint64_t> &Record,
1928 if (!
N->isNonDebug()) {
1930 Record.push_back(
N->getScopes().size());
1931 for (
const FLScope &Scope :
N->getScopes())
1934 Record.push_back(
N->getSrcLocs().size());
1935 for (
const FLSrcLoc &SrcLoc :
N->getSrcLocs()) {
1936 Record.push_back(SrcLoc.Line);
1937 Record.push_back(SrcLoc.Column);
1939 Record.push_back(SrcLoc.ScopeIdx.asRaw());
1943 Record.push_back(
N->getInlinedCalls().size());
1944 for (
const FLInlinedCall &InlinedCall :
N->getInlinedCalls()) {
1945 Record.push_back(InlinedCall.SrcLocIdx.asRaw());
1952 uint32_t InlinedAtUniquable =
1953 ((uint32_t)InlinedCall.InlinedAtIdx.asRaw() << 1) |
1954 InlinedCall.Uniquable;
1955 Record.push_back(InlinedAtUniquable);
1963unsigned ModuleBitcodeWriter::createDILocationAbbrev(
bool WithIRLayers) {
1969 auto Abbv = std::make_shared<BitCodeAbbrev>();
1984void ModuleBitcodeWriter::writeDILocation(
const DILocation *
N,
1985 SmallVectorImpl<uint64_t> &Record,
1988 Abbrev = createDILocationAbbrev(
false);
1990 Record.push_back(
N->isDistinct());
1991 Record.push_back(
N->getLine());
1992 Record.push_back(
N->getColumn());
1995 Record.push_back(
N->isImplicitCode());
1996 Record.push_back(
N->getAtomGroup());
1997 Record.push_back(
N->getAtomRank());
1999 unsigned AbbrevToUse = Abbrev;
2000 if (DILayerLocList *IRLayers =
N->getIRLayers()) {
2001 if (!DILocationLayersAbbrev)
2002 DILocationLayersAbbrev = createDILocationAbbrev(
true);
2003 AbbrevToUse = DILocationLayersAbbrev;
2011void ModuleBitcodeWriter::writeDILayerLoc(
const DILayerLoc *
N,
2012 SmallVectorImpl<uint64_t> &Record,
2014 Record.push_back(
N->isDistinct());
2015 Record.push_back(
N->getLine());
2016 Record.push_back(
N->getColumn());
2023void ModuleBitcodeWriter::writeDILayerLocList(
const DILayerLocList *
N,
2024 SmallVectorImpl<uint64_t> &Record,
2026 Record.push_back(
N->isDistinct());
2027 for (
const MDOperand &
Op :
N->layers())
2033unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
2036 auto Abbv = std::make_shared<BitCodeAbbrev>();
2047void ModuleBitcodeWriter::writeGenericDINode(
const GenericDINode *
N,
2048 SmallVectorImpl<uint64_t> &Record,
2051 Abbrev = createGenericDINodeAbbrev();
2053 Record.push_back(
N->isDistinct());
2054 Record.push_back(
N->getTag());
2057 for (
auto &
I :
N->operands())
2064void ModuleBitcodeWriter::writeDISubrange(
const DISubrange *
N,
2065 SmallVectorImpl<uint64_t> &Record,
2078void ModuleBitcodeWriter::writeDIGenericSubrange(
2079 const DIGenericSubrange *
N, SmallVectorImpl<uint64_t> &Record,
2091void ModuleBitcodeWriter::writeDIEnumerator(
const DIEnumerator *
N,
2092 SmallVectorImpl<uint64_t> &Record,
2095 Record.push_back(IsBigInt | (
N->isUnsigned() << 1) |
N->isDistinct());
2096 Record.push_back(
N->getValue().getBitWidth());
2104void ModuleBitcodeWriter::writeDIBasicType(
const DIBasicType *
N,
2105 SmallVectorImpl<uint64_t> &Record,
2107 const unsigned SizeIsMetadata = 0x2;
2108 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2109 Record.push_back(
N->getTag());
2112 Record.push_back(
N->getAlignInBits());
2113 Record.push_back(
N->getEncoding());
2114 Record.push_back(
N->getFlags());
2115 Record.push_back(
N->getNumExtraInhabitants());
2116 Record.push_back(
N->getDataSizeInBits());
2118 Record.push_back(
N->getLine());
2125void ModuleBitcodeWriter::writeDIFixedPointType(
2126 const DIFixedPointType *
N, SmallVectorImpl<uint64_t> &Record,
2128 const unsigned SizeIsMetadata = 0x2;
2129 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2130 Record.push_back(
N->getTag());
2133 Record.push_back(
N->getAlignInBits());
2134 Record.push_back(
N->getEncoding());
2135 Record.push_back(
N->getFlags());
2136 Record.push_back(
N->getKind());
2137 Record.push_back(
N->getFactorRaw());
2139 auto WriteWideInt = [&](
const APInt &
Value) {
2144 Record.push_back(Encoded);
2148 WriteWideInt(
N->getNumeratorRaw());
2149 WriteWideInt(
N->getDenominatorRaw());
2152 Record.push_back(
N->getLine());
2159void ModuleBitcodeWriter::writeDIStringType(
const DIStringType *
N,
2160 SmallVectorImpl<uint64_t> &Record,
2162 const unsigned SizeIsMetadata = 0x2;
2163 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2164 Record.push_back(
N->getTag());
2170 Record.push_back(
N->getAlignInBits());
2171 Record.push_back(
N->getEncoding());
2178void ModuleBitcodeWriter::writeDIDerivedType(
const DIDerivedType *
N,
2179 SmallVectorImpl<uint64_t> &Record,
2181 const unsigned SizeIsMetadata = 0x2;
2182 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2183 Record.push_back(
N->getTag());
2186 Record.push_back(
N->getLine());
2190 Record.push_back(
N->getAlignInBits());
2192 Record.push_back(
N->getFlags());
2197 if (
const auto &DWARFAddressSpace =
N->getDWARFAddressSpace())
2198 Record.push_back(*DWARFAddressSpace + 1);
2204 if (
auto PtrAuthData =
N->getPtrAuthData())
2205 Record.push_back(PtrAuthData->RawData);
2213void ModuleBitcodeWriter::writeDISubrangeType(
const DISubrangeType *
N,
2214 SmallVectorImpl<uint64_t> &Record,
2216 const unsigned SizeIsMetadata = 0x2;
2217 Record.push_back(SizeIsMetadata | (
unsigned)
N->isDistinct());
2220 Record.push_back(
N->getLine());
2223 Record.push_back(
N->getAlignInBits());
2224 Record.push_back(
N->getFlags());
2235void ModuleBitcodeWriter::writeDICompositeType(
2236 const DICompositeType *
N, SmallVectorImpl<uint64_t> &Record,
2238 const unsigned IsNotUsedInOldTypeRef = 0x2;
2239 const unsigned SizeIsMetadata = 0x4;
2240 Record.push_back(SizeIsMetadata | IsNotUsedInOldTypeRef |
2241 (
unsigned)
N->isDistinct());
2242 Record.push_back(
N->getTag());
2245 Record.push_back(
N->getLine());
2249 Record.push_back(
N->getAlignInBits());
2251 Record.push_back(
N->getFlags());
2253 Record.push_back(
N->getRuntimeLang());
2263 Record.push_back(
N->getNumExtraInhabitants());
2273void ModuleBitcodeWriter::writeDISubroutineType(
2274 const DISubroutineType *
N, SmallVectorImpl<uint64_t> &Record,
2276 const unsigned HasNoOldTypeRefs = 0x2;
2277 Record.push_back(HasNoOldTypeRefs | (
unsigned)
N->isDistinct());
2278 Record.push_back(
N->getFlags());
2286void ModuleBitcodeWriter::writeDIFile(
const DIFile *
N,
2287 SmallVectorImpl<uint64_t> &Record,
2289 Record.push_back(
N->isDistinct());
2292 if (
N->getRawChecksum()) {
2293 Record.push_back(
N->getRawChecksum()->Kind);
2301 auto Source =
N->getRawSource();
2309void ModuleBitcodeWriter::writeDICompileUnit(
const DICompileUnit *
N,
2310 SmallVectorImpl<uint64_t> &Record,
2312 assert(
N->isDistinct() &&
"Expected distinct compile units");
2315 auto Lang =
N->getSourceLanguage();
2316 Record.push_back(Lang.getName());
2319 if (Lang.hasVersionedName())
2324 Record.push_back(
N->isOptimized());
2326 Record.push_back(
N->getRuntimeVersion());
2328 Record.push_back(
N->getEmissionKind());
2334 Record.push_back(
N->getDWOId());
2336 Record.push_back(
N->getSplitDebugInlining());
2337 Record.push_back(
N->getDebugInfoForProfiling());
2338 Record.push_back((
unsigned)
N->getNameTableKind());
2339 Record.push_back(
N->getRangesBaseAddress());
2342 Record.push_back(Lang.hasVersionedName() ? Lang.getVersion() : 0);
2343 Record.push_back(Lang.getDialect());
2349void ModuleBitcodeWriter::writeDISubprogram(
const DISubprogram *
N,
2350 SmallVectorImpl<uint64_t> &Record,
2352 const uint64_t HasUnitFlag = 1 << 1;
2353 const uint64_t HasSPFlagsFlag = 1 << 2;
2354 Record.push_back(
uint64_t(
N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
2359 Record.push_back(
N->getLine());
2361 Record.push_back(
N->getScopeLine());
2363 Record.push_back(
N->getSPFlags());
2364 Record.push_back(
N->getVirtualIndex());
2365 Record.push_back(
N->getFlags());
2370 Record.push_back(
N->getThisAdjustment());
2374 Record.push_back(
N->getKeyInstructionsEnabled());
2380void ModuleBitcodeWriter::writeDILexicalBlock(
const DILexicalBlock *
N,
2381 SmallVectorImpl<uint64_t> &Record,
2383 Record.push_back(
N->isDistinct());
2386 Record.push_back(
N->getLine());
2387 Record.push_back(
N->getColumn());
2393void ModuleBitcodeWriter::writeDILexicalBlockFile(
2394 const DILexicalBlockFile *
N, SmallVectorImpl<uint64_t> &Record,
2396 Record.push_back(
N->isDistinct());
2399 Record.push_back(
N->getDiscriminator());
2405void ModuleBitcodeWriter::writeDICommonBlock(
const DICommonBlock *
N,
2406 SmallVectorImpl<uint64_t> &Record,
2408 Record.push_back(
N->isDistinct());
2413 Record.push_back(
N->getLineNo());
2419void ModuleBitcodeWriter::writeDINamespace(
const DINamespace *
N,
2420 SmallVectorImpl<uint64_t> &Record,
2422 Record.push_back(
N->isDistinct() |
N->getExportSymbols() << 1);
2430void ModuleBitcodeWriter::writeDIMacro(
const DIMacro *
N,
2431 SmallVectorImpl<uint64_t> &Record,
2433 Record.push_back(
N->isDistinct());
2434 Record.push_back(
N->getMacinfoType());
2435 Record.push_back(
N->getLine());
2443void ModuleBitcodeWriter::writeDIMacroFile(
const DIMacroFile *
N,
2444 SmallVectorImpl<uint64_t> &Record,
2446 Record.push_back(
N->isDistinct());
2447 Record.push_back(
N->getMacinfoType());
2448 Record.push_back(
N->getLine());
2456void ModuleBitcodeWriter::writeDIArgList(
const DIArgList *
N,
2457 SmallVectorImpl<uint64_t> &Record) {
2458 Record.reserve(
N->getArgs().size());
2459 for (ValueAsMetadata *MD :
N->getArgs())
2466void ModuleBitcodeWriter::writeDIModule(
const DIModule *
N,
2467 SmallVectorImpl<uint64_t> &Record,
2469 Record.push_back(
N->isDistinct());
2470 for (
auto &
I :
N->operands())
2472 Record.push_back(
N->getLineNo());
2473 Record.push_back(
N->getIsDecl());
2479void ModuleBitcodeWriter::writeDIAssignID(
const DIAssignID *
N,
2480 SmallVectorImpl<uint64_t> &Record,
2483 Record.push_back(
N->isDistinct());
2488void ModuleBitcodeWriter::writeDITemplateTypeParameter(
2489 const DITemplateTypeParameter *
N, SmallVectorImpl<uint64_t> &Record,
2491 Record.push_back(
N->isDistinct());
2494 Record.push_back(
N->isDefault());
2500void ModuleBitcodeWriter::writeDITemplateValueParameter(
2501 const DITemplateValueParameter *
N, SmallVectorImpl<uint64_t> &Record,
2503 Record.push_back(
N->isDistinct());
2504 Record.push_back(
N->getTag());
2507 Record.push_back(
N->isDefault());
2514void ModuleBitcodeWriter::writeDIGlobalVariable(
2515 const DIGlobalVariable *
N, SmallVectorImpl<uint64_t> &Record,
2523 Record.push_back(
N->getLine());
2525 Record.push_back(
N->isLocalToUnit());
2526 Record.push_back(
N->isDefinition());
2529 Record.push_back(
N->getAlignInBits());
2536void ModuleBitcodeWriter::writeDILocalVariable(
2537 const DILocalVariable *
N, SmallVectorImpl<uint64_t> &Record,
2552 const uint64_t HasAlignmentFlag = 1 << 1;
2557 Record.push_back(
N->getLine());
2559 Record.push_back(
N->getArg());
2560 Record.push_back(
N->getFlags());
2561 Record.push_back(
N->getAlignInBits());
2568void ModuleBitcodeWriter::writeDILabel(
2569 const DILabel *
N, SmallVectorImpl<uint64_t> &Record,
2576 Record.push_back(
N->getLine());
2577 Record.push_back(
N->getColumn());
2578 Record.push_back(
N->getCoroSuspendIdx().has_value()
2579 ? (
uint64_t)
N->getCoroSuspendIdx().value()
2580 : std::numeric_limits<uint64_t>::max());
2586void ModuleBitcodeWriter::writeDIExpression(
const DIExpression *
N,
2587 SmallVectorImpl<uint64_t> &Record,
2589 Record.reserve(
N->getElements().size() + 1);
2592 Record.append(
N->elements_begin(),
N->elements_end());
2598void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
2599 const DIGlobalVariableExpression *
N, SmallVectorImpl<uint64_t> &Record,
2601 Record.push_back(
N->isDistinct());
2609void ModuleBitcodeWriter::writeDIObjCProperty(
const DIObjCProperty *
N,
2610 SmallVectorImpl<uint64_t> &Record,
2612 Record.push_back(
N->isDistinct());
2615 Record.push_back(
N->getLine());
2618 Record.push_back(
N->getAttributes());
2625void ModuleBitcodeWriter::writeDIProperty(
const DIProperty *
N,
2626 SmallVectorImpl<uint64_t> &Record,
2628 Record.push_back(
N->isDistinct());
2631 Record.push_back(
N->getLine());
2639void ModuleBitcodeWriter::writeDIImportedEntity(
2640 const DIImportedEntity *
N, SmallVectorImpl<uint64_t> &Record,
2642 Record.push_back(
N->isDistinct());
2643 Record.push_back(
N->getTag());
2646 Record.push_back(
N->getLine());
2655unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
2656 auto Abbv = std::make_shared<BitCodeAbbrev>();
2663void ModuleBitcodeWriter::writeNamedMetadata(
2664 SmallVectorImpl<uint64_t> &Record) {
2665 if (
M.named_metadata_empty())
2668 unsigned Abbrev = createNamedMetadataAbbrev();
2669 for (
const NamedMDNode &NMD :
M.named_metadata()) {
2671 StringRef Str = NMD.getName();
2672 Record.append(Str.bytes_begin(), Str.bytes_end());
2677 for (
const MDNode *
N : NMD.operands())
2684unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
2685 auto Abbv = std::make_shared<BitCodeAbbrev>();
2697void ModuleBitcodeWriter::writeMetadataStrings(
2699 if (Strings.
empty())
2707 SmallString<256> Blob;
2709 BitstreamWriter
W(Blob);
2729#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
2730#include "llvm/IR/Metadata.def"
2734void ModuleBitcodeWriter::writeMetadataRecords(
2736 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
2741#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
2742#include "llvm/IR/Metadata.def"
2748 assert(
N->isResolved() &&
"Expected forward references to be resolved");
2750 switch (
N->getMetadataID()) {
2753#define HANDLE_MDNODE_LEAF(CLASS) \
2754 case Metadata::CLASS##Kind: \
2756 write##CLASS(cast<CLASS>(N), Record, \
2757 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
2759 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
2761#include "llvm/IR/Metadata.def"
2772void ModuleBitcodeWriter::writeModuleMetadata() {
2773 if (!VE.
hasMDs() &&
M.named_metadata_empty())
2777 SmallVector<uint64_t, 64>
Record;
2781 std::vector<unsigned> MDAbbrevs;
2784 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] =
2785 createDILocationAbbrev(
false);
2786 DILocationLayersAbbrev = createDILocationAbbrev(
true);
2787 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
2788 createGenericDINodeAbbrev();
2790 auto Abbv = std::make_shared<BitCodeAbbrev>();
2794 unsigned OffsetAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
2796 Abbv = std::make_shared<BitCodeAbbrev>();
2800 unsigned IndexAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
2822 std::vector<uint64_t> IndexPos;
2826 writeMetadataRecords(VE.
getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2837 uint64_t PreviousValue = IndexOffsetRecordBitPos;
2838 for (
auto &Elt : IndexPos) {
2839 auto EltDelta = Elt - PreviousValue;
2840 PreviousValue = Elt;
2849 writeNamedMetadata(Record);
2851 auto AddDeclAttachedMetadata = [&](
const GlobalObject &GO) {
2852 SmallVector<uint64_t, 4>
Record;
2854 pushGlobalMetadataAttachment(Record, GO);
2858 if (
F.isDeclaration() &&
F.hasMetadata())
2859 AddDeclAttachedMetadata(
F);
2860 for (
const GlobalIFunc &GI :
M.ifuncs())
2861 if (GI.hasMetadata())
2862 AddDeclAttachedMetadata(GI);
2865 for (
const GlobalVariable &GV :
M.globals())
2866 if (GV.hasMetadata())
2867 AddDeclAttachedMetadata(GV);
2872void ModuleBitcodeWriter::writeFunctionMetadata(
const Function &
F) {
2879 DILocationLayersAbbrev = 0;
2880 SmallVector<uint64_t, 64>
Record;
2886void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2887 SmallVectorImpl<uint64_t> &Record,
const GlobalObject &GO) {
2891 for (
const auto &
I : MDs) {
2897void ModuleBitcodeWriter::writeFunctionMetadataAttachment(
const Function &
F) {
2900 SmallVector<uint64_t, 64>
Record;
2902 if (
F.hasMetadata()) {
2903 pushGlobalMetadataAttachment(Record,
F);
2911 for (
const BasicBlock &BB :
F)
2912 for (
const Instruction &
I : BB) {
2914 I.getAllMetadataOtherThanDebugLoc(MDs);
2917 if (MDs.
empty())
continue;
2921 for (
const auto &[ID, MD] : MDs) {
2932void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2933 SmallVector<uint64_t, 64>
Record;
2938 M.getMDKindNames(Names);
2940 if (Names.
empty())
return;
2944 for (
unsigned MDKindID = 0, e = Names.
size(); MDKindID != e; ++MDKindID) {
2945 Record.push_back(MDKindID);
2946 StringRef KName = Names[MDKindID];
2956void ModuleBitcodeWriter::writeOperandBundleTags() {
2964 M.getOperandBundleTags(Tags);
2971 SmallVector<uint64_t, 64>
Record;
2973 for (
auto Tag : Tags) {
2983void ModuleBitcodeWriter::writeSyncScopeNames() {
2985 M.getContext().getSyncScopeNames(SSNs);
2991 SmallVector<uint64_t, 64>
Record;
2992 for (
auto SSN : SSNs) {
2993 Record.append(SSN.begin(), SSN.end());
3001void ModuleBitcodeWriter::writeConstants(
unsigned FirstVal,
unsigned LastVal,
3003 if (FirstVal == LastVal)
return;
3007 unsigned AggregateAbbrev = 0;
3008 unsigned String8Abbrev = 0;
3009 unsigned CString7Abbrev = 0;
3010 unsigned CString6Abbrev = 0;
3014 auto Abbv = std::make_shared<BitCodeAbbrev>();
3018 AggregateAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
3021 Abbv = std::make_shared<BitCodeAbbrev>();
3025 String8Abbrev = Stream.
EmitAbbrev(std::move(Abbv));
3027 Abbv = std::make_shared<BitCodeAbbrev>();
3031 CString7Abbrev = Stream.
EmitAbbrev(std::move(Abbv));
3033 Abbv = std::make_shared<BitCodeAbbrev>();
3037 CString6Abbrev = Stream.
EmitAbbrev(std::move(Abbv));
3040 SmallVector<uint64_t, 64>
Record;
3043 Type *LastTy =
nullptr;
3044 for (
unsigned i = FirstVal; i != LastVal; ++i) {
3045 const Value *
V = Vals[i].first;
3047 if (
V->getType() != LastTy) {
3048 LastTy =
V->getType();
3051 CONSTANTS_SETTYPE_ABBREV);
3058 unsigned(
IA->hasSideEffects()) |
unsigned(
IA->isAlignStack()) << 1 |
3059 unsigned(
IA->getDialect() & 1) << 2 |
unsigned(
IA->canThrow()) << 3);
3062 StringRef AsmStr =
IA->getAsmString();
3067 StringRef ConstraintStr =
IA->getConstraintString();
3075 unsigned Code = -1U;
3076 unsigned AbbrevToUse = 0;
3077 if (
C->isNullValue()) {
3084 if (
IV->getBitWidth() <= 64) {
3088 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
3094 if (BV->getBitWidth() <= 64) {
3098 AbbrevToUse = CONSTANTS_BYTE_ABBREV;
3108 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
3112 APInt api = CFP->getValueAPF().bitcastToAPInt();
3114 Record.push_back((p[1] << 48) | (p[0] >> 16));
3115 Record.push_back(p[0] & 0xffffLL);
3117 APInt api = CFP->getValueAPF().bitcastToAPInt();
3122 assert(0 &&
"Unknown FP type!");
3128 uint64_t NumElts = Str->getNumElements();
3130 if (Str->isCString()) {
3135 AbbrevToUse = String8Abbrev;
3139 for (
uint64_t i = 0; i != NumElts; ++i) {
3140 unsigned char V = Str->getElementAsInteger(i);
3142 isCStr7 &= (
V & 128) == 0;
3148 AbbrevToUse = CString6Abbrev;
3150 AbbrevToUse = CString7Abbrev;
3151 }
else if (
const ConstantDataSequential *CDS =
3154 Type *EltTy = CDS->getElementType();
3156 for (
uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i)
3157 Record.push_back(CDS->getElementAsInteger(i));
3159 for (
uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i)
3161 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
3165 for (
const Value *
Op :
C->operands())
3167 AbbrevToUse = AggregateAbbrev;
3169 switch (
CE->getOpcode()) {
3176 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
3178 assert(
CE->getNumOperands() == 2 &&
"Unknown constant expr!");
3188 case Instruction::GetElementPtr: {
3193 if (std::optional<ConstantRange>
Range = GO->getInRange()) {
3197 for (
const Value *
Op :
CE->operands()) {
3203 case Instruction::ExtractElement:
3210 case Instruction::InsertElement:
3217 case Instruction::ShuffleVector:
3222 if (
C->getType() ==
C->getOperand(0)->getType()) {
3259 Stream.
EmitRecord(Code, Record, AbbrevToUse);
3266void ModuleBitcodeWriter::writeModuleConstants() {
3271 for (
unsigned i = 0, e = Vals.size(); i != e; ++i) {
3273 writeConstants(i, Vals.size(),
true);
3287bool ModuleBitcodeWriter::pushValueAndType(
const Value *
V,
unsigned InstID,
3288 SmallVectorImpl<unsigned> &Vals) {
3292 if (ValID >= InstID) {
3299bool ModuleBitcodeWriter::pushValueOrMetadata(
const Value *
V,
unsigned InstID,
3300 SmallVectorImpl<unsigned> &Vals) {
3301 bool IsMetadata =
V->getType()->isMetadataTy();
3309 return pushValueAndType(
V, InstID, Vals);
3312void ModuleBitcodeWriter::writeOperandBundles(
const CallBase &CS,
3319 Record.push_back(
C.getOperandBundleTagID(Bundle.getTagName()));
3321 for (
auto &Input : Bundle.Inputs)
3322 pushValueOrMetadata(Input, InstID, Record);
3331void ModuleBitcodeWriter::pushValue(
const Value *
V,
unsigned InstID,
3332 SmallVectorImpl<unsigned> &Vals) {
3337void ModuleBitcodeWriter::pushValueSigned(
const Value *
V,
unsigned InstID,
3338 SmallVectorImpl<uint64_t> &Vals) {
3340 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
3345void ModuleBitcodeWriter::writeInstruction(
const Instruction &
I,
3347 SmallVectorImpl<unsigned> &Vals) {
3349 unsigned AbbrevToUse = 0;
3351 switch (
I.getOpcode()) {
3355 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3356 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
3361 if (AbbrevToUse == FUNCTION_INST_CAST_ABBREV)
3362 AbbrevToUse = FUNCTION_INST_CAST_FLAGS_ABBREV;
3368 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3369 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
3370 pushValue(
I.getOperand(1), InstID, Vals);
3374 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
3375 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
3380 case Instruction::FNeg: {
3382 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3383 AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
3387 if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
3388 AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
3393 case Instruction::GetElementPtr: {
3395 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
3399 for (
const Value *
Op :
I.operands())
3400 pushValueAndType(
Op, InstID, Vals);
3403 case Instruction::ExtractValue: {
3405 pushValueAndType(
I.getOperand(0), InstID, Vals);
3410 case Instruction::InsertValue: {
3412 pushValueAndType(
I.getOperand(0), InstID, Vals);
3413 pushValueAndType(
I.getOperand(1), InstID, Vals);
3418 case Instruction::Select: {
3420 pushValueAndType(
I.getOperand(1), InstID, Vals);
3421 pushValue(
I.getOperand(2), InstID, Vals);
3422 pushValueAndType(
I.getOperand(0), InstID, Vals);
3428 case Instruction::ExtractElement:
3430 pushValueAndType(
I.getOperand(0), InstID, Vals);
3431 pushValueAndType(
I.getOperand(1), InstID, Vals);
3433 case Instruction::InsertElement:
3435 pushValueAndType(
I.getOperand(0), InstID, Vals);
3436 pushValue(
I.getOperand(1), InstID, Vals);
3437 pushValueAndType(
I.getOperand(2), InstID, Vals);
3439 case Instruction::BitExtract:
3442 pushValueAndType(
I.getOperand(0), InstID, Vals);
3443 pushValueAndType(
I.getOperand(1), InstID, Vals);
3445 case Instruction::BitInsert:
3447 pushValueAndType(
I.getOperand(0), InstID, Vals);
3448 pushValueAndType(
I.getOperand(1), InstID, Vals);
3449 pushValueAndType(
I.getOperand(2), InstID, Vals);
3451 case Instruction::ShuffleVector:
3453 pushValueAndType(
I.getOperand(0), InstID, Vals);
3454 pushValue(
I.getOperand(1), InstID, Vals);
3458 case Instruction::ICmp:
3459 case Instruction::FCmp: {
3462 AbbrevToUse = FUNCTION_INST_CMP_ABBREV;
3463 if (pushValueAndType(
I.getOperand(0), InstID, Vals))
3465 pushValue(
I.getOperand(1), InstID, Vals);
3471 AbbrevToUse = FUNCTION_INST_CMP_FLAGS_ABBREV;
3476 case Instruction::Ret:
3479 unsigned NumOperands =
I.getNumOperands();
3480 if (NumOperands == 0)
3481 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
3482 else if (NumOperands == 1) {
3483 if (!pushValueAndType(
I.getOperand(0), InstID, Vals))
3484 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
3486 for (
const Value *
Op :
I.operands())
3487 pushValueAndType(
Op, InstID, Vals);
3491 case Instruction::UncondBr: {
3493 AbbrevToUse = FUNCTION_INST_BR_UNCOND_ABBREV;
3497 case Instruction::CondBr: {
3499 AbbrevToUse = FUNCTION_INST_BR_COND_ABBREV;
3503 pushValue(
II.getCondition(), InstID, Vals);
3505 case Instruction::Switch:
3510 pushValue(
SI.getCondition(), InstID, Vals);
3512 for (
auto Case :
SI.cases()) {
3518 case Instruction::IndirectBr:
3522 pushValue(
I.getOperand(0), InstID, Vals);
3527 case Instruction::Invoke: {
3530 FunctionType *FTy =
II->getFunctionType();
3532 if (
II->hasOperandBundles())
3533 writeOperandBundles(*
II, InstID);
3542 pushValueAndType(Callee, InstID, Vals);
3545 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3546 pushValue(
I.getOperand(i), InstID, Vals);
3549 if (FTy->isVarArg()) {
3550 for (
unsigned i = FTy->getNumParams(), e =
II->arg_size(); i != e; ++i)
3551 pushValueAndType(
I.getOperand(i), InstID, Vals);
3555 case Instruction::Resume:
3557 pushValueAndType(
I.getOperand(0), InstID, Vals);
3559 case Instruction::CleanupRet: {
3562 pushValue(CRI.getCleanupPad(), InstID, Vals);
3563 if (CRI.hasUnwindDest())
3567 case Instruction::CatchRet: {
3570 pushValue(CRI.getCatchPad(), InstID, Vals);
3574 case Instruction::CleanupPad:
3575 case Instruction::CatchPad: {
3579 pushValue(FuncletPad.getParentPad(), InstID, Vals);
3581 unsigned NumArgOperands = FuncletPad.arg_size();
3583 for (
unsigned Op = 0;
Op != NumArgOperands; ++
Op)
3584 pushValueAndType(FuncletPad.getArgOperand(
Op), InstID, Vals);
3587 case Instruction::CatchSwitch: {
3591 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
3593 unsigned NumHandlers = CatchSwitch.getNumHandlers();
3595 for (
const BasicBlock *CatchPadBB : CatchSwitch.handlers())
3598 if (CatchSwitch.hasUnwindDest())
3602 case Instruction::CallBr: {
3608 writeOperandBundles(*CBI, InstID);
3623 pushValueAndType(Callee, InstID, Vals);
3626 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3627 pushValue(
I.getOperand(i), InstID, Vals);
3630 if (FTy->isVarArg()) {
3631 for (
unsigned i = FTy->getNumParams(), e = CBI->
arg_size(); i != e; ++i)
3632 pushValueAndType(
I.getOperand(i), InstID, Vals);
3636 case Instruction::Unreachable:
3638 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
3641 case Instruction::PHI: {
3659 Stream.
EmitRecord(Code, Vals64, AbbrevToUse);
3664 case Instruction::LandingPad: {
3675 pushValueAndType(LP.
getClause(
I), InstID, Vals);
3680 case Instruction::Alloca: {
3686 using APV = AllocaPackedValues;
3688 unsigned EncodedAlign = getEncodedAlign(AI.
getAlign());
3690 Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1));
3692 EncodedAlign >> APV::AlignLower::Bits);
3699 if (AS !=
M.getDataLayout().getAllocaAddrSpace())
3704 case Instruction::Load: {
3706 if (LI.isAtomic()) {
3708 pushValueAndType(LI.getOperand(0), InstID, Vals);
3711 if (!pushValueAndType(LI.getOperand(0), InstID, Vals))
3712 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
3715 Vals.
push_back(getEncodedAlign(LI.getAlign()));
3717 if (LI.isAtomic()) {
3719 Vals.
push_back(getEncodedSyncScopeID(LI.getSyncScopeID()));
3720 if (LI.isElementwise())
3726 case Instruction::Store: {
3728 if (
SI.isAtomic()) {
3732 AbbrevToUse = FUNCTION_INST_STORE_ABBREV;
3734 if (pushValueAndType(
I.getOperand(1), InstID, Vals))
3736 if (pushValueAndType(
I.getOperand(0), InstID, Vals))
3740 if (
SI.isAtomic()) {
3742 Vals.
push_back(getEncodedSyncScopeID(
SI.getSyncScopeID()));
3743 if (
SI.isElementwise())
3749 case Instruction::AtomicCmpXchg:
3751 pushValueAndType(
I.getOperand(0), InstID, Vals);
3752 pushValueAndType(
I.getOperand(1), InstID, Vals);
3753 pushValue(
I.getOperand(2), InstID, Vals);
3764 case Instruction::AtomicRMW:
3766 pushValueAndType(
I.getOperand(0), InstID, Vals);
3767 pushValueAndType(
I.getOperand(1), InstID, Vals);
3775 case Instruction::Fence:
3780 case Instruction::Call: {
3785 writeOperandBundles(CI, InstID);
3805 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3809 if (FTy->isVarArg()) {
3810 for (
unsigned i = FTy->getNumParams(), e = CI.
arg_size(); i != e; ++i)
3815 case Instruction::VAArg:
3818 pushValue(
I.getOperand(0), InstID, Vals);
3821 case Instruction::Freeze:
3823 pushValueAndType(
I.getOperand(0), InstID, Vals);
3833void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3834 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3839 VSTOffset -= bitcodeStartBit();
3840 assert((VSTOffset & 31) == 0 &&
"VST block not 32-bit aligned");
3844 Stream.
BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
3848 auto Abbv = std::make_shared<BitCodeAbbrev>();
3852 unsigned FnEntryAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
3857 if (
F.isDeclaration())
3864 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&
F] - bitcodeStartBit();
3865 assert((BitcodeIndex & 31) == 0 &&
"function block not 32-bit aligned");
3869 Record[1] = BitcodeIndex / 32 + 1;
3878void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3879 const ValueSymbolTable &VST) {
3887 SmallVector<uint64_t, 64> NameVals;
3893 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3902 AbbrevToUse = VST_BBENTRY_6_ABBREV;
3906 AbbrevToUse = VST_ENTRY_6_ABBREV;
3908 AbbrevToUse = VST_ENTRY_7_ABBREV;
3911 for (
const auto P :
Name.getKey())
3915 Stream.
EmitRecord(Code, NameVals, AbbrevToUse);
3922void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3923 assert(Order.Shuffle.size() >= 2 &&
"Shuffle too small");
3930 SmallVector<uint64_t, 64>
Record(Order.Shuffle.begin(), Order.Shuffle.end());
3935void ModuleBitcodeWriter::writeUseListBlock(
const Function *
F) {
3937 "Expected to be preserving use-list order");
3939 auto hasMore = [&]() {
3955void ModuleBitcodeWriter::writeFunction(
3957 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3974 unsigned CstStart, CstEnd;
3976 writeConstants(CstStart, CstEnd,
false);
3979 writeFunctionMetadata(
F);
3982 unsigned InstID = CstEnd;
3984 bool NeedsMetadataAttachment =
F.hasMetadata();
3986 DILocation *LastDL =
nullptr;
3987 SmallSetVector<Function *, 4> BlockAddressUsers;
3990 for (
const BasicBlock &BB :
F) {
3991 for (
const Instruction &
I : BB) {
3992 writeInstruction(
I, InstID, Vals);
3994 if (!
I.getType()->isVoidTy())
3998 NeedsMetadataAttachment |=
I.hasMetadataOtherThanDebugLoc();
4001 if (DILocation *
DL =
I.getDebugLoc()) {
4014 unsigned DLAbbrev = FUNCTION_DEBUG_LOC_ABBREV;
4015 if (DILayerLocList *IRLayers =
DL->getIRLayers()) {
4016 DLAbbrev = FUNCTION_DEBUG_LOC_LAYERS_ABBREV;
4030 if (
I.hasDbgRecords()) {
4034 auto PushValueOrMetadata = [&Vals, InstID,
4037 "RawLocation unexpectedly null in DbgVariableRecord");
4039 SmallVector<unsigned, 2> ValAndType;
4043 if (!pushValueAndType(VAM->getValue(), InstID, ValAndType)) {
4057 for (DbgRecord &DR :
I.getDbgMarker()->getDbgRecordRange()) {
4083 FUNCTION_DEBUG_RECORD_VALUE_ABBREV);
4107 SmallPtrSet<Value *, 8> Visited{BA};
4108 while (!Worklist.
empty()) {
4110 for (User *U :
V->users()) {
4116 Visited.
insert(U).second)
4123 if (!BlockAddressUsers.
empty()) {
4132 if (
auto *Symtab =
F.getValueSymbolTable())
4133 writeFunctionLevelValueSymbolTable(*Symtab);
4135 if (NeedsMetadataAttachment)
4136 writeFunctionMetadataAttachment(
F);
4138 writeUseListBlock(&
F);
4144void ModuleBitcodeWriter::writeBlockInfo() {
4157 auto Abbv = std::make_shared<BitCodeAbbrev>();
4168 auto Abbv = std::make_shared<BitCodeAbbrev>();
4178 auto Abbv = std::make_shared<BitCodeAbbrev>();
4188 auto Abbv = std::make_shared<BitCodeAbbrev>();
4194 VST_BBENTRY_6_ABBREV)
4199 auto Abbv = std::make_shared<BitCodeAbbrev>();
4201 Abbv->Add(TypeAbbrevOp);
4203 CONSTANTS_SETTYPE_ABBREV)
4208 auto Abbv = std::make_shared<BitCodeAbbrev>();
4212 CONSTANTS_INTEGER_ABBREV)
4217 auto Abbv = std::make_shared<BitCodeAbbrev>();
4221 CONSTANTS_BYTE_ABBREV)
4226 auto Abbv = std::make_shared<BitCodeAbbrev>();
4234 CONSTANTS_CE_CAST_Abbrev)
4238 auto Abbv = std::make_shared<BitCodeAbbrev>();
4241 CONSTANTS_NULL_Abbrev)
4248 auto Abbv = std::make_shared<BitCodeAbbrev>();
4250 Abbv->Add(ValAbbrevOp);
4251 Abbv->Add(TypeAbbrevOp);
4255 FUNCTION_INST_LOAD_ABBREV)
4259 auto Abbv = std::make_shared<BitCodeAbbrev>();
4261 Abbv->Add(ValAbbrevOp);
4262 Abbv->Add(ValAbbrevOp);
4266 FUNCTION_INST_STORE_ABBREV)
4270 auto Abbv = std::make_shared<BitCodeAbbrev>();
4272 Abbv->Add(ValAbbrevOp);
4275 FUNCTION_INST_UNOP_ABBREV)
4279 auto Abbv = std::make_shared<BitCodeAbbrev>();
4281 Abbv->Add(ValAbbrevOp);
4285 FUNCTION_INST_UNOP_FLAGS_ABBREV)
4289 auto Abbv = std::make_shared<BitCodeAbbrev>();
4291 Abbv->Add(ValAbbrevOp);
4292 Abbv->Add(ValAbbrevOp);
4295 FUNCTION_INST_BINOP_ABBREV)
4299 auto Abbv = std::make_shared<BitCodeAbbrev>();
4301 Abbv->Add(ValAbbrevOp);
4302 Abbv->Add(ValAbbrevOp);
4306 FUNCTION_INST_BINOP_FLAGS_ABBREV)
4310 auto Abbv = std::make_shared<BitCodeAbbrev>();
4312 Abbv->Add(ValAbbrevOp);
4313 Abbv->Add(TypeAbbrevOp);
4316 FUNCTION_INST_CAST_ABBREV)
4320 auto Abbv = std::make_shared<BitCodeAbbrev>();
4322 Abbv->Add(ValAbbrevOp);
4323 Abbv->Add(TypeAbbrevOp);
4327 FUNCTION_INST_CAST_FLAGS_ABBREV)
4332 auto Abbv = std::make_shared<BitCodeAbbrev>();
4335 FUNCTION_INST_RET_VOID_ABBREV)
4339 auto Abbv = std::make_shared<BitCodeAbbrev>();
4341 Abbv->Add(ValAbbrevOp);
4343 FUNCTION_INST_RET_VAL_ABBREV)
4347 auto Abbv = std::make_shared<BitCodeAbbrev>();
4350 Abbv->Add(ValAbbrevOp);
4352 FUNCTION_INST_BR_UNCOND_ABBREV)
4356 auto Abbv = std::make_shared<BitCodeAbbrev>();
4359 Abbv->Add(ValAbbrevOp);
4360 Abbv->Add(ValAbbrevOp);
4361 Abbv->Add(ValAbbrevOp);
4363 FUNCTION_INST_BR_COND_ABBREV)
4367 auto Abbv = std::make_shared<BitCodeAbbrev>();
4370 FUNCTION_INST_UNREACHABLE_ABBREV)
4374 auto Abbv = std::make_shared<BitCodeAbbrev>();
4377 Abbv->Add(TypeAbbrevOp);
4379 Abbv->Add(ValAbbrevOp);
4381 FUNCTION_INST_GEP_ABBREV)
4385 auto Abbv = std::make_shared<BitCodeAbbrev>();
4387 Abbv->Add(ValAbbrevOp);
4388 Abbv->Add(ValAbbrevOp);
4391 FUNCTION_INST_CMP_ABBREV)
4395 auto Abbv = std::make_shared<BitCodeAbbrev>();
4397 Abbv->Add(ValAbbrevOp);
4398 Abbv->Add(ValAbbrevOp);
4402 FUNCTION_INST_CMP_FLAGS_ABBREV)
4406 auto Abbv = std::make_shared<BitCodeAbbrev>();
4411 Abbv->Add(ValAbbrevOp);
4413 FUNCTION_DEBUG_RECORD_VALUE_ABBREV)
4417 auto Abbv = std::make_shared<BitCodeAbbrev>();
4428 FUNCTION_DEBUG_LOC_ABBREV)
4434 auto Abbv = std::make_shared<BitCodeAbbrev>();
4445 FUNCTION_DEBUG_LOC_LAYERS_ABBREV)
4453void IndexBitcodeWriter::writeModStrings() {
4459 auto Abbv = std::make_shared<BitCodeAbbrev>();
4464 unsigned Abbrev8Bit = Stream.
EmitAbbrev(std::move(Abbv));
4467 Abbv = std::make_shared<BitCodeAbbrev>();
4472 unsigned Abbrev7Bit = Stream.
EmitAbbrev(std::move(Abbv));
4475 Abbv = std::make_shared<BitCodeAbbrev>();
4480 unsigned Abbrev6Bit = Stream.
EmitAbbrev(std::move(Abbv));
4483 Abbv = std::make_shared<BitCodeAbbrev>();
4490 unsigned AbbrevHash = Stream.
EmitAbbrev(std::move(Abbv));
4493 forEachModule([&](
const StringMapEntry<ModuleHash> &MPSE) {
4495 const auto &Hash = MPSE.
getValue();
4497 unsigned AbbrevToUse = Abbrev8Bit;
4499 AbbrevToUse = Abbrev6Bit;
4501 AbbrevToUse = Abbrev7Bit;
4503 auto ModuleId = ModuleIdMap.
size();
4504 ModuleIdMap[
Key] = ModuleId;
4514 Vals.
assign(Hash.begin(), Hash.end());
4526template <
typename Fn>
4530 if (!FS->type_tests().empty())
4535 auto WriteVFuncIdVec = [&](
uint64_t Ty,
4540 for (
auto &VF : VFs) {
4541 Record.push_back(VF.GUID);
4542 Record.push_back(VF.Offset);
4548 FS->type_test_assume_vcalls());
4550 FS->type_checked_load_vcalls());
4552 auto WriteConstVCallVec = [&](
uint64_t Ty,
4554 for (
auto &VC : VCs) {
4556 Record.push_back(VC.VFunc.GUID);
4557 Record.push_back(VC.VFunc.Offset);
4564 FS->type_test_assume_const_vcalls());
4566 FS->type_checked_load_const_vcalls());
4576 if (!FS->paramAccesses().empty()) {
4578 for (
auto &Arg : FS->paramAccesses()) {
4579 size_t UndoSize =
Record.size();
4580 Record.push_back(Arg.ParamNo);
4581 WriteRange(Arg.Use);
4582 Record.push_back(Arg.Calls.size());
4583 for (
auto &
Call : Arg.Calls) {
4585 std::optional<unsigned> ValueID = GetValueID(
Call.Callee);
4592 Record.push_back(*ValueID);
4593 WriteRange(
Call.Offsets);
4604 std::set<GlobalValue::GUID> &ReferencedTypeIds) {
4605 if (!FS->type_tests().empty())
4606 for (
auto &TT : FS->type_tests())
4607 ReferencedTypeIds.insert(TT);
4609 auto GetReferencedTypesFromVFuncIdVec =
4611 for (
auto &VF : VFs)
4612 ReferencedTypeIds.insert(VF.GUID);
4615 GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
4616 GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
4618 auto GetReferencedTypesFromConstVCallVec =
4620 for (
auto &VC : VCs)
4621 ReferencedTypeIds.insert(VC.VFunc.GUID);
4624 GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
4625 GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
4661 NameVals.
push_back(Summary.TTRes.TheKind);
4662 NameVals.
push_back(Summary.TTRes.SizeM1BitWidth);
4663 NameVals.
push_back(Summary.TTRes.AlignLog2);
4664 NameVals.
push_back(Summary.TTRes.SizeM1);
4665 NameVals.
push_back(Summary.TTRes.BitMask);
4666 NameVals.
push_back(Summary.TTRes.InlineBits);
4668 for (
auto &W : Summary.WPDRes)
4680 for (
auto &
P : Summary) {
4682 NameVals.
push_back(
VE.getValueID(
P.VTableVI.getValue()));
4696 static_assert(std::is_same_v<LinearFrameId, unsigned>);
4697 for (
auto &AI : FS->allocs()) {
4698 for (
auto &MIB : AI.MIBs) {
4700 StackIdIndices.
reserve(MIB.StackIdIndices.size());
4701 for (
auto Id : MIB.StackIdIndices)
4702 StackIdIndices.
push_back(GetStackIndex(Id));
4704 CallStacks.insert({CallStacks.size(), StackIdIndices});
4717 assert(!CallStacks.empty());
4723 Builder.
build(std::move(CallStacks),
nullptr,
4727 return Builder.takeCallStackPos();
4732 unsigned AllocAbbrev,
unsigned ContextIdAbbvId,
bool PerModule,
4733 std::function<
unsigned(
const ValueInfo &VI)> GetValueID,
4734 std::function<
unsigned(
unsigned)> GetStackIndex,
4735 bool WriteContextSizeInfoIndex,
4740 for (
auto &CI : FS->callsites()) {
4744 assert(!PerModule || (CI.Clones.size() == 1 && CI.Clones[0] == 0));
4745 Record.push_back(GetValueID(CI.Callee));
4747 Record.push_back(CI.StackIdIndices.size());
4748 Record.push_back(CI.Clones.size());
4750 for (
auto Id : CI.StackIdIndices)
4751 Record.push_back(GetStackIndex(Id));
4759 for (
auto &AI : FS->allocs()) {
4763 assert(!PerModule || (AI.Versions.size() == 1 && AI.Versions[0] == 0));
4764 Record.push_back(AI.MIBs.size());
4766 Record.push_back(AI.Versions.size());
4767 for (
auto &MIB : AI.MIBs) {
4774 assert(CallStackCount <= CallStackPos.
size());
4775 Record.push_back(CallStackPos[CallStackCount++]);
4780 assert(AI.ContextSizeInfos.empty() ||
4781 AI.ContextSizeInfos.size() == AI.MIBs.size());
4783 if (WriteContextSizeInfoIndex && !AI.ContextSizeInfos.empty()) {
4791 ContextIds.
reserve(AI.ContextSizeInfos.size() * 2);
4792 for (
auto &Infos : AI.ContextSizeInfos) {
4793 Record.push_back(Infos.size());
4794 for (
auto [FullStackId, TotalSize] : Infos) {
4801 Record.push_back(TotalSize);
4819void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
4820 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
4821 unsigned ValueID,
unsigned FSCallsProfileAbbrev,
unsigned CallsiteAbbrev,
4822 unsigned AllocAbbrev,
unsigned ContextIdAbbvId,
const Function &
F,
4823 DenseMap<CallStackId, LinearCallStackId> &CallStackPos,
4830 Stream, FS, [&](
const ValueInfo &VI) -> std::optional<unsigned> {
4834 auto SpecialRefCnts =
FS->specialRefCounts();
4839 NameVals.
push_back(SpecialRefCnts.first);
4840 NameVals.
push_back(SpecialRefCnts.second);
4842 for (
auto &RI :
FS->refs())
4845 for (
auto &ECI :
FS->calls()) {
4846 NameVals.
push_back(getValueId(ECI.first));
4855 Stream, FS, CallsiteAbbrev, AllocAbbrev, ContextIdAbbvId,
4857 [&](
const ValueInfo &VI) {
return getValueId(VI); },
4858 [&](
unsigned I) {
return I; },
4859 true, CallStackPos, CallStackCount);
4864void ModuleBitcodeWriterBase::writeModuleLevelReferences(
4865 const GlobalVariable &
V, SmallVector<uint64_t, 64> &NameVals,
4866 unsigned FSModRefsAbbrev,
unsigned FSModVTableRefsAbbrev) {
4871 auto VI =
Index->getValueInfo(GUID);
4872 if (!VI ||
VI.getSummaryList().empty()) {
4878 auto *
Summary =
VI.getSummaryList()[0].get();
4884 auto VTableFuncs =
VS->vTableFuncs();
4885 if (!VTableFuncs.empty())
4888 unsigned SizeBeforeRefs = NameVals.
size();
4889 for (
auto &RI :
VS->refs())
4895 if (VTableFuncs.empty())
4900 for (
auto &
P : VTableFuncs) {
4906 FSModVTableRefsAbbrev);
4913void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
4916 bool IsThinLTO =
true;
4919 IsThinLTO = MD->getZExtValue();
4931 if (
Index->enableSplitLTOUnit())
4933 if (
Index->hasUnifiedLTO())
4943 auto Abbv = std::make_shared<BitCodeAbbrev>();
4949 unsigned ValueGuidAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
4951 for (
const auto &GVI : valueIds()) {
4953 ArrayRef<uint32_t>{GVI.second,
4954 static_cast<uint32_t
>(GVI.first >> 32),
4955 static_cast<uint32_t
>(GVI.first)},
4959 if (!
Index->stackIds().empty()) {
4960 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
4967 unsigned StackIdAbbvId = Stream.
EmitAbbrev(std::move(StackIdAbbv));
4968 SmallVector<uint32_t> Vals;
4970 for (
auto Id :
Index->stackIds()) {
4971 Vals.
push_back(
static_cast<uint32_t
>(Id >> 32));
4972 Vals.
push_back(
static_cast<uint32_t
>(Id));
4977 unsigned ContextIdAbbvId = 0;
4980 auto ContextIdAbbv = std::make_shared<BitCodeAbbrev>();
4992 ContextIdAbbvId = Stream.
EmitAbbrev(std::move(ContextIdAbbv));
4996 Abbv = std::make_shared<BitCodeAbbrev>();
5008 unsigned FSCallsProfileAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5011 Abbv = std::make_shared<BitCodeAbbrev>();
5017 unsigned FSModRefsAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5020 Abbv = std::make_shared<BitCodeAbbrev>();
5028 unsigned FSModVTableRefsAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5031 Abbv = std::make_shared<BitCodeAbbrev>();
5036 unsigned FSAliasAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5039 Abbv = std::make_shared<BitCodeAbbrev>();
5046 unsigned TypeIdCompatibleVtableAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5048 Abbv = std::make_shared<BitCodeAbbrev>();
5054 unsigned CallsiteAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5056 Abbv = std::make_shared<BitCodeAbbrev>();
5063 unsigned AllocAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5065 Abbv = std::make_shared<BitCodeAbbrev>();
5070 unsigned RadixAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5077 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks;
5088 ValueInfo
VI =
Index->getValueInfo(GUID);
5089 if (!VI ||
VI.getSummaryList().empty()) {
5092 if (!
F.isDeclaration())
5094 " to have an associated value info.");
5097 auto *
Summary =
VI.getSummaryList()[0].get();
5100 FS, [](
unsigned I) {
return I; }, CallStacks);
5104 DenseMap<CallStackId, LinearCallStackId> CallStackPos;
5105 if (!CallStacks.
empty()) {
5113 SmallVector<uint64_t, 64> NameVals;
5124 ValueInfo
VI =
Index->getValueInfo(GUID);
5125 if (!VI ||
VI.getSummaryList().empty()) {
5131 auto *
Summary =
VI.getSummaryList()[0].get();
5132 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.
getValueID(&
F),
5133 FSCallsProfileAbbrev, CallsiteAbbrev,
5134 AllocAbbrev, ContextIdAbbvId,
F,
5135 CallStackPos, CallStackCount);
5140 for (
const GlobalVariable &
G :
M.globals())
5141 writeModuleLevelReferences(
G, NameVals, FSModRefsAbbrev,
5142 FSModVTableRefsAbbrev);
5144 for (
const GlobalAlias &
A :
M.aliases()) {
5145 auto *Aliasee =
A.getAliaseeObject();
5161 for (
auto &S :
Index->typeIdCompatibleVtableMap()) {
5165 TypeIdCompatibleVtableAbbrev);
5169 if (
Index->getBlockCount())
5171 ArrayRef<uint64_t>{
Index->getBlockCount()});
5176void ModuleBitcodeWriterBase::writeGUIDList() {
5178 for (
const GlobalValue &GV :
M.global_values()) {
5179 auto MaybeGUID = GV.getGUIDIfAssigned();
5180 if (!MaybeGUID || *MaybeGUID == 0)
5183 if (ValueID >= GUIDs.
size())
5184 GUIDs.
resize(ValueID + 1);
5185 GUIDs[ValueID] = *MaybeGUID;
5188 auto Abbv = std::make_shared<BitCodeAbbrev>();
5192 unsigned GUIDListAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5194 SmallVector<uint32_t> RecordVals;
5196 for (
auto GUID : GUIDs) {
5197 RecordVals.
push_back(
static_cast<uint32_t
>(GUID >> 32));
5198 RecordVals.
push_back(
static_cast<uint32_t
>(GUID));
5205void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
5214 auto Abbv = std::make_shared<BitCodeAbbrev>();
5220 unsigned ValueGuidAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5222 for (
const auto &GVI : valueIds()) {
5224 ArrayRef<uint32_t>{GVI.second,
5225 static_cast<uint32_t
>(GVI.first >> 32),
5226 static_cast<uint32_t
>(GVI.first)},
5232 if (!StackIds.empty()) {
5233 auto StackIdAbbv = std::make_shared<BitCodeAbbrev>();
5240 unsigned StackIdAbbvId = Stream.
EmitAbbrev(std::move(StackIdAbbv));
5241 SmallVector<uint32_t> Vals;
5242 Vals.
reserve(StackIds.size() * 2);
5243 for (
auto Id : StackIds) {
5244 Vals.
push_back(
static_cast<uint32_t
>(Id >> 32));
5245 Vals.
push_back(
static_cast<uint32_t
>(Id));
5251 Abbv = std::make_shared<BitCodeAbbrev>();
5265 unsigned FSCallsProfileAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5268 Abbv = std::make_shared<BitCodeAbbrev>();
5275 unsigned FSModRefsAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5278 Abbv = std::make_shared<BitCodeAbbrev>();
5284 unsigned FSAliasAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5286 Abbv = std::make_shared<BitCodeAbbrev>();
5294 unsigned CallsiteAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5296 Abbv = std::make_shared<BitCodeAbbrev>();
5307 unsigned AllocAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5309 auto shouldImportValueAsDecl = [&](GlobalValueSummary *GVS) ->
bool {
5310 if (DecSummaries ==
nullptr)
5312 return DecSummaries->
count(GVS);
5320 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
5322 SmallVector<uint64_t, 64> NameVals;
5326 std::set<GlobalValue::GUID> ReferencedTypeIds;
5330 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
5340 NameVals.
push_back(S.getOriginalName());
5345 DenseMap<CallStackId, LinearCallStackId> CallStackPos;
5347 Abbv = std::make_shared<BitCodeAbbrev>();
5352 unsigned RadixAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5359 MapVector<CallStackId, llvm::SmallVector<LinearFrameId>> CallStacks;
5360 forEachSummary([&](GVInfo
I,
bool IsAliasee) {
5366 GlobalValueSummary *S =
I.second;
5379 return StackIdIndicesToIndex[
I];
5385 if (!CallStacks.
empty()) {
5395 DenseSet<GlobalValue::GUID> DefOrUseGUIDs;
5396 forEachSummary([&](GVInfo
I,
bool IsAliasee) {
5397 GlobalValueSummary *S =
I.second;
5399 DefOrUseGUIDs.
insert(
I.first);
5400 for (
const ValueInfo &VI : S->
refs())
5401 DefOrUseGUIDs.
insert(
VI.getGUID());
5403 auto ValueId = getValueId(
I.first);
5405 SummaryToValueIdMap[S] = *ValueId;
5423 NameVals.
push_back(ModuleIdMap[
VS->modulePath()]);
5427 for (
auto &RI :
VS->refs()) {
5428 auto RefValueId = getValueId(RI.getGUID());
5438 MaybeEmitOriginalName(*S);
5442 auto GetValueId = [&](
const ValueInfo &
VI) -> std::optional<unsigned> {
5444 return std::nullopt;
5445 return getValueId(
VI.getGUID());
5454 NameVals.
push_back(ModuleIdMap[
FS->modulePath()]);
5467 unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;
5468 for (
auto &RI :
FS->refs()) {
5469 auto RefValueId = getValueId(RI.getGUID());
5473 if (RI.isReadOnly())
5475 else if (RI.isWriteOnly())
5479 NameVals[6] =
Count;
5480 NameVals[7] = RORefCnt;
5481 NameVals[8] = WORefCnt;
5483 for (
auto &EI :
FS->calls()) {
5486 std::optional<unsigned> CallValueId = GetValueId(EI.first);
5495 FSCallsProfileAbbrev);
5499 Stream, FS, CallsiteAbbrev, AllocAbbrev, 0,
5502 [&](
const ValueInfo &VI) ->
unsigned {
5503 std::optional<unsigned> ValueID = GetValueId(VI);
5518 return StackIdIndicesToIndex[
I];
5520 false, CallStackPos, CallStackCount);
5522 MaybeEmitOriginalName(*S);
5525 for (
auto *AS : Aliases) {
5526 auto AliasValueId = SummaryToValueIdMap[AS];
5535 auto AliaseeValueId =
5542 MaybeEmitOriginalName(*AS);
5550 auto EmitCfiFunctions = [&](
const CfiFunctionIndex &CfiIndex,
5552 if (CfiIndex.
empty())
5556 for (StringRef Name : Names)
5559 if (Functions.
empty())
5562 for (
const auto &Record : Functions) {
5577 for (
auto &
T : ReferencedTypeIds) {
5578 auto TidIter =
Index.typeIds().equal_range(
T);
5579 for (
const auto &[GUID, TypeIdPair] :
make_range(TidIter)) {
5587 if (
Index.getBlockCount())
5589 ArrayRef<uint64_t>{
Index.getBlockCount()});
5600 auto Abbv = std::make_shared<BitCodeAbbrev>();
5604 auto StringAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5606 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
5609 Abbv = std::make_shared<BitCodeAbbrev>();
5612 auto EpochAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5618void ModuleBitcodeWriter::writeModuleHash(StringRef View) {
5623 Hasher.
update(ArrayRef<uint8_t>(
5624 reinterpret_cast<const uint8_t *
>(
View.data()),
View.size()));
5625 std::array<uint8_t, 20> Hash = Hasher.
result();
5626 for (
int Pos = 0; Pos < 20; Pos += 4) {
5639void ModuleBitcodeWriter::write() {
5647 writeModuleVersion();
5656 writeAttributeGroupTable();
5659 writeAttributeTable();
5668 writeModuleConstants();
5671 writeModuleMetadataKinds();
5674 writeModuleMetadata();
5678 writeUseListBlock(
nullptr);
5680 writeOperandBundleTags();
5681 writeSyncScopeNames();
5684 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
5686 if (!
F.isDeclaration())
5687 writeFunction(
F, FunctionToBitcodeIndex);
5692 writePerModuleGlobalValueSummary();
5694 writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
5722 unsigned CPUType = ~0U;
5729 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
5730 DARWIN_CPU_TYPE_X86 = 7,
5731 DARWIN_CPU_TYPE_ARM = 12,
5732 DARWIN_CPU_TYPE_POWERPC = 18
5737 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
5739 CPUType = DARWIN_CPU_TYPE_X86;
5741 CPUType = DARWIN_CPU_TYPE_POWERPC;
5743 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
5745 CPUType = DARWIN_CPU_TYPE_ARM;
5749 "Expected header size to be reserved");
5754 unsigned Position = 0;
5762 while (Buffer.
size() & 15)
5769 Stream.
Emit((
unsigned)
'B', 8);
5770 Stream.
Emit((
unsigned)
'C', 8);
5771 Stream.
Emit(0x0, 4);
5772 Stream.
Emit(0xC, 4);
5773 Stream.
Emit(0xE, 4);
5774 Stream.
Emit(0xD, 4);
5792 auto Abbv = std::make_shared<BitCodeAbbrev>();
5795 auto AbbrevNo = Stream->
EmitAbbrev(std::move(Abbv));
5803 assert(!WroteStrtab && !WroteSymtab);
5809 if (M->getModuleInlineAsm().empty())
5813 const Triple TT(M->getTargetTriple());
5815 if (!
T || !
T->hasMCAsmParser())
5837 std::vector<char> Strtab;
5838 StrtabBuilder.finalizeInOrder();
5839 Strtab.resize(StrtabBuilder.getSize());
5840 StrtabBuilder.write((
uint8_t *)Strtab.data());
5843 {Strtab.data(), Strtab.size()});
5854 bool ShouldPreserveUseListOrder,
5863 assert(M.isMaterialized());
5864 Mods.push_back(
const_cast<Module *
>(&M));
5866 ModuleBitcodeWriter ModuleWriter(M, StrtabBuilder, *Stream,
5867 ShouldPreserveUseListOrder, Index,
5868 GenerateHash, ModHash);
5869 ModuleWriter.write();
5876 IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index, DecSummaries,
5877 ModuleToSummariesForIndex);
5878 IndexWriter.write();
5883 bool ShouldPreserveUseListOrder,
5887 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
5889 Writer.writeSymtab();
5890 Writer.writeStrtab();
5892 Triple TT(M.getTargetTriple());
5893 if (TT.isOSDarwin() || TT.isOSBinFormatMachO()) {
5904 Out.write(Buffer.
data(), Buffer.
size());
5912void IndexBitcodeWriter::write() {
5915 writeModuleVersion();
5921 writeCombinedGlobalValueSummary();
5938 Writer.
writeIndex(&Index, ModuleToSummariesForIndex, DecSummaries);
5941 Out.write((
char *)&Buffer.
front(), Buffer.
size());
5947class ThinLinkBitcodeWriter :
public ModuleBitcodeWriterBase {
5957 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
5959 ModHash(&ModHash) {}
5964 void writeSimplifiedModuleInfo();
5974void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
5986 auto Abbv = std::make_shared<BitCodeAbbrev>();
5989 Abbv->Add(AbbrevOpToUse);
5990 unsigned FilenameAbbrev = Stream.
EmitAbbrev(std::move(Abbv));
5992 for (
const auto P :
M.getSourceFileName())
6058void ThinLinkBitcodeWriter::write() {
6061 writeModuleVersion();
6063 writeSimplifiedModuleInfo();
6065 writePerModuleGlobalValueSummary();
6082 assert(M.isMaterialized());
6083 Mods.push_back(
const_cast<Module *
>(&M));
6085 ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
6087 ThinLinkWriter.write();
6104 Out.write((
char *)&Buffer.
front(), Buffer.
size());
6108 switch (
T.getObjectFormat()) {
6110 return "__LLVM,__bitcode";
6135 switch (
T.getObjectFormat()) {
6137 return "__LLVM,__cmdline";
6163 const std::vector<uint8_t> &CmdArgs) {
6168 Type *UsedElementType = Used ? Used->getValueType()->getArrayElementType()
6170 for (
auto *GV : UsedGlobals) {
6171 if (GV->getName() !=
"llvm.embedded.module" &&
6172 GV->getName() !=
"llvm.cmdline")
6177 Used->eraseFromParent();
6182 Triple T(M.getTargetTriple());
6211 M.getGlobalVariable(
"llvm.embedded.module",
true)) {
6212 assert(Old->hasZeroLiveUses() &&
6213 "llvm.embedded.module can only be used once in llvm.compiler.used");
6215 Old->eraseFromParent();
6217 GV->
setName(
"llvm.embedded.module");
6235 assert(Old->hasZeroLiveUses() &&
6236 "llvm.cmdline can only be used once in llvm.compiler.used");
6238 Old->eraseFromParent();
6244 if (UsedArray.
empty())
6252 NewUsed->setSection(
"llvm.metadata");
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void writeDIMacro(raw_ostream &Out, const DIMacro *N, AsmWriterContext &WriterCtx)
static void writeDIGlobalVariableExpression(raw_ostream &Out, const DIGlobalVariableExpression *N, AsmWriterContext &WriterCtx)
static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N, AsmWriterContext &WriterCtx)
static void writeDIFixedPointType(raw_ostream &Out, const DIFixedPointType *N, AsmWriterContext &WriterCtx)
static void writeDISubrangeType(raw_ostream &Out, const DISubrangeType *N, AsmWriterContext &WriterCtx)
static void writeDIStringType(raw_ostream &Out, const DIStringType *N, AsmWriterContext &WriterCtx)
static void writeDILayerLocList(raw_ostream &Out, const DILayerLocList *N, AsmWriterContext &WriterCtx)
static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N, AsmWriterContext &WriterCtx)
static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N, AsmWriterContext &WriterCtx)
static void writeDILayerLoc(raw_ostream &Out, const DILayerLoc *N, AsmWriterContext &WriterCtx)
static void writeDIModule(raw_ostream &Out, const DIModule *N, AsmWriterContext &WriterCtx)
static void writeDIFile(raw_ostream &Out, const DIFile *N, AsmWriterContext &)
static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N, AsmWriterContext &WriterCtx)
static void writeDILabel(raw_ostream &Out, const DILabel *N, AsmWriterContext &WriterCtx)
static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N, AsmWriterContext &WriterCtx)
static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N, AsmWriterContext &WriterCtx)
static void writeMDFunctionLocalContext(raw_ostream &Out, const MDFunctionLocalContext *FLMD, AsmWriterContext &WriterCtx)
static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N, AsmWriterContext &WriterCtx)
static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N, AsmWriterContext &WriterCtx)
static void writeDILocation(raw_ostream &Out, const DILocation *DL, AsmWriterContext &WriterCtx)
static void writeDINamespace(raw_ostream &Out, const DINamespace *N, AsmWriterContext &WriterCtx)
static void writeDICommonBlock(raw_ostream &Out, const DICommonBlock *N, AsmWriterContext &WriterCtx)
static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N, AsmWriterContext &WriterCtx)
static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N, AsmWriterContext &WriterCtx)
static void writeDITemplateTypeParameter(raw_ostream &Out, const DITemplateTypeParameter *N, AsmWriterContext &WriterCtx)
static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N, AsmWriterContext &WriterCtx)
static void writeDIGenericSubrange(raw_ostream &Out, const DIGenericSubrange *N, AsmWriterContext &WriterCtx)
static void writeDISubrange(raw_ostream &Out, const DISubrange *N, AsmWriterContext &WriterCtx)
static void writeDIProperty(raw_ostream &Out, const DIProperty *N, AsmWriterContext &WriterCtx)
static void writeDILexicalBlockFile(raw_ostream &Out, const DILexicalBlockFile *N, AsmWriterContext &WriterCtx)
static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N, AsmWriterContext &)
static void writeMDTuple(raw_ostream &Out, const MDTuple *Node, AsmWriterContext &WriterCtx)
static void writeDIExpression(raw_ostream &Out, const DIExpression *N, AsmWriterContext &WriterCtx)
static void writeDIAssignID(raw_ostream &Out, const DIAssignID *DL, AsmWriterContext &WriterCtx)
static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N, AsmWriterContext &WriterCtx)
static void writeDIArgList(raw_ostream &Out, const DIArgList *N, AsmWriterContext &WriterCtx, bool FromValue=false)
static void writeDITemplateValueParameter(raw_ostream &Out, const DITemplateValueParameter *N, AsmWriterContext &WriterCtx)
static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N, AsmWriterContext &WriterCtx)
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
static void writeFunctionHeapProfileRecords(BitstreamWriter &Stream, FunctionSummary *FS, unsigned CallsiteAbbrev, unsigned AllocAbbrev, unsigned ContextIdAbbvId, bool PerModule, std::function< unsigned(const ValueInfo &VI)> GetValueID, std::function< unsigned(unsigned)> GetStackIndex, bool WriteContextSizeInfoIndex, DenseMap< CallStackId, LinearCallStackId > &CallStackPos, CallStackId &CallStackCount)
static unsigned serializeSanitizerMetadata(const GlobalValue::SanitizerMetadata &Meta)
static void writeTypeIdCompatibleVtableSummaryRecord(SmallVector< uint64_t, 64 > &NameVals, StringTableBuilder &StrtabBuilder, StringRef Id, const TypeIdCompatibleVtableInfo &Summary, ValueEnumerator &VE)
static void getReferencedTypeIds(FunctionSummary *FS, std::set< GlobalValue::GUID > &ReferencedTypeIds)
Collect type IDs from type tests used by function.
static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind)
static void collectMemProfCallStacks(FunctionSummary *FS, std::function< LinearFrameId(unsigned)> GetStackIndex, MapVector< CallStackId, llvm::SmallVector< LinearFrameId > > &CallStacks)
static unsigned getEncodedUnaryOpcode(unsigned Opcode)
static void emitSignedInt64(SmallVectorImpl< uint64_t > &Vals, uint64_t V)
static unsigned getEncodedVisibility(const GlobalValue &GV)
static uint64_t getOptimizationFlags(const Value *V)
static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage)
static unsigned getEncodedThreadLocalMode(const GlobalValue &GV)
static DenseMap< CallStackId, LinearCallStackId > writeMemoryProfileRadixTree(MapVector< CallStackId, llvm::SmallVector< LinearFrameId > > &&CallStacks, BitstreamWriter &Stream, unsigned RadixAbbrev)
static void writeIdentificationBlock(BitstreamWriter &Stream)
Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the current llvm version,...
static unsigned getEncodedCastOpcode(unsigned Opcode)
static unsigned getEncodedOrdering(AtomicOrdering Ordering)
static unsigned getEncodedUnnamedAddr(const GlobalValue &GV)
static unsigned getEncodedComdatSelectionKind(const Comdat &C)
static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags, bool ImportAsDecl=false)
static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl< char > &Buffer, const Triple &TT)
If generating a bc file on darwin, we have to emit a header and trailer to make it compatible with th...
static void writeBitcodeHeader(BitstreamWriter &Stream)
Helper to write the header common to all bitcode files.
static void writeWholeProgramDevirtResolutionByArg(SmallVector< uint64_t, 64 > &NameVals, const std::vector< uint64_t > &args, const WholeProgramDevirtResolution::ByArg &ByArg)
static void emitConstantRange(SmallVectorImpl< uint64_t > &Record, const ConstantRange &CR, bool EmitBitWidth)
static StringEncoding getStringEncoding(StringRef Str)
Determine the encoding to use for the given string name and length.
static uint64_t getEncodedGVarFlags(GlobalVarSummary::GVarFlags Flags)
static const char * getSectionNameForCommandline(const Triple &T)
static void writeTypeIdSummaryRecord(SmallVector< uint64_t, 64 > &NameVals, StringTableBuilder &StrtabBuilder, StringRef Id, const TypeIdSummary &Summary)
static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream, FunctionSummary *FS, Fn GetValueID)
Write the function type metadata related records that need to appear before a function summary entry ...
static uint64_t getEncodedHotnessCallEdgeInfo(const CalleeInfo &CI)
static void emitWideAPInt(SmallVectorImpl< uint64_t > &Vals, const APInt &A)
static void writeStringRecord(BitstreamWriter &Stream, unsigned Code, StringRef Str, unsigned AbbrevToUse)
static unsigned getEncodedRMWOperation(const AtomicRMWInst &I)
static void writeWholeProgramDevirtResolution(SmallVector< uint64_t, 64 > &NameVals, StringTableBuilder &StrtabBuilder, uint64_t Id, const WholeProgramDevirtResolution &Wpd)
static unsigned getEncodedDLLStorageClass(const GlobalValue &GV)
static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl< char > &Buffer, uint32_t &Position)
static const char * getSectionNameForBitcode(const Triple &T)
static cl::opt< bool > CombinedIndexMemProfContext("combined-index-memprof-context", cl::Hidden, cl::init(true), cl::desc(""))
static unsigned getEncodedBinaryOpcode(unsigned Opcode)
static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
static MaybeAlign getAlign(Value *Ptr)
Module.h This file contains the declarations for the Module class.
static cl::opt< LTOBitcodeEmbedding > EmbedBitcode("lto-embed-bitcode", cl::init(LTOBitcodeEmbedding::DoNotEmbed), cl::values(clEnumValN(LTOBitcodeEmbedding::DoNotEmbed, "none", "Do not embed"), clEnumValN(LTOBitcodeEmbedding::EmbedOptimized, "optimized", "Embed after all optimization passes"), clEnumValN(LTOBitcodeEmbedding::EmbedPostMergePreOptimized, "post-merge-pre-opt", "Embed post merge, but before optimizations")), cl::desc("Embed LLVM bitcode in object files produced by LTO"))
if(!TBB||Cond.size()< 1) return false
Machine Check Debug Module
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallString class.
This file defines the SmallVector class.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static const uint32_t IV[8]
Class for arbitrary precision integers.
unsigned getActiveWords() const
Compute the number of active words in the value of this APInt.
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
int64_t getSExtValue() const
Get sign extended value.
const GlobalValueSummary & getAliasee() const
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
bool isUsedWithInAlloca() const
Return true if this alloca is used as an inalloca argument to a call.
unsigned getAddressSpace() const
Return the address space for the allocation.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
bool empty() const
Check if the array is empty.
Class to represent array types.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
an instruction that atomically reads a memory location, combines it with another value,...
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
bool hasAttributes() const
Return true if attributes exists in this set.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
@ None
No attributes have been set.
@ EndAttrKinds
Sentinel value useful for loops.
BitCodeAbbrevOp - This describes one or more operands in an abbreviation.
static bool isChar6(char C)
isChar6 - Return true if this character is legal in the Char6 encoding.
LLVM_ABI void writeThinLinkBitcode(const Module &M, const ModuleSummaryIndex &Index, const ModuleHash &ModHash)
Write the specified thin link bitcode file (i.e., the minimized bitcode file) to the buffer specified...
LLVM_ABI void writeIndex(const ModuleSummaryIndex *Index, const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex, const GVSummaryPtrSet *DecSummaries)
LLVM_ABI void copyStrtab(StringRef Strtab)
Copy the string table for another module into this bitcode file.
LLVM_ABI void writeStrtab()
Write the bitcode file's string table.
LLVM_ABI ~BitcodeWriter()
LLVM_ABI void writeSymtab()
Attempt to write a symbol table to the bitcode file.
LLVM_ABI void writeModule(const Module &M, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false, ModuleHash *ModHash=nullptr)
Write the specified module to the buffer specified at construction time.
LLVM_ABI BitcodeWriter(SmallVectorImpl< char > &Buffer)
Create a BitcodeWriter that writes to Buffer.
unsigned EmitAbbrev(std::shared_ptr< BitCodeAbbrev > Abbv)
Emits the abbreviation Abbv to the stream.
void markAndBlockFlushing()
For scenarios where the user wants to access a section of the stream to (for example) compute some ch...
StringRef getMarkedBufferAndResumeFlushing()
resumes flushing, but does not flush, and returns the section in the internal buffer starting from th...
void EmitRecord(unsigned Code, const Container &Vals, unsigned Abbrev=0)
EmitRecord - Emit the specified record to the stream, using an abbrev if we have one to compress the ...
void Emit(uint32_t Val, unsigned NumBits)
void EmitRecordWithBlob(unsigned Abbrev, const Container &Vals, StringRef Blob)
EmitRecordWithBlob - Emit the specified record to the stream, using an abbrev that includes a blob at...
unsigned EmitBlockInfoAbbrev(unsigned BlockID, std::shared_ptr< BitCodeAbbrev > Abbv)
EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified BlockID.
void EnterBlockInfoBlock()
EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
void BackpatchWord(uint64_t BitNo, unsigned Val)
void BackpatchWord64(uint64_t BitNo, uint64_t Val)
void EnterSubblock(unsigned BlockID, unsigned CodeLen)
uint64_t GetCurrentBitNo() const
Retrieve the current position in the stream, in bits.
void EmitRecordWithAbbrev(unsigned Abbrev, const Container &Vals)
EmitRecordWithAbbrev - Emit a record with the specified abbreviation.
static LLVM_ABI BlockAddress * lookup(const BasicBlock *BB)
Lookup an existing BlockAddress constant for the given BasicBlock.
OperandBundleUse getOperandBundleAt(unsigned Index) const
Return the operand bundle at a specific index.
unsigned getNumOperandBundles() const
Return the number of operand bundles associated with this User.
CallingConv::ID getCallingConv() const
Value * getCalledOperand() const
Value * getArgOperand(unsigned i) const
FunctionType * getFunctionType() const
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
bool hasOperandBundles() const
Return true if this User has any operand bundles.
BasicBlock * getIndirectDest(unsigned i) const
BasicBlock * getDefaultDest() const
unsigned getNumIndirectDests() const
Return the number of callbr indirect dest labels.
bool isNoTailCall() const
bool isMustTailCall() const
auto getNamesForGUID(GlobalValue::GUID GUID) const
get the name(s) associated with a given ThinLTO GUID.
@ Largest
The linker will choose the largest COMDAT.
@ SameSize
The data referenced by the COMDAT must be the same size.
@ Any
The linker may choose any COMDAT.
@ NoDeduplicate
No deduplication is performed.
@ ExactMatch
The data referenced by the COMDAT must be the same.
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
This class represents a range of values.
const APInt & getLower() const
Return the lower value for this range.
const APInt & getUpper() const
Return the upper value for this range.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
This is an important base class in LLVM.
DebugLoc getDebugLoc() const
LLVM_ABI DIAssignID * getAssignID() const
DIExpression * getExpression() const
DILocalVariable * getVariable() const
bool isDbgDeclareValue() const
Metadata * getRawLocation() const
Returns the metadata operand for the first location description.
bool isDbgDeclare() const
Metadata * getRawAddress() const
DIExpression * getAddressExpression() const
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Lightweight error class with error context and mandatory checking.
Function summary information to aid decisions and implementation of importing.
LLVM_ABI void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
Appends all metadata attached to this value to MDs, sorting by KindID.
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
GVFlags flags() const
Get the flags for this GlobalValue (see struct GVFlags).
StringRef modulePath() const
Get the path to the module containing this function.
ArrayRef< ValueInfo > refs() const
Return the list of values referenced by this global value definition.
VisibilityTypes getVisibility() const
static bool isLocalLinkage(LinkageTypes Linkage)
LinkageTypes getLinkage() const
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
ThreadLocalMode getThreadLocalMode() const
@ DLLExportStorageClass
Function to be accessible from DLL.
@ DLLImportStorageClass
Function to be imported from DLL.
@ DefaultVisibility
The GV is visible.
@ HiddenVisibility
The GV is hidden.
@ ProtectedVisibility
The GV is protected.
UnnamedAddr getUnnamedAddr() const
LinkageTypes
An enumeration for the kinds of linkage for global values.
@ PrivateLinkage
Like Internal, but omit from symbol table.
@ CommonLinkage
Tentative definitions.
@ InternalLinkage
Rename collisions when linking (static functions).
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
@ WeakODRLinkage
Same, but only replaced by something equivalent.
@ ExternalLinkage
Externally visible function.
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
@ AppendingLinkage
Special purpose, only applies to global arrays.
@ AvailableExternallyLinkage
Available for inspection, not emission.
@ ExternalWeakLinkage
ExternalWeak linkage description.
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
DLLStorageClassTypes getDLLStorageClass() const
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
idx_iterator idx_end() const
idx_iterator idx_begin() const
bool isCleanup() const
Return 'true' if this landingpad instruction is a cleanup.
unsigned getNumClauses() const
Get the number of clauses for this landing pad.
bool isCatch(unsigned Idx) const
Return 'true' if the clause and index Idx is a catch clause.
Constant * getClause(unsigned Idx) const
Get the value of the clause at index Idx.
This class implements a map that also provides access to all stored values in a deterministic order.
size_t getBufferSize() const
const char * getBufferStart() const
const char * getBufferEnd() const
Class to hold module path string table and global value map, and encapsulate methods for operating on...
static constexpr uint64_t BitcodeSummaryVersion
A Module instance is used to store all the information related to an LLVM module.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Digest more data.
LLVM_ABI std::array< uint8_t, 20 > result()
Return the current raw 160-bits SHA1 for the digested data since the last call to init().
size_type size() const
Determine the number of elements in the SetVector.
bool empty() const
Determine if the SetVector is empty or not.
bool insert(const value_type &X)
Insert a new element into the SetVector.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void append(StringRef RHS)
Append from a StringRef.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
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.
size_t add(CachedHashStringRef S, uint8_t Priority=0)
Add a string to the builder.
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
The instances of the Type class are immutable: once they are created, they are never changed.
bool isX86_FP80Ty() const
Return true if this is x86 long double.
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
bool isFP128Ty() const
Return true if this is 'fp128'.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
std::vector< std::pair< const Value *, unsigned > > ValueList
unsigned getTypeID(Type *T) const
unsigned getMetadataID(const Metadata *MD) const
UseListOrderStack UseListOrders
ArrayRef< const Metadata * > getNonMDStrings() const
Get the non-MDString metadata for this block.
unsigned getInstructionID(const Instruction *I) const
unsigned getAttributeListID(AttributeList PAL) const
void incorporateFunction(const Function &F)
incorporateFunction/purgeFunction - If you'd like to deal with a function, use these two methods to g...
void getFunctionConstantRange(unsigned &Start, unsigned &End) const
getFunctionConstantRange - Return the range of values that corresponds to function-local constants.
unsigned getAttributeGroupID(IndexAndAttrSet Group) const
bool hasMDs() const
Check whether the current block has any metadata to emit.
unsigned getComdatID(const Comdat *C) const
uint64_t computeBitsRequiredForTypeIndices() const
unsigned getValueID(const Value *V) const
unsigned getMetadataOrNullID(const Metadata *MD) const
const std::vector< IndexAndAttrSet > & getAttributeGroups() const
const ValueList & getValues() const
unsigned getGlobalBasicBlockID(const BasicBlock *BB) const
getGlobalBasicBlockID - This returns the function-specific ID for the specified basic block.
void setInstructionID(const Instruction *I)
const std::vector< const BasicBlock * > & getBasicBlocks() const
const std::vector< AttributeList > & getAttributeLists() const
bool shouldPreserveUseListOrder() const
const ComdatSetType & getComdats() const
std::vector< Type * > TypeList
ArrayRef< const Metadata * > getMDStrings() const
Get the MDString metadata for this block.
std::pair< unsigned, AttributeSet > IndexAndAttrSet
Attribute groups as encoded in bitcode are almost AttributeSets, but they include the AttributeList i...
const TypeList & getTypes() const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
LLVMContext & getContext() const
All values hold a context through their type.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
std::pair< iterator, bool > insert(const ValueT &V)
void build(llvm::MapVector< CallStackId, llvm::SmallVector< FrameIdTy > > &&MemProfCallStackData, const llvm::DenseMap< FrameIdTy, LinearFrameId > *MemProfFrameIndexes, llvm::DenseMap< FrameIdTy, FrameStat > &FrameHistogram)
This class implements an extremely fast bulk output stream that can only output to a stream.
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
Predicate getPredicate(unsigned Condition, unsigned Hint)
Return predicate consisting of specified condition and hint bits.
@ CE
Windows NT (Windows on ARM)
@ TYPE_CODE_OPAQUE_POINTER
@ METADATA_TEMPLATE_VALUE
@ METADATA_LEXICAL_BLOCK_FILE
@ METADATA_SUBROUTINE_TYPE
@ METADATA_GLOBAL_DECL_ATTACHMENT
@ METADATA_IMPORTED_ENTITY
@ METADATA_GENERIC_SUBRANGE
@ METADATA_COMPOSITE_TYPE
@ METADATA_FIXED_POINT_TYPE
@ METADATA_GLOBAL_VAR_EXPR
GlobalValueSummarySymtabCodes
@ FS_CONTEXT_RADIX_TREE_ARRAY
@ FS_COMBINED_GLOBALVAR_INIT_REFS
@ FS_TYPE_CHECKED_LOAD_VCALLS
@ FS_COMBINED_ORIGINAL_NAME
@ FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_CONST_VCALL
@ FS_PERMODULE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_VCALLS
@ FS_COMBINED_ALLOC_INFO_NO_CONTEXT
@ FS_COMBINED_CALLSITE_INFO
@ FS_PERMODULE_CALLSITE_INFO
@ FS_PERMODULE_ALLOC_INFO
@ FS_TYPE_CHECKED_LOAD_CONST_VCALL
@ IDENTIFICATION_CODE_EPOCH
@ IDENTIFICATION_CODE_STRING
@ CST_CODE_DSO_LOCAL_EQUIVALENT
@ CST_CODE_CE_GEP_WITH_INRANGE
@ COMDAT_SELECTION_KIND_LARGEST
@ COMDAT_SELECTION_KIND_ANY
@ COMDAT_SELECTION_KIND_SAME_SIZE
@ COMDAT_SELECTION_KIND_EXACT_MATCH
@ COMDAT_SELECTION_KIND_NO_DUPLICATES
@ ATTR_KIND_STACK_PROTECT
@ ATTR_KIND_STACK_PROTECT_STRONG
@ ATTR_KIND_SANITIZE_MEMORY
@ ATTR_KIND_OPTIMIZE_FOR_SIZE
@ ATTR_KIND_FNRETTHUNK_EXTERN
@ ATTR_KIND_NO_DIVERGENCE_SOURCE
@ ATTR_KIND_SANITIZE_ADDRESS
@ ATTR_KIND_NO_IMPLICIT_FLOAT
@ ATTR_KIND_DEAD_ON_UNWIND
@ ATTR_KIND_STACK_ALIGNMENT
@ ATTR_KIND_STACK_PROTECT_REQ
@ ATTR_KIND_NULL_POINTER_IS_VALID
@ ATTR_KIND_SANITIZE_HWADDRESS
@ ATTR_KIND_RETURNS_TWICE
@ ATTR_KIND_SHADOWCALLSTACK
@ ATTR_KIND_OPT_FOR_FUZZING
@ ATTR_KIND_DENORMAL_FPENV
@ ATTR_KIND_SANITIZE_NUMERICAL_STABILITY
@ ATTR_KIND_SANITIZE_CONCURRENCY
@ ATTR_KIND_ALLOCATED_POINTER
@ ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION
@ ATTR_KIND_CORO_ELIDE_SAFE
@ ATTR_KIND_NON_LAZY_BIND
@ ATTR_KIND_DEREFERENCEABLE
@ ATTR_KIND_ALWAYS_UNIFORM
@ ATTR_KIND_LIKELY_MODULE_LOCAL
@ ATTR_KIND_OPTIMIZE_NONE
@ ATTR_KIND_HYBRID_PATCHABLE
@ ATTR_KIND_DEREFERENCEABLE_OR_NULL
@ ATTR_KIND_SANITIZE_REALTIME
@ ATTR_KIND_SPECULATIVE_LOAD_HARDENING
@ ATTR_KIND_ALWAYS_INLINE
@ ATTR_KIND_SANITIZE_TYPE
@ ATTR_KIND_PRESPLIT_COROUTINE
@ ATTR_KIND_SANITIZE_ALLOC_TOKEN
@ ATTR_KIND_NO_SANITIZE_COVERAGE
@ ATTR_KIND_NO_CREATE_UNDEF_OR_POISON
@ ATTR_KIND_DEAD_ON_RETURN
@ ATTR_KIND_SANITIZE_REALTIME_BLOCKING
@ ATTR_KIND_NO_SANITIZE_BOUNDS
@ ATTR_KIND_SANITIZE_MEMTAG
@ ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE
@ ATTR_KIND_SANITIZE_THREAD
@ ATTR_KIND_OPTIMIZE_FOR_DEBUGGING
@ SYNC_SCOPE_NAMES_BLOCK_ID
@ PARAMATTR_GROUP_BLOCK_ID
@ IDENTIFICATION_BLOCK_ID
@ GLOBALVAL_SUMMARY_BLOCK_ID
@ FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID
@ OPERAND_BUNDLE_TAGS_BLOCK_ID
@ MODULE_CODE_SOURCE_FILENAME
@ MODULE_CODE_SECTIONNAME
@ MODULE_CODE_ASM_PROPERTY
@ FUNC_CODE_INST_CATCHRET
@ FUNC_CODE_INST_LANDINGPAD
@ FUNC_CODE_INST_EXTRACTVAL
@ FUNC_CODE_INST_CATCHPAD
@ FUNC_CODE_INST_CATCHSWITCH
@ FUNC_CODE_INST_CLEANUPRET
@ FUNC_CODE_DEBUG_RECORD_VALUE
@ FUNC_CODE_INST_LOADATOMIC
@ FUNC_CODE_DEBUG_RECORD_ASSIGN
@ FUNC_CODE_INST_STOREATOMIC
@ FUNC_CODE_INST_BITEXTRACT
@ FUNC_CODE_INST_ATOMICRMW
@ FUNC_CODE_DEBUG_RECORD_DECLARE_VALUE
@ FUNC_CODE_DEBUG_LOC_AGAIN
@ FUNC_CODE_INST_EXTRACTELT
@ FUNC_CODE_INST_INDIRECTBR
@ FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE
@ FUNC_CODE_INST_INSERTVAL
@ FUNC_CODE_DECLAREBLOCKS
@ FUNC_CODE_DEBUG_RECORD_LABEL
@ FUNC_CODE_INST_INSERTELT
@ FUNC_CODE_BLOCKADDR_USERS
@ FUNC_CODE_INST_CLEANUPPAD
@ FUNC_CODE_INST_SHUFFLEVEC
@ FUNC_CODE_INST_UNREACHABLE
@ FUNC_CODE_INST_BITINSERT
@ FUNC_CODE_DEBUG_RECORD_DECLARE
@ FUNC_CODE_OPERAND_BUNDLE
@ FIRST_APPLICATION_ABBREV
@ PARAMATTR_GRP_CODE_ENTRY
initializer< Ty > init(const Ty &Val)
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
LLVM_ABI Error build(ArrayRef< Module * > Mods, SmallVector< char, 0 > &Symtab, StringTableBuilder &StrtabBuilder, BumpPtrAllocator &Alloc)
Fills in Symtab and StrtabBuilder with a valid symbol and string table for Mods.
Scope
Defines the scope in which this symbol should be visible: Default – Visible in the public interface o...
llvm::unique_function< void(llvm::Expected< T >)> Callback
A Callback<T> is a void function that accepts Expected<T>.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract_or_null(Y &&MD)
Extract a Value from Metadata, allowing null.
LLVM_ABI bool metadataIncludesAllContextSizeInfo()
Whether the alloc memeprof metadata will include context size info for all MIBs.
template LLVM_ABI llvm::DenseMap< LinearFrameId, FrameStat > computeFrameHistogram< LinearFrameId >(llvm::MapVector< CallStackId, llvm::SmallVector< LinearFrameId > > &MemProfCallStackData)
LLVM_ABI bool metadataMayIncludeContextSizeInfo()
Whether the alloc memprof metadata may include context size info for some MIBs (but possibly not all)...
NodeAddr< CodeNode * > Code
void write32le(void *P, uint32_t V)
uint32_t read32be(const void *P)
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
void stable_sort(R &&Range)
StringMapEntry< Value * > ValueName
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
unsigned encode(MaybeAlign A)
Returns a representation of the alignment that encodes undefined as 0.
LLVM_ABI void WriteBitcodeToFile(const Module &M, raw_ostream &Out, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false, ModuleHash *ModHash=nullptr)
Write the specified module to the specified raw output stream.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
LLVM_ABI void writeThinLinkBitcodeToFile(const Module &M, raw_ostream &Out, const ModuleSummaryIndex &Index, const ModuleHash &ModHash)
Write the specified thin link bitcode file (i.e., the minimized bitcode file) to the given raw output...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI void writeIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out, const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex=nullptr, const GVSummaryPtrSet *DecSummaries=nullptr)
Write the specified module summary index to the given raw output stream, where it will be written in ...
LLVM_ABI void embedBitcodeInModule(Module &M, MemoryBufferRef Buf, bool EmbedBitcode, bool EmbedCmdline, const std::vector< uint8_t > &CmdArgs)
If EmbedBitcode is set, save a copy of the llvm IR as data in the __LLVM,__bitcode section (....
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
const BitWriterOptions & getBitWriterOptions(const LLVMContext &C)
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
std::map< std::string, GVSummaryMapTy, std::less<> > ModuleToSummariesForIndexTy
Map of a module name to the GUIDs and summaries we will import from that module.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
AtomicOrdering
Atomic ordering for LLVM's memory model.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt copy(R &&Range, OutputIt Out)
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
constexpr bool valueOr(BoolOrDefault X, bool Default)
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
bool isBitcode(const unsigned char *BufPtr, const unsigned char *BufEnd)
isBitcode - Return true if the given bytes are the magic bytes for LLVM IR bitcode,...
SmallPtrSet< GlobalValueSummary *, 0 > GVSummaryPtrSet
A set of global value summary pointers.
void consumeError(Error Err)
Consume a Error without doing anything.
LLVM_ABI Error write(DWPWriter &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue, Dwarf64StrOffsetsPromotion StrOffsetsOptValue, raw_pwrite_stream *OS=nullptr)
LLVM_ABI GlobalVariable * collectUsedGlobalVariables(const Module &M, SmallVectorImpl< GlobalValue * > &Vec, bool CompilerUsed)
Given "llvm.used" or "llvm.compiler.used" as a global name, collect the initializer elements of that ...
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
This struct is a compact representation of a valid (non-zero power of two) alignment.
static void set(StorageType &Packed, typename Bitfield::Type Value)
Sets the typed value in the provided Packed value.
Class to accumulate and hold information about a callee.
Flags specific to function summaries.
static constexpr uint32_t RangeWidth
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
static LLVM_ABI const Target * lookupTarget(const Triple &TheTriple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
Struct that holds a reference to a particular GUID in a global value summary.
uint64_t Info
Additional information for the resolution:
enum llvm::WholeProgramDevirtResolution::ByArg::Kind TheKind
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
std::string SingleImplName