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(NumBitSetsCreated, "Number of bitsets created");
35 STATISTIC(NumBitSetCallsLowered, "Number of bitset calls lowered");
36 STATISTIC(NumBitSetDisjointSets, "Number of disjoint sets of bitsets");
38 bool BitSetInfo::containsGlobalOffset(uint64_t Offset) const {
39 if (Offset < ByteOffset)
42 if ((Offset - ByteOffset) % (uint64_t(1) << AlignLog2) != 0)
45 uint64_t BitOffset = (Offset - ByteOffset) >> AlignLog2;
46 if (BitOffset >= BitSize)
49 return (Bits[BitOffset / 8] >> (BitOffset % 8)) & 1;
52 bool BitSetInfo::containsValue(
54 const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout, Value *V,
55 uint64_t COffset) const {
56 if (auto GV = dyn_cast<GlobalVariable>(V)) {
57 auto I = GlobalLayout.find(GV);
58 if (I == GlobalLayout.end())
60 return containsGlobalOffset(I->second + COffset);
63 if (auto GEP = dyn_cast<GEPOperator>(V)) {
64 APInt APOffset(DL->getPointerSizeInBits(0), 0);
65 bool Result = GEP->accumulateConstantOffset(*DL, APOffset);
68 COffset += APOffset.getZExtValue();
69 return containsValue(DL, GlobalLayout, GEP->getPointerOperand(),
73 if (auto Op = dyn_cast<Operator>(V)) {
74 if (Op->getOpcode() == Instruction::BitCast)
75 return containsValue(DL, GlobalLayout, Op->getOperand(0), COffset);
77 if (Op->getOpcode() == Instruction::Select)
78 return containsValue(DL, GlobalLayout, Op->getOperand(1), COffset) &&
79 containsValue(DL, GlobalLayout, Op->getOperand(2), COffset);
85 BitSetInfo BitSetBuilder::build() {
89 // Normalize each offset against the minimum observed offset, and compute
90 // the bitwise OR of each of the offsets. The number of trailing zeros
91 // in the mask gives us the log2 of the alignment of all offsets, which
92 // allows us to compress the bitset by only storing one bit per aligned
95 for (uint64_t &Offset : Offsets) {
101 BSI.ByteOffset = Min;
104 // FIXME: Can probably do something smarter if all offsets are 0.
106 BSI.AlignLog2 = countTrailingZeros(Mask, ZB_Undefined);
108 // Build the compressed bitset while normalizing the offsets against the
109 // computed alignment.
110 BSI.BitSize = ((Max - Min) >> BSI.AlignLog2) + 1;
111 uint64_t ByteSize = (BSI.BitSize + 7) / 8;
112 BSI.Bits.resize(ByteSize);
113 for (uint64_t Offset : Offsets) {
114 Offset >>= BSI.AlignLog2;
115 BSI.Bits[Offset / 8] |= 1 << (Offset % 8);
121 void GlobalLayoutBuilder::addFragment(const std::set<uint64_t> &F) {
122 // Create a new fragment to hold the layout for F.
123 Fragments.emplace_back();
124 std::vector<uint64_t> &Fragment = Fragments.back();
125 uint64_t FragmentIndex = Fragments.size() - 1;
127 for (auto ObjIndex : F) {
128 uint64_t OldFragmentIndex = FragmentMap[ObjIndex];
129 if (OldFragmentIndex == 0) {
130 // We haven't seen this object index before, so just add it to the current
132 Fragment.push_back(ObjIndex);
134 // This index belongs to an existing fragment. Copy the elements of the
135 // old fragment into this one and clear the old fragment. We don't update
136 // the fragment map just yet, this ensures that any further references to
137 // indices from the old fragment in this fragment do not insert any more
139 std::vector<uint64_t> &OldFragment = Fragments[OldFragmentIndex];
140 Fragment.insert(Fragment.end(), OldFragment.begin(), OldFragment.end());
145 // Update the fragment map to point our object indices to this fragment.
146 for (uint64_t ObjIndex : Fragment)
147 FragmentMap[ObjIndex] = FragmentIndex;
152 struct LowerBitSets : public ModulePass {
154 LowerBitSets() : ModulePass(ID) {
155 initializeLowerBitSetsPass(*PassRegistry::getPassRegistry());
158 const DataLayout *DL;
161 IntegerType *Int32Ty;
163 IntegerType *Int64Ty;
166 // The llvm.bitsets named metadata.
167 NamedMDNode *BitSetNM;
169 // Mapping from bitset mdstrings to the call sites that test them.
170 DenseMap<MDString *, std::vector<CallInst *>> BitSetTestCallSites;
173 buildBitSet(MDString *BitSet,
174 const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout);
175 Value *createBitSetTest(IRBuilder<> &B, const BitSetInfo &BSI,
176 GlobalVariable *BitSetGlobal, Value *BitOffset);
178 lowerBitSetCall(CallInst *CI, const BitSetInfo &BSI,
179 GlobalVariable *BitSetGlobal, GlobalVariable *CombinedGlobal,
180 const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout);
181 void buildBitSetsFromGlobals(Module &M,
182 const std::vector<MDString *> &BitSets,
183 const std::vector<GlobalVariable *> &Globals);
184 bool buildBitSets(Module &M);
185 bool eraseBitSetMetadata(Module &M);
187 bool doInitialization(Module &M) override;
188 bool runOnModule(Module &M) override;
193 INITIALIZE_PASS_BEGIN(LowerBitSets, "lowerbitsets",
194 "Lower bitset metadata", false, false)
195 INITIALIZE_PASS_END(LowerBitSets, "lowerbitsets",
196 "Lower bitset metadata", false, false)
197 char LowerBitSets::ID = 0;
199 ModulePass *llvm::createLowerBitSetsPass() { return new LowerBitSets; }
201 bool LowerBitSets::doInitialization(Module &M) {
202 DL = M.getDataLayout();
204 report_fatal_error("Data layout required");
206 Int1Ty = Type::getInt1Ty(M.getContext());
207 Int8Ty = Type::getInt8Ty(M.getContext());
208 Int32Ty = Type::getInt32Ty(M.getContext());
209 Int32PtrTy = PointerType::getUnqual(Int32Ty);
210 Int64Ty = Type::getInt64Ty(M.getContext());
211 IntPtrTy = DL->getIntPtrType(M.getContext(), 0);
213 BitSetNM = M.getNamedMetadata("llvm.bitsets");
215 BitSetTestCallSites.clear();
220 /// Build a bit set for BitSet using the object layouts in
222 BitSetInfo LowerBitSets::buildBitSet(
224 const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout) {
227 // Compute the byte offset of each element of this bitset.
229 for (MDNode *Op : BitSetNM->operands()) {
230 if (Op->getOperand(0) != BitSet || !Op->getOperand(1))
232 auto OpGlobal = cast<GlobalVariable>(
233 cast<ConstantAsMetadata>(Op->getOperand(1))->getValue());
235 cast<ConstantInt>(cast<ConstantAsMetadata>(Op->getOperand(2))
236 ->getValue())->getZExtValue();
238 Offset += GlobalLayout.find(OpGlobal)->second;
240 BSB.addOffset(Offset);
247 /// Build a test that bit BitOffset mod sizeof(Bits)*8 is set in
248 /// Bits. This pattern matches to the bt instruction on x86.
249 static Value *createMaskedBitTest(IRBuilder<> &B, Value *Bits,
251 auto BitsType = cast<IntegerType>(Bits->getType());
252 unsigned BitWidth = BitsType->getBitWidth();
254 BitOffset = B.CreateZExtOrTrunc(BitOffset, BitsType);
256 B.CreateAnd(BitOffset, ConstantInt::get(BitsType, BitWidth - 1));
257 Value *BitMask = B.CreateShl(ConstantInt::get(BitsType, 1), BitIndex);
258 Value *MaskedBits = B.CreateAnd(Bits, BitMask);
259 return B.CreateICmpNE(MaskedBits, ConstantInt::get(BitsType, 0));
262 /// Build a test that bit BitOffset is set in BSI, where
263 /// BitSetGlobal is a global containing the bits in BSI.
264 Value *LowerBitSets::createBitSetTest(IRBuilder<> &B, const BitSetInfo &BSI,
265 GlobalVariable *BitSetGlobal,
267 if (BSI.Bits.size() <= 8) {
268 // If the bit set is sufficiently small, we can avoid a load by bit testing
271 if (BSI.Bits.size() <= 4)
277 for (auto I = BSI.Bits.rbegin(), E = BSI.Bits.rend(); I != E; ++I) {
281 Constant *BitsConst = ConstantInt::get(BitsTy, Bits);
282 return createMaskedBitTest(B, BitsConst, BitOffset);
284 // TODO: We might want to use the memory variant of the bt instruction
285 // with the previously computed bit offset at -Os. This instruction does
286 // exactly what we want but has been benchmarked as being slower than open
287 // coding the load+bt.
288 Value *BitSetGlobalOffset =
289 B.CreateLShr(BitOffset, ConstantInt::get(IntPtrTy, 5));
290 Value *BitSetEntryAddr = B.CreateGEP(
291 ConstantExpr::getBitCast(BitSetGlobal, Int32PtrTy), BitSetGlobalOffset);
292 Value *BitSetEntry = B.CreateLoad(BitSetEntryAddr);
294 return createMaskedBitTest(B, BitSetEntry, BitOffset);
298 /// Lower a llvm.bitset.test call to its implementation. Returns the value to
299 /// replace the call with.
300 Value *LowerBitSets::lowerBitSetCall(
301 CallInst *CI, const BitSetInfo &BSI, GlobalVariable *BitSetGlobal,
302 GlobalVariable *CombinedGlobal,
303 const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout) {
304 Value *Ptr = CI->getArgOperand(0);
306 if (BSI.containsValue(DL, GlobalLayout, Ptr))
307 return ConstantInt::getTrue(BitSetGlobal->getParent()->getContext());
309 Constant *GlobalAsInt = ConstantExpr::getPtrToInt(CombinedGlobal, IntPtrTy);
310 Constant *OffsetedGlobalAsInt = ConstantExpr::getAdd(
311 GlobalAsInt, ConstantInt::get(IntPtrTy, BSI.ByteOffset));
313 BasicBlock *InitialBB = CI->getParent();
317 Value *PtrAsInt = B.CreatePtrToInt(Ptr, IntPtrTy);
319 if (BSI.isSingleOffset())
320 return B.CreateICmpEQ(PtrAsInt, OffsetedGlobalAsInt);
322 Value *PtrOffset = B.CreateSub(PtrAsInt, OffsetedGlobalAsInt);
325 if (BSI.AlignLog2 == 0) {
326 BitOffset = PtrOffset;
328 // We need to check that the offset both falls within our range and is
329 // suitably aligned. We can check both properties at the same time by
330 // performing a right rotate by log2(alignment) followed by an integer
331 // comparison against the bitset size. The rotate will move the lower
332 // order bits that need to be zero into the higher order bits of the
333 // result, causing the comparison to fail if they are nonzero. The rotate
334 // also conveniently gives us a bit offset to use during the load from
337 B.CreateLShr(PtrOffset, ConstantInt::get(IntPtrTy, BSI.AlignLog2));
338 Value *OffsetSHL = B.CreateShl(
339 PtrOffset, ConstantInt::get(IntPtrTy, DL->getPointerSizeInBits(0) -
341 BitOffset = B.CreateOr(OffsetSHR, OffsetSHL);
344 Constant *BitSizeConst = ConstantInt::get(IntPtrTy, BSI.BitSize);
345 Value *OffsetInRange = B.CreateICmpULT(BitOffset, BitSizeConst);
347 // If the bit set is all ones, testing against it is unnecessary.
349 return OffsetInRange;
351 TerminatorInst *Term = SplitBlockAndInsertIfThen(OffsetInRange, CI, false);
352 IRBuilder<> ThenB(Term);
354 // Now that we know that the offset is in range and aligned, load the
355 // appropriate bit from the bitset.
356 Value *Bit = createBitSetTest(ThenB, BSI, BitSetGlobal, BitOffset);
358 // The value we want is 0 if we came directly from the initial block
359 // (having failed the range or alignment checks), or the loaded bit if
360 // we came from the block in which we loaded it.
361 B.SetInsertPoint(CI);
362 PHINode *P = B.CreatePHI(Int1Ty, 2);
363 P->addIncoming(ConstantInt::get(Int1Ty, 0), InitialBB);
364 P->addIncoming(Bit, ThenB.GetInsertBlock());
368 /// Given a disjoint set of bitsets and globals, layout the globals, build the
369 /// bit sets and lower the llvm.bitset.test calls.
370 void LowerBitSets::buildBitSetsFromGlobals(
372 const std::vector<MDString *> &BitSets,
373 const std::vector<GlobalVariable *> &Globals) {
374 // Build a new global with the combined contents of the referenced globals.
375 std::vector<Constant *> GlobalInits;
376 for (GlobalVariable *G : Globals) {
377 GlobalInits.push_back(G->getInitializer());
378 uint64_t InitSize = DL->getTypeAllocSize(G->getInitializer()->getType());
380 // Compute the amount of padding required to align the next element to the
382 uint64_t Padding = NextPowerOf2(InitSize - 1) - InitSize;
384 // Cap at 128 was found experimentally to have a good data/instruction
385 // overhead tradeoff.
387 Padding = RoundUpToAlignment(InitSize, 128) - InitSize;
389 GlobalInits.push_back(
390 ConstantAggregateZero::get(ArrayType::get(Int8Ty, Padding)));
392 if (!GlobalInits.empty())
393 GlobalInits.pop_back();
394 Constant *NewInit = ConstantStruct::getAnon(M.getContext(), GlobalInits);
395 auto CombinedGlobal =
396 new GlobalVariable(M, NewInit->getType(), /*isConstant=*/true,
397 GlobalValue::PrivateLinkage, NewInit);
399 const StructLayout *CombinedGlobalLayout =
400 DL->getStructLayout(cast<StructType>(NewInit->getType()));
402 // Compute the offsets of the original globals within the new global.
403 DenseMap<GlobalVariable *, uint64_t> GlobalLayout;
404 for (unsigned I = 0; I != Globals.size(); ++I)
405 // Multiply by 2 to account for padding elements.
406 GlobalLayout[Globals[I]] = CombinedGlobalLayout->getElementOffset(I * 2);
408 // For each bitset in this disjoint set...
409 for (MDString *BS : BitSets) {
411 BitSetInfo BSI = buildBitSet(BS, GlobalLayout);
413 // Create a global in which to store it.
415 Constant *BitsConst = ConstantDataArray::get(M.getContext(), BSI.Bits);
416 auto BitSetGlobal = new GlobalVariable(
417 M, BitsConst->getType(), /*isConstant=*/true,
418 GlobalValue::PrivateLinkage, BitsConst, BS->getString() + ".bits");
420 // Lower each call to llvm.bitset.test for this bitset.
421 for (CallInst *CI : BitSetTestCallSites[BS]) {
422 ++NumBitSetCallsLowered;
424 lowerBitSetCall(CI, BSI, BitSetGlobal, CombinedGlobal, GlobalLayout);
425 CI->replaceAllUsesWith(Lowered);
426 CI->eraseFromParent();
430 // Build aliases pointing to offsets into the combined global for each
431 // global from which we built the combined global, and replace references
432 // to the original globals with references to the aliases.
433 for (unsigned I = 0; I != Globals.size(); ++I) {
434 // Multiply by 2 to account for padding elements.
435 Constant *CombinedGlobalIdxs[] = {ConstantInt::get(Int32Ty, 0),
436 ConstantInt::get(Int32Ty, I * 2)};
437 Constant *CombinedGlobalElemPtr =
438 ConstantExpr::getGetElementPtr(CombinedGlobal, CombinedGlobalIdxs);
439 GlobalAlias *GAlias = GlobalAlias::create(
440 Globals[I]->getType()->getElementType(),
441 Globals[I]->getType()->getAddressSpace(), Globals[I]->getLinkage(),
442 "", CombinedGlobalElemPtr, &M);
443 GAlias->takeName(Globals[I]);
444 Globals[I]->replaceAllUsesWith(GAlias);
445 Globals[I]->eraseFromParent();
449 /// Lower all bit sets in this module.
450 bool LowerBitSets::buildBitSets(Module &M) {
451 Function *BitSetTestFunc =
452 M.getFunction(Intrinsic::getName(Intrinsic::bitset_test));
456 // Equivalence class set containing bitsets and the globals they reference.
457 // This is used to partition the set of bitsets in the module into disjoint
459 typedef EquivalenceClasses<PointerUnion<GlobalVariable *, MDString *>>
461 GlobalClassesTy GlobalClasses;
463 for (const Use &U : BitSetTestFunc->uses()) {
464 auto CI = cast<CallInst>(U.getUser());
466 auto BitSetMDVal = dyn_cast<MetadataAsValue>(CI->getArgOperand(1));
467 if (!BitSetMDVal || !isa<MDString>(BitSetMDVal->getMetadata()))
469 "Second argument of llvm.bitset.test must be metadata string");
470 auto BitSet = cast<MDString>(BitSetMDVal->getMetadata());
472 // Add the call site to the list of call sites for this bit set. We also use
473 // BitSetTestCallSites to keep track of whether we have seen this bit set
474 // before. If we have, we don't need to re-add the referenced globals to the
475 // equivalence class.
476 std::pair<DenseMap<MDString *, std::vector<CallInst *>>::iterator,
478 BitSetTestCallSites.insert(
479 std::make_pair(BitSet, std::vector<CallInst *>()));
480 Ins.first->second.push_back(CI);
484 // Add the bitset to the equivalence class.
485 GlobalClassesTy::iterator GCI = GlobalClasses.insert(BitSet);
486 GlobalClassesTy::member_iterator CurSet = GlobalClasses.findLeader(GCI);
491 // Verify the bitset metadata and add the referenced globals to the bitset's
492 // equivalence class.
493 for (MDNode *Op : BitSetNM->operands()) {
494 if (Op->getNumOperands() != 3)
496 "All operands of llvm.bitsets metadata must have 3 elements");
498 if (Op->getOperand(0) != BitSet || !Op->getOperand(1))
501 auto OpConstMD = dyn_cast<ConstantAsMetadata>(Op->getOperand(1));
503 report_fatal_error("Bit set element must be a constant");
504 auto OpGlobal = dyn_cast<GlobalVariable>(OpConstMD->getValue());
506 report_fatal_error("Bit set element must refer to global");
508 auto OffsetConstMD = dyn_cast<ConstantAsMetadata>(Op->getOperand(2));
510 report_fatal_error("Bit set element offset must be a constant");
511 auto OffsetInt = dyn_cast<ConstantInt>(OffsetConstMD->getValue());
514 "Bit set element offset must be an integer constant");
516 CurSet = GlobalClasses.unionSets(
517 CurSet, GlobalClasses.findLeader(GlobalClasses.insert(OpGlobal)));
521 if (GlobalClasses.empty())
524 // For each disjoint set we found...
525 for (GlobalClassesTy::iterator I = GlobalClasses.begin(),
526 E = GlobalClasses.end();
528 if (!I->isLeader()) continue;
530 ++NumBitSetDisjointSets;
532 // Build the list of bitsets and referenced globals in this disjoint set.
533 std::vector<MDString *> BitSets;
534 std::vector<GlobalVariable *> Globals;
535 llvm::DenseMap<MDString *, uint64_t> BitSetIndices;
536 llvm::DenseMap<GlobalVariable *, uint64_t> GlobalIndices;
537 for (GlobalClassesTy::member_iterator MI = GlobalClasses.member_begin(I);
538 MI != GlobalClasses.member_end(); ++MI) {
539 if ((*MI).is<MDString *>()) {
540 BitSetIndices[MI->get<MDString *>()] = BitSets.size();
541 BitSets.push_back(MI->get<MDString *>());
543 GlobalIndices[MI->get<GlobalVariable *>()] = Globals.size();
544 Globals.push_back(MI->get<GlobalVariable *>());
548 // For each bitset, build a set of indices that refer to globals referenced
550 std::vector<std::set<uint64_t>> BitSetMembers(BitSets.size());
552 for (MDNode *Op : BitSetNM->operands()) {
553 // Op = { bitset name, global, offset }
554 if (!Op->getOperand(1))
556 auto I = BitSetIndices.find(cast<MDString>(Op->getOperand(0)));
557 if (I == BitSetIndices.end())
560 auto OpGlobal = cast<GlobalVariable>(
561 cast<ConstantAsMetadata>(Op->getOperand(1))->getValue());
562 BitSetMembers[I->second].insert(GlobalIndices[OpGlobal]);
566 // Order the sets of indices by size. The GlobalLayoutBuilder works best
567 // when given small index sets first.
569 BitSetMembers.begin(), BitSetMembers.end(),
570 [](const std::set<uint64_t> &O1, const std::set<uint64_t> &O2) {
571 return O1.size() < O2.size();
574 // Create a GlobalLayoutBuilder and provide it with index sets as layout
575 // fragments. The GlobalLayoutBuilder tries to lay out members of fragments
576 // as close together as possible.
577 GlobalLayoutBuilder GLB(Globals.size());
578 for (auto &&MemSet : BitSetMembers)
579 GLB.addFragment(MemSet);
581 // Build a vector of globals with the computed layout.
582 std::vector<GlobalVariable *> OrderedGlobals(Globals.size());
583 auto OGI = OrderedGlobals.begin();
584 for (auto &&F : GLB.Fragments)
585 for (auto &&Offset : F)
586 *OGI++ = Globals[Offset];
588 // Order bitsets by name for determinism.
589 std::sort(BitSets.begin(), BitSets.end(), [](MDString *S1, MDString *S2) {
590 return S1->getString() < S2->getString();
593 // Build the bitsets from this disjoint set.
594 buildBitSetsFromGlobals(M, BitSets, OrderedGlobals);
600 bool LowerBitSets::eraseBitSetMetadata(Module &M) {
604 M.eraseNamedMetadata(BitSetNM);
608 bool LowerBitSets::runOnModule(Module &M) {
609 bool Changed = buildBitSets(M);
610 Changed |= eraseBitSetMetadata(M);