1 //===-- LowerBitSets.cpp - Bitset lowering pass ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass lowers bitset metadata and calls to the llvm.bitset.test intrinsic.
11 // See http://llvm.org/docs/LangRef.html#bitsets for more information.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Transforms/IPO/LowerBitSets.h"
16 #include "llvm/Transforms/IPO.h"
17 #include "llvm/ADT/EquivalenceClasses.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/IR/Constant.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/GlobalVariable.h"
22 #include "llvm/IR/IRBuilder.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/Intrinsics.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IR/Operator.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
32 #define DEBUG_TYPE "lowerbitsets"
34 STATISTIC(ByteArraySizeBits, "Byte array size in bits");
35 STATISTIC(ByteArraySizeBytes, "Byte array size in bytes");
36 STATISTIC(NumByteArraysCreated, "Number of byte arrays created");
37 STATISTIC(NumBitSetCallsLowered, "Number of bitset calls lowered");
38 STATISTIC(NumBitSetDisjointSets, "Number of disjoint sets of bitsets");
40 bool BitSetInfo::containsGlobalOffset(uint64_t Offset) const {
41 if (Offset < ByteOffset)
44 if ((Offset - ByteOffset) % (uint64_t(1) << AlignLog2) != 0)
47 uint64_t BitOffset = (Offset - ByteOffset) >> AlignLog2;
48 if (BitOffset >= BitSize)
51 return Bits.count(BitOffset);
54 bool BitSetInfo::containsValue(
56 const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout, Value *V,
57 uint64_t COffset) const {
58 if (auto GV = dyn_cast<GlobalVariable>(V)) {
59 auto I = GlobalLayout.find(GV);
60 if (I == GlobalLayout.end())
62 return containsGlobalOffset(I->second + COffset);
65 if (auto GEP = dyn_cast<GEPOperator>(V)) {
66 APInt APOffset(DL->getPointerSizeInBits(0), 0);
67 bool Result = GEP->accumulateConstantOffset(*DL, APOffset);
70 COffset += APOffset.getZExtValue();
71 return containsValue(DL, GlobalLayout, GEP->getPointerOperand(),
75 if (auto Op = dyn_cast<Operator>(V)) {
76 if (Op->getOpcode() == Instruction::BitCast)
77 return containsValue(DL, GlobalLayout, Op->getOperand(0), COffset);
79 if (Op->getOpcode() == Instruction::Select)
80 return containsValue(DL, GlobalLayout, Op->getOperand(1), COffset) &&
81 containsValue(DL, GlobalLayout, Op->getOperand(2), COffset);
87 BitSetInfo BitSetBuilder::build() {
91 // Normalize each offset against the minimum observed offset, and compute
92 // the bitwise OR of each of the offsets. The number of trailing zeros
93 // in the mask gives us the log2 of the alignment of all offsets, which
94 // allows us to compress the bitset by only storing one bit per aligned
97 for (uint64_t &Offset : Offsets) {
103 BSI.ByteOffset = Min;
107 BSI.AlignLog2 = countTrailingZeros(Mask, ZB_Undefined);
109 // Build the compressed bitset while normalizing the offsets against the
110 // computed alignment.
111 BSI.BitSize = ((Max - Min) >> BSI.AlignLog2) + 1;
112 for (uint64_t Offset : Offsets) {
113 Offset >>= BSI.AlignLog2;
114 BSI.Bits.insert(Offset);
120 void GlobalLayoutBuilder::addFragment(const std::set<uint64_t> &F) {
121 // Create a new fragment to hold the layout for F.
122 Fragments.emplace_back();
123 std::vector<uint64_t> &Fragment = Fragments.back();
124 uint64_t FragmentIndex = Fragments.size() - 1;
126 for (auto ObjIndex : F) {
127 uint64_t OldFragmentIndex = FragmentMap[ObjIndex];
128 if (OldFragmentIndex == 0) {
129 // We haven't seen this object index before, so just add it to the current
131 Fragment.push_back(ObjIndex);
133 // This index belongs to an existing fragment. Copy the elements of the
134 // old fragment into this one and clear the old fragment. We don't update
135 // the fragment map just yet, this ensures that any further references to
136 // indices from the old fragment in this fragment do not insert any more
138 std::vector<uint64_t> &OldFragment = Fragments[OldFragmentIndex];
139 Fragment.insert(Fragment.end(), OldFragment.begin(), OldFragment.end());
144 // Update the fragment map to point our object indices to this fragment.
145 for (uint64_t ObjIndex : Fragment)
146 FragmentMap[ObjIndex] = FragmentIndex;
149 void ByteArrayBuilder::allocate(const std::set<uint64_t> &Bits,
150 uint64_t BitSize, uint64_t &AllocByteOffset,
151 uint8_t &AllocMask) {
152 // Find the smallest current allocation.
154 for (unsigned I = 1; I != BitsPerByte; ++I)
155 if (BitAllocs[I] < BitAllocs[Bit])
158 AllocByteOffset = BitAllocs[Bit];
160 // Add our size to it.
161 unsigned ReqSize = AllocByteOffset + BitSize;
162 BitAllocs[Bit] = ReqSize;
163 if (Bytes.size() < ReqSize)
164 Bytes.resize(ReqSize);
167 AllocMask = 1 << Bit;
168 for (uint64_t B : Bits)
169 Bytes[AllocByteOffset + B] |= AllocMask;
174 struct ByteArrayInfo {
175 std::set<uint64_t> Bits;
177 GlobalVariable *ByteArray;
181 struct LowerBitSets : public ModulePass {
183 LowerBitSets() : ModulePass(ID) {
184 initializeLowerBitSetsPass(*PassRegistry::getPassRegistry());
189 const DataLayout *DL;
192 IntegerType *Int32Ty;
194 IntegerType *Int64Ty;
197 // The llvm.bitsets named metadata.
198 NamedMDNode *BitSetNM;
200 // Mapping from bitset mdstrings to the call sites that test them.
201 DenseMap<MDString *, std::vector<CallInst *>> BitSetTestCallSites;
203 std::vector<ByteArrayInfo> ByteArrayInfos;
206 buildBitSet(MDString *BitSet,
207 const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout);
208 ByteArrayInfo *createByteArray(BitSetInfo &BSI);
209 void allocateByteArrays();
210 Value *createBitSetTest(IRBuilder<> &B, BitSetInfo &BSI, ByteArrayInfo *&BAI,
213 lowerBitSetCall(CallInst *CI, BitSetInfo &BSI, ByteArrayInfo *&BAI,
214 GlobalVariable *CombinedGlobal,
215 const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout);
216 void buildBitSetsFromGlobals(const std::vector<MDString *> &BitSets,
217 const std::vector<GlobalVariable *> &Globals);
219 bool eraseBitSetMetadata();
221 bool doInitialization(Module &M) override;
222 bool runOnModule(Module &M) override;
227 INITIALIZE_PASS_BEGIN(LowerBitSets, "lowerbitsets",
228 "Lower bitset metadata", false, false)
229 INITIALIZE_PASS_END(LowerBitSets, "lowerbitsets",
230 "Lower bitset metadata", false, false)
231 char LowerBitSets::ID = 0;
233 ModulePass *llvm::createLowerBitSetsPass() { return new LowerBitSets; }
235 bool LowerBitSets::doInitialization(Module &Mod) {
237 DL = &Mod.getDataLayout();
239 Int1Ty = Type::getInt1Ty(M->getContext());
240 Int8Ty = Type::getInt8Ty(M->getContext());
241 Int32Ty = Type::getInt32Ty(M->getContext());
242 Int32PtrTy = PointerType::getUnqual(Int32Ty);
243 Int64Ty = Type::getInt64Ty(M->getContext());
244 IntPtrTy = DL->getIntPtrType(M->getContext(), 0);
246 BitSetNM = M->getNamedMetadata("llvm.bitsets");
248 BitSetTestCallSites.clear();
253 /// Build a bit set for BitSet using the object layouts in
255 BitSetInfo LowerBitSets::buildBitSet(
257 const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout) {
260 // Compute the byte offset of each element of this bitset.
262 for (MDNode *Op : BitSetNM->operands()) {
263 if (Op->getOperand(0) != BitSet || !Op->getOperand(1))
265 auto OpGlobal = cast<GlobalVariable>(
266 cast<ConstantAsMetadata>(Op->getOperand(1))->getValue());
268 cast<ConstantInt>(cast<ConstantAsMetadata>(Op->getOperand(2))
269 ->getValue())->getZExtValue();
271 Offset += GlobalLayout.find(OpGlobal)->second;
273 BSB.addOffset(Offset);
280 /// Build a test that bit BitOffset mod sizeof(Bits)*8 is set in
281 /// Bits. This pattern matches to the bt instruction on x86.
282 static Value *createMaskedBitTest(IRBuilder<> &B, Value *Bits,
284 auto BitsType = cast<IntegerType>(Bits->getType());
285 unsigned BitWidth = BitsType->getBitWidth();
287 BitOffset = B.CreateZExtOrTrunc(BitOffset, BitsType);
289 B.CreateAnd(BitOffset, ConstantInt::get(BitsType, BitWidth - 1));
290 Value *BitMask = B.CreateShl(ConstantInt::get(BitsType, 1), BitIndex);
291 Value *MaskedBits = B.CreateAnd(Bits, BitMask);
292 return B.CreateICmpNE(MaskedBits, ConstantInt::get(BitsType, 0));
295 ByteArrayInfo *LowerBitSets::createByteArray(BitSetInfo &BSI) {
296 // Create globals to stand in for byte arrays and masks. These never actually
297 // get initialized, we RAUW and erase them later in allocateByteArrays() once
298 // we know the offset and mask to use.
299 auto ByteArrayGlobal = new GlobalVariable(
300 *M, Int8Ty, /*isConstant=*/true, GlobalValue::PrivateLinkage, nullptr);
301 auto MaskGlobal = new GlobalVariable(
302 *M, Int8Ty, /*isConstant=*/true, GlobalValue::PrivateLinkage, nullptr);
304 ByteArrayInfos.emplace_back();
305 ByteArrayInfo *BAI = &ByteArrayInfos.back();
307 BAI->Bits = BSI.Bits;
308 BAI->BitSize = BSI.BitSize;
309 BAI->ByteArray = ByteArrayGlobal;
310 BAI->Mask = ConstantExpr::getPtrToInt(MaskGlobal, Int8Ty);
314 void LowerBitSets::allocateByteArrays() {
315 std::stable_sort(ByteArrayInfos.begin(), ByteArrayInfos.end(),
316 [](const ByteArrayInfo &BAI1, const ByteArrayInfo &BAI2) {
317 return BAI1.BitSize > BAI2.BitSize;
320 std::vector<uint64_t> ByteArrayOffsets(ByteArrayInfos.size());
322 ByteArrayBuilder BAB;
323 for (unsigned I = 0; I != ByteArrayInfos.size(); ++I) {
324 ByteArrayInfo *BAI = &ByteArrayInfos[I];
327 BAB.allocate(BAI->Bits, BAI->BitSize, ByteArrayOffsets[I], Mask);
329 BAI->Mask->replaceAllUsesWith(ConstantInt::get(Int8Ty, Mask));
330 cast<GlobalVariable>(BAI->Mask->getOperand(0))->eraseFromParent();
333 Constant *ByteArrayConst = ConstantDataArray::get(M->getContext(), BAB.Bytes);
335 new GlobalVariable(*M, ByteArrayConst->getType(), /*isConstant=*/true,
336 GlobalValue::PrivateLinkage, ByteArrayConst);
338 for (unsigned I = 0; I != ByteArrayInfos.size(); ++I) {
339 ByteArrayInfo *BAI = &ByteArrayInfos[I];
341 Constant *Idxs[] = {ConstantInt::get(IntPtrTy, 0),
342 ConstantInt::get(IntPtrTy, ByteArrayOffsets[I])};
343 Constant *GEP = ConstantExpr::getInBoundsGetElementPtr(ByteArray, Idxs);
345 // Create an alias instead of RAUW'ing the gep directly. On x86 this ensures
346 // that the pc-relative displacement is folded into the lea instead of the
347 // test instruction getting another displacement.
348 GlobalAlias *Alias = GlobalAlias::create(
349 Int8Ty, 0, GlobalValue::PrivateLinkage, "bits", GEP, M);
350 BAI->ByteArray->replaceAllUsesWith(Alias);
351 BAI->ByteArray->eraseFromParent();
354 ByteArraySizeBits = BAB.BitAllocs[0] + BAB.BitAllocs[1] + BAB.BitAllocs[2] +
355 BAB.BitAllocs[3] + BAB.BitAllocs[4] + BAB.BitAllocs[5] +
356 BAB.BitAllocs[6] + BAB.BitAllocs[7];
357 ByteArraySizeBytes = BAB.Bytes.size();
360 /// Build a test that bit BitOffset is set in BSI, where
361 /// BitSetGlobal is a global containing the bits in BSI.
362 Value *LowerBitSets::createBitSetTest(IRBuilder<> &B, BitSetInfo &BSI,
363 ByteArrayInfo *&BAI, Value *BitOffset) {
364 if (BSI.BitSize <= 64) {
365 // If the bit set is sufficiently small, we can avoid a load by bit testing
368 if (BSI.BitSize <= 32)
374 for (auto Bit : BSI.Bits)
375 Bits |= uint64_t(1) << Bit;
376 Constant *BitsConst = ConstantInt::get(BitsTy, Bits);
377 return createMaskedBitTest(B, BitsConst, BitOffset);
380 ++NumByteArraysCreated;
381 BAI = createByteArray(BSI);
384 Value *ByteAddr = B.CreateGEP(BAI->ByteArray, BitOffset);
385 Value *Byte = B.CreateLoad(ByteAddr);
387 Value *ByteAndMask = B.CreateAnd(Byte, BAI->Mask);
388 return B.CreateICmpNE(ByteAndMask, ConstantInt::get(Int8Ty, 0));
392 /// Lower a llvm.bitset.test call to its implementation. Returns the value to
393 /// replace the call with.
394 Value *LowerBitSets::lowerBitSetCall(
395 CallInst *CI, BitSetInfo &BSI, ByteArrayInfo *&BAI,
396 GlobalVariable *CombinedGlobal,
397 const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout) {
398 Value *Ptr = CI->getArgOperand(0);
400 if (BSI.containsValue(DL, GlobalLayout, Ptr))
401 return ConstantInt::getTrue(CombinedGlobal->getParent()->getContext());
403 Constant *GlobalAsInt = ConstantExpr::getPtrToInt(CombinedGlobal, IntPtrTy);
404 Constant *OffsetedGlobalAsInt = ConstantExpr::getAdd(
405 GlobalAsInt, ConstantInt::get(IntPtrTy, BSI.ByteOffset));
407 BasicBlock *InitialBB = CI->getParent();
411 Value *PtrAsInt = B.CreatePtrToInt(Ptr, IntPtrTy);
413 if (BSI.isSingleOffset())
414 return B.CreateICmpEQ(PtrAsInt, OffsetedGlobalAsInt);
416 Value *PtrOffset = B.CreateSub(PtrAsInt, OffsetedGlobalAsInt);
419 if (BSI.AlignLog2 == 0) {
420 BitOffset = PtrOffset;
422 // We need to check that the offset both falls within our range and is
423 // suitably aligned. We can check both properties at the same time by
424 // performing a right rotate by log2(alignment) followed by an integer
425 // comparison against the bitset size. The rotate will move the lower
426 // order bits that need to be zero into the higher order bits of the
427 // result, causing the comparison to fail if they are nonzero. The rotate
428 // also conveniently gives us a bit offset to use during the load from
431 B.CreateLShr(PtrOffset, ConstantInt::get(IntPtrTy, BSI.AlignLog2));
432 Value *OffsetSHL = B.CreateShl(
433 PtrOffset, ConstantInt::get(IntPtrTy, DL->getPointerSizeInBits(0) -
435 BitOffset = B.CreateOr(OffsetSHR, OffsetSHL);
438 Constant *BitSizeConst = ConstantInt::get(IntPtrTy, BSI.BitSize);
439 Value *OffsetInRange = B.CreateICmpULT(BitOffset, BitSizeConst);
441 // If the bit set is all ones, testing against it is unnecessary.
443 return OffsetInRange;
445 TerminatorInst *Term = SplitBlockAndInsertIfThen(OffsetInRange, CI, false);
446 IRBuilder<> ThenB(Term);
448 // Now that we know that the offset is in range and aligned, load the
449 // appropriate bit from the bitset.
450 Value *Bit = createBitSetTest(ThenB, BSI, BAI, BitOffset);
452 // The value we want is 0 if we came directly from the initial block
453 // (having failed the range or alignment checks), or the loaded bit if
454 // we came from the block in which we loaded it.
455 B.SetInsertPoint(CI);
456 PHINode *P = B.CreatePHI(Int1Ty, 2);
457 P->addIncoming(ConstantInt::get(Int1Ty, 0), InitialBB);
458 P->addIncoming(Bit, ThenB.GetInsertBlock());
462 /// Given a disjoint set of bitsets and globals, layout the globals, build the
463 /// bit sets and lower the llvm.bitset.test calls.
464 void LowerBitSets::buildBitSetsFromGlobals(
465 const std::vector<MDString *> &BitSets,
466 const std::vector<GlobalVariable *> &Globals) {
467 // Build a new global with the combined contents of the referenced globals.
468 std::vector<Constant *> GlobalInits;
469 for (GlobalVariable *G : Globals) {
470 GlobalInits.push_back(G->getInitializer());
471 uint64_t InitSize = DL->getTypeAllocSize(G->getInitializer()->getType());
473 // Compute the amount of padding required to align the next element to the
475 uint64_t Padding = NextPowerOf2(InitSize - 1) - InitSize;
477 // Cap at 128 was found experimentally to have a good data/instruction
478 // overhead tradeoff.
480 Padding = RoundUpToAlignment(InitSize, 128) - InitSize;
482 GlobalInits.push_back(
483 ConstantAggregateZero::get(ArrayType::get(Int8Ty, Padding)));
485 if (!GlobalInits.empty())
486 GlobalInits.pop_back();
487 Constant *NewInit = ConstantStruct::getAnon(M->getContext(), GlobalInits);
488 auto CombinedGlobal =
489 new GlobalVariable(*M, NewInit->getType(), /*isConstant=*/true,
490 GlobalValue::PrivateLinkage, NewInit);
492 const StructLayout *CombinedGlobalLayout =
493 DL->getStructLayout(cast<StructType>(NewInit->getType()));
495 // Compute the offsets of the original globals within the new global.
496 DenseMap<GlobalVariable *, uint64_t> GlobalLayout;
497 for (unsigned I = 0; I != Globals.size(); ++I)
498 // Multiply by 2 to account for padding elements.
499 GlobalLayout[Globals[I]] = CombinedGlobalLayout->getElementOffset(I * 2);
501 // For each bitset in this disjoint set...
502 for (MDString *BS : BitSets) {
504 BitSetInfo BSI = buildBitSet(BS, GlobalLayout);
506 ByteArrayInfo *BAI = 0;
508 // Lower each call to llvm.bitset.test for this bitset.
509 for (CallInst *CI : BitSetTestCallSites[BS]) {
510 ++NumBitSetCallsLowered;
511 Value *Lowered = lowerBitSetCall(CI, BSI, BAI, CombinedGlobal, GlobalLayout);
512 CI->replaceAllUsesWith(Lowered);
513 CI->eraseFromParent();
517 // Build aliases pointing to offsets into the combined global for each
518 // global from which we built the combined global, and replace references
519 // to the original globals with references to the aliases.
520 for (unsigned I = 0; I != Globals.size(); ++I) {
521 // Multiply by 2 to account for padding elements.
522 Constant *CombinedGlobalIdxs[] = {ConstantInt::get(Int32Ty, 0),
523 ConstantInt::get(Int32Ty, I * 2)};
524 Constant *CombinedGlobalElemPtr =
525 ConstantExpr::getGetElementPtr(CombinedGlobal, CombinedGlobalIdxs);
526 GlobalAlias *GAlias = GlobalAlias::create(
527 Globals[I]->getType()->getElementType(),
528 Globals[I]->getType()->getAddressSpace(), Globals[I]->getLinkage(),
529 "", CombinedGlobalElemPtr, M);
530 GAlias->takeName(Globals[I]);
531 Globals[I]->replaceAllUsesWith(GAlias);
532 Globals[I]->eraseFromParent();
536 /// Lower all bit sets in this module.
537 bool LowerBitSets::buildBitSets() {
538 Function *BitSetTestFunc =
539 M->getFunction(Intrinsic::getName(Intrinsic::bitset_test));
543 // Equivalence class set containing bitsets and the globals they reference.
544 // This is used to partition the set of bitsets in the module into disjoint
546 typedef EquivalenceClasses<PointerUnion<GlobalVariable *, MDString *>>
548 GlobalClassesTy GlobalClasses;
550 for (const Use &U : BitSetTestFunc->uses()) {
551 auto CI = cast<CallInst>(U.getUser());
553 auto BitSetMDVal = dyn_cast<MetadataAsValue>(CI->getArgOperand(1));
554 if (!BitSetMDVal || !isa<MDString>(BitSetMDVal->getMetadata()))
556 "Second argument of llvm.bitset.test must be metadata string");
557 auto BitSet = cast<MDString>(BitSetMDVal->getMetadata());
559 // Add the call site to the list of call sites for this bit set. We also use
560 // BitSetTestCallSites to keep track of whether we have seen this bit set
561 // before. If we have, we don't need to re-add the referenced globals to the
562 // equivalence class.
563 std::pair<DenseMap<MDString *, std::vector<CallInst *>>::iterator,
565 BitSetTestCallSites.insert(
566 std::make_pair(BitSet, std::vector<CallInst *>()));
567 Ins.first->second.push_back(CI);
571 // Add the bitset to the equivalence class.
572 GlobalClassesTy::iterator GCI = GlobalClasses.insert(BitSet);
573 GlobalClassesTy::member_iterator CurSet = GlobalClasses.findLeader(GCI);
578 // Verify the bitset metadata and add the referenced globals to the bitset's
579 // equivalence class.
580 for (MDNode *Op : BitSetNM->operands()) {
581 if (Op->getNumOperands() != 3)
583 "All operands of llvm.bitsets metadata must have 3 elements");
585 if (Op->getOperand(0) != BitSet || !Op->getOperand(1))
588 auto OpConstMD = dyn_cast<ConstantAsMetadata>(Op->getOperand(1));
590 report_fatal_error("Bit set element must be a constant");
591 auto OpGlobal = dyn_cast<GlobalVariable>(OpConstMD->getValue());
593 report_fatal_error("Bit set element must refer to global");
595 auto OffsetConstMD = dyn_cast<ConstantAsMetadata>(Op->getOperand(2));
597 report_fatal_error("Bit set element offset must be a constant");
598 auto OffsetInt = dyn_cast<ConstantInt>(OffsetConstMD->getValue());
601 "Bit set element offset must be an integer constant");
603 CurSet = GlobalClasses.unionSets(
604 CurSet, GlobalClasses.findLeader(GlobalClasses.insert(OpGlobal)));
608 if (GlobalClasses.empty())
611 // For each disjoint set we found...
612 for (GlobalClassesTy::iterator I = GlobalClasses.begin(),
613 E = GlobalClasses.end();
615 if (!I->isLeader()) continue;
617 ++NumBitSetDisjointSets;
619 // Build the list of bitsets and referenced globals in this disjoint set.
620 std::vector<MDString *> BitSets;
621 std::vector<GlobalVariable *> Globals;
622 llvm::DenseMap<MDString *, uint64_t> BitSetIndices;
623 llvm::DenseMap<GlobalVariable *, uint64_t> GlobalIndices;
624 for (GlobalClassesTy::member_iterator MI = GlobalClasses.member_begin(I);
625 MI != GlobalClasses.member_end(); ++MI) {
626 if ((*MI).is<MDString *>()) {
627 BitSetIndices[MI->get<MDString *>()] = BitSets.size();
628 BitSets.push_back(MI->get<MDString *>());
630 GlobalIndices[MI->get<GlobalVariable *>()] = Globals.size();
631 Globals.push_back(MI->get<GlobalVariable *>());
635 // For each bitset, build a set of indices that refer to globals referenced
637 std::vector<std::set<uint64_t>> BitSetMembers(BitSets.size());
639 for (MDNode *Op : BitSetNM->operands()) {
640 // Op = { bitset name, global, offset }
641 if (!Op->getOperand(1))
643 auto I = BitSetIndices.find(cast<MDString>(Op->getOperand(0)));
644 if (I == BitSetIndices.end())
647 auto OpGlobal = cast<GlobalVariable>(
648 cast<ConstantAsMetadata>(Op->getOperand(1))->getValue());
649 BitSetMembers[I->second].insert(GlobalIndices[OpGlobal]);
653 // Order the sets of indices by size. The GlobalLayoutBuilder works best
654 // when given small index sets first.
656 BitSetMembers.begin(), BitSetMembers.end(),
657 [](const std::set<uint64_t> &O1, const std::set<uint64_t> &O2) {
658 return O1.size() < O2.size();
661 // Create a GlobalLayoutBuilder and provide it with index sets as layout
662 // fragments. The GlobalLayoutBuilder tries to lay out members of fragments
663 // as close together as possible.
664 GlobalLayoutBuilder GLB(Globals.size());
665 for (auto &&MemSet : BitSetMembers)
666 GLB.addFragment(MemSet);
668 // Build a vector of globals with the computed layout.
669 std::vector<GlobalVariable *> OrderedGlobals(Globals.size());
670 auto OGI = OrderedGlobals.begin();
671 for (auto &&F : GLB.Fragments)
672 for (auto &&Offset : F)
673 *OGI++ = Globals[Offset];
675 // Order bitsets by name for determinism.
676 std::sort(BitSets.begin(), BitSets.end(), [](MDString *S1, MDString *S2) {
677 return S1->getString() < S2->getString();
680 // Build the bitsets from this disjoint set.
681 buildBitSetsFromGlobals(BitSets, OrderedGlobals);
684 allocateByteArrays();
689 bool LowerBitSets::eraseBitSetMetadata() {
693 M->eraseNamedMetadata(BitSetNM);
697 bool LowerBitSets::runOnModule(Module &M) {
698 bool Changed = buildBitSets();
699 Changed |= eraseBitSetMetadata();