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;
160 IntegerType *Int32Ty;
162 IntegerType *Int64Ty;
165 // The llvm.bitsets named metadata.
166 NamedMDNode *BitSetNM;
168 // Mapping from bitset mdstrings to the call sites that test them.
169 DenseMap<MDString *, std::vector<CallInst *>> BitSetTestCallSites;
172 buildBitSet(MDString *BitSet,
173 const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout);
174 Value *createBitSetTest(IRBuilder<> &B, const BitSetInfo &BSI,
175 GlobalVariable *BitSetGlobal, Value *BitOffset);
177 lowerBitSetCall(CallInst *CI, const BitSetInfo &BSI,
178 GlobalVariable *BitSetGlobal, GlobalVariable *CombinedGlobal,
179 const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout);
180 void buildBitSetsFromGlobals(Module &M,
181 const std::vector<MDString *> &BitSets,
182 const std::vector<GlobalVariable *> &Globals);
183 bool buildBitSets(Module &M);
184 bool eraseBitSetMetadata(Module &M);
186 bool doInitialization(Module &M) override;
187 bool runOnModule(Module &M) override;
192 INITIALIZE_PASS_BEGIN(LowerBitSets, "lowerbitsets",
193 "Lower bitset metadata", false, false)
194 INITIALIZE_PASS_END(LowerBitSets, "lowerbitsets",
195 "Lower bitset metadata", false, false)
196 char LowerBitSets::ID = 0;
198 ModulePass *llvm::createLowerBitSetsPass() { return new LowerBitSets; }
200 bool LowerBitSets::doInitialization(Module &M) {
201 DL = M.getDataLayout();
203 report_fatal_error("Data layout required");
205 Int1Ty = Type::getInt1Ty(M.getContext());
206 Int32Ty = Type::getInt32Ty(M.getContext());
207 Int32PtrTy = PointerType::getUnqual(Int32Ty);
208 Int64Ty = Type::getInt64Ty(M.getContext());
209 IntPtrTy = DL->getIntPtrType(M.getContext(), 0);
211 BitSetNM = M.getNamedMetadata("llvm.bitsets");
213 BitSetTestCallSites.clear();
218 /// Build a bit set for BitSet using the object layouts in
220 BitSetInfo LowerBitSets::buildBitSet(
222 const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout) {
225 // Compute the byte offset of each element of this bitset.
227 for (MDNode *Op : BitSetNM->operands()) {
228 if (Op->getOperand(0) != BitSet || !Op->getOperand(1))
230 auto OpGlobal = cast<GlobalVariable>(
231 cast<ConstantAsMetadata>(Op->getOperand(1))->getValue());
233 cast<ConstantInt>(cast<ConstantAsMetadata>(Op->getOperand(2))
234 ->getValue())->getZExtValue();
236 Offset += GlobalLayout.find(OpGlobal)->second;
238 BSB.addOffset(Offset);
245 /// Build a test that bit BitOffset mod sizeof(Bits)*8 is set in
246 /// Bits. This pattern matches to the bt instruction on x86.
247 static Value *createMaskedBitTest(IRBuilder<> &B, Value *Bits,
249 auto BitsType = cast<IntegerType>(Bits->getType());
250 unsigned BitWidth = BitsType->getBitWidth();
252 BitOffset = B.CreateZExtOrTrunc(BitOffset, BitsType);
254 B.CreateAnd(BitOffset, ConstantInt::get(BitsType, BitWidth - 1));
255 Value *BitMask = B.CreateShl(ConstantInt::get(BitsType, 1), BitIndex);
256 Value *MaskedBits = B.CreateAnd(Bits, BitMask);
257 return B.CreateICmpNE(MaskedBits, ConstantInt::get(BitsType, 0));
260 /// Build a test that bit BitOffset is set in BSI, where
261 /// BitSetGlobal is a global containing the bits in BSI.
262 Value *LowerBitSets::createBitSetTest(IRBuilder<> &B, const BitSetInfo &BSI,
263 GlobalVariable *BitSetGlobal,
265 if (BSI.Bits.size() <= 8) {
266 // If the bit set is sufficiently small, we can avoid a load by bit testing
269 if (BSI.Bits.size() <= 4)
275 for (auto I = BSI.Bits.rbegin(), E = BSI.Bits.rend(); I != E; ++I) {
279 Constant *BitsConst = ConstantInt::get(BitsTy, Bits);
280 return createMaskedBitTest(B, BitsConst, BitOffset);
282 // TODO: We might want to use the memory variant of the bt instruction
283 // with the previously computed bit offset at -Os. This instruction does
284 // exactly what we want but has been benchmarked as being slower than open
285 // coding the load+bt.
286 Value *BitSetGlobalOffset =
287 B.CreateLShr(BitOffset, ConstantInt::get(IntPtrTy, 5));
288 Value *BitSetEntryAddr = B.CreateGEP(
289 ConstantExpr::getBitCast(BitSetGlobal, Int32PtrTy), BitSetGlobalOffset);
290 Value *BitSetEntry = B.CreateLoad(BitSetEntryAddr);
292 return createMaskedBitTest(B, BitSetEntry, BitOffset);
296 /// Lower a llvm.bitset.test call to its implementation.
297 void LowerBitSets::lowerBitSetCall(
298 CallInst *CI, const BitSetInfo &BSI, GlobalVariable *BitSetGlobal,
299 GlobalVariable *CombinedGlobal,
300 const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout) {
301 Value *Ptr = CI->getArgOperand(0);
303 if (BSI.containsValue(DL, GlobalLayout, Ptr)) {
304 CI->replaceAllUsesWith(
305 ConstantInt::getTrue(BitSetGlobal->getParent()->getContext()));
306 CI->eraseFromParent();
310 Constant *GlobalAsInt = ConstantExpr::getPtrToInt(CombinedGlobal, IntPtrTy);
311 Constant *OffsetedGlobalAsInt = ConstantExpr::getAdd(
312 GlobalAsInt, ConstantInt::get(IntPtrTy, BSI.ByteOffset));
314 BasicBlock *InitialBB = CI->getParent();
318 Value *PtrAsInt = B.CreatePtrToInt(Ptr, IntPtrTy);
320 if (BSI.isSingleOffset()) {
321 Value *Eq = B.CreateICmpEQ(PtrAsInt, OffsetedGlobalAsInt);
322 CI->replaceAllUsesWith(Eq);
323 CI->eraseFromParent();
327 Value *PtrOffset = B.CreateSub(PtrAsInt, OffsetedGlobalAsInt);
330 if (BSI.AlignLog2 == 0) {
331 BitOffset = PtrOffset;
333 // We need to check that the offset both falls within our range and is
334 // suitably aligned. We can check both properties at the same time by
335 // performing a right rotate by log2(alignment) followed by an integer
336 // comparison against the bitset size. The rotate will move the lower
337 // order bits that need to be zero into the higher order bits of the
338 // result, causing the comparison to fail if they are nonzero. The rotate
339 // also conveniently gives us a bit offset to use during the load from
342 B.CreateLShr(PtrOffset, ConstantInt::get(IntPtrTy, BSI.AlignLog2));
343 Value *OffsetSHL = B.CreateShl(
344 PtrOffset, ConstantInt::get(IntPtrTy, DL->getPointerSizeInBits(0) -
346 BitOffset = B.CreateOr(OffsetSHR, OffsetSHL);
349 Constant *BitSizeConst = ConstantInt::get(IntPtrTy, BSI.BitSize);
350 Value *OffsetInRange = B.CreateICmpULT(BitOffset, BitSizeConst);
352 TerminatorInst *Term = SplitBlockAndInsertIfThen(OffsetInRange, CI, false);
353 IRBuilder<> ThenB(Term);
355 // Now that we know that the offset is in range and aligned, load the
356 // appropriate bit from the bitset.
357 Value *Bit = createBitSetTest(ThenB, BSI, BitSetGlobal, BitOffset);
359 // The value we want is 0 if we came directly from the initial block
360 // (having failed the range or alignment checks), or the loaded bit if
361 // we came from the block in which we loaded it.
362 B.SetInsertPoint(CI);
363 PHINode *P = B.CreatePHI(Int1Ty, 2);
364 P->addIncoming(ConstantInt::get(Int1Ty, 0), InitialBB);
365 P->addIncoming(Bit, ThenB.GetInsertBlock());
367 CI->replaceAllUsesWith(P);
368 CI->eraseFromParent();
371 /// Given a disjoint set of bitsets and globals, layout the globals, build the
372 /// bit sets and lower the llvm.bitset.test calls.
373 void LowerBitSets::buildBitSetsFromGlobals(
375 const std::vector<MDString *> &BitSets,
376 const std::vector<GlobalVariable *> &Globals) {
377 // Build a new global with the combined contents of the referenced globals.
378 std::vector<Constant *> GlobalInits;
379 for (GlobalVariable *G : Globals)
380 GlobalInits.push_back(G->getInitializer());
381 Constant *NewInit = ConstantStruct::getAnon(M.getContext(), GlobalInits);
382 auto CombinedGlobal =
383 new GlobalVariable(M, NewInit->getType(), /*isConstant=*/true,
384 GlobalValue::PrivateLinkage, NewInit);
386 const StructLayout *CombinedGlobalLayout =
387 DL->getStructLayout(cast<StructType>(NewInit->getType()));
389 // Compute the offsets of the original globals within the new global.
390 DenseMap<GlobalVariable *, uint64_t> GlobalLayout;
391 for (unsigned I = 0; I != Globals.size(); ++I)
392 GlobalLayout[Globals[I]] = CombinedGlobalLayout->getElementOffset(I);
394 // For each bitset in this disjoint set...
395 for (MDString *BS : BitSets) {
397 BitSetInfo BSI = buildBitSet(BS, GlobalLayout);
399 // Create a global in which to store it.
401 Constant *BitsConst = ConstantDataArray::get(M.getContext(), BSI.Bits);
402 auto BitSetGlobal = new GlobalVariable(
403 M, BitsConst->getType(), /*isConstant=*/true,
404 GlobalValue::PrivateLinkage, BitsConst, BS->getString() + ".bits");
406 // Lower each call to llvm.bitset.test for this bitset.
407 for (CallInst *CI : BitSetTestCallSites[BS]) {
408 ++NumBitSetCallsLowered;
409 lowerBitSetCall(CI, BSI, BitSetGlobal, CombinedGlobal, GlobalLayout);
413 // Build aliases pointing to offsets into the combined global for each
414 // global from which we built the combined global, and replace references
415 // to the original globals with references to the aliases.
416 for (unsigned I = 0; I != Globals.size(); ++I) {
417 Constant *CombinedGlobalIdxs[] = {ConstantInt::get(Int32Ty, 0),
418 ConstantInt::get(Int32Ty, I)};
419 Constant *CombinedGlobalElemPtr =
420 ConstantExpr::getGetElementPtr(CombinedGlobal, CombinedGlobalIdxs);
421 GlobalAlias *GAlias = GlobalAlias::create(
422 Globals[I]->getType()->getElementType(),
423 Globals[I]->getType()->getAddressSpace(), Globals[I]->getLinkage(),
424 "", CombinedGlobalElemPtr, &M);
425 GAlias->takeName(Globals[I]);
426 Globals[I]->replaceAllUsesWith(GAlias);
427 Globals[I]->eraseFromParent();
431 /// Lower all bit sets in this module.
432 bool LowerBitSets::buildBitSets(Module &M) {
433 Function *BitSetTestFunc =
434 M.getFunction(Intrinsic::getName(Intrinsic::bitset_test));
438 // Equivalence class set containing bitsets and the globals they reference.
439 // This is used to partition the set of bitsets in the module into disjoint
441 typedef EquivalenceClasses<PointerUnion<GlobalVariable *, MDString *>>
443 GlobalClassesTy GlobalClasses;
445 for (const Use &U : BitSetTestFunc->uses()) {
446 auto CI = cast<CallInst>(U.getUser());
448 auto BitSetMDVal = dyn_cast<MetadataAsValue>(CI->getArgOperand(1));
449 if (!BitSetMDVal || !isa<MDString>(BitSetMDVal->getMetadata()))
451 "Second argument of llvm.bitset.test must be metadata string");
452 auto BitSet = cast<MDString>(BitSetMDVal->getMetadata());
454 // Add the call site to the list of call sites for this bit set. We also use
455 // BitSetTestCallSites to keep track of whether we have seen this bit set
456 // before. If we have, we don't need to re-add the referenced globals to the
457 // equivalence class.
458 std::pair<DenseMap<MDString *, std::vector<CallInst *>>::iterator,
460 BitSetTestCallSites.insert(
461 std::make_pair(BitSet, std::vector<CallInst *>()));
462 Ins.first->second.push_back(CI);
466 // Add the bitset to the equivalence class.
467 GlobalClassesTy::iterator GCI = GlobalClasses.insert(BitSet);
468 GlobalClassesTy::member_iterator CurSet = GlobalClasses.findLeader(GCI);
473 // Verify the bitset metadata and add the referenced globals to the bitset's
474 // equivalence class.
475 for (MDNode *Op : BitSetNM->operands()) {
476 if (Op->getNumOperands() != 3)
478 "All operands of llvm.bitsets metadata must have 3 elements");
480 if (Op->getOperand(0) != BitSet || !Op->getOperand(1))
483 auto OpConstMD = dyn_cast<ConstantAsMetadata>(Op->getOperand(1));
485 report_fatal_error("Bit set element must be a constant");
486 auto OpGlobal = dyn_cast<GlobalVariable>(OpConstMD->getValue());
488 report_fatal_error("Bit set element must refer to global");
490 auto OffsetConstMD = dyn_cast<ConstantAsMetadata>(Op->getOperand(2));
492 report_fatal_error("Bit set element offset must be a constant");
493 auto OffsetInt = dyn_cast<ConstantInt>(OffsetConstMD->getValue());
496 "Bit set element offset must be an integer constant");
498 CurSet = GlobalClasses.unionSets(
499 CurSet, GlobalClasses.findLeader(GlobalClasses.insert(OpGlobal)));
503 if (GlobalClasses.empty())
506 // For each disjoint set we found...
507 for (GlobalClassesTy::iterator I = GlobalClasses.begin(),
508 E = GlobalClasses.end();
510 if (!I->isLeader()) continue;
512 ++NumBitSetDisjointSets;
514 // Build the list of bitsets and referenced globals in this disjoint set.
515 std::vector<MDString *> BitSets;
516 std::vector<GlobalVariable *> Globals;
517 llvm::DenseMap<MDString *, uint64_t> BitSetIndices;
518 llvm::DenseMap<GlobalVariable *, uint64_t> GlobalIndices;
519 for (GlobalClassesTy::member_iterator MI = GlobalClasses.member_begin(I);
520 MI != GlobalClasses.member_end(); ++MI) {
521 if ((*MI).is<MDString *>()) {
522 BitSetIndices[MI->get<MDString *>()] = BitSets.size();
523 BitSets.push_back(MI->get<MDString *>());
525 GlobalIndices[MI->get<GlobalVariable *>()] = Globals.size();
526 Globals.push_back(MI->get<GlobalVariable *>());
530 // For each bitset, build a set of indices that refer to globals referenced
532 std::vector<std::set<uint64_t>> BitSetMembers(BitSets.size());
534 for (MDNode *Op : BitSetNM->operands()) {
535 // Op = { bitset name, global, offset }
536 if (!Op->getOperand(1))
538 auto I = BitSetIndices.find(cast<MDString>(Op->getOperand(0)));
539 if (I == BitSetIndices.end())
542 auto OpGlobal = cast<GlobalVariable>(
543 cast<ConstantAsMetadata>(Op->getOperand(1))->getValue());
544 BitSetMembers[I->second].insert(GlobalIndices[OpGlobal]);
548 // Order the sets of indices by size. The GlobalLayoutBuilder works best
549 // when given small index sets first.
551 BitSetMembers.begin(), BitSetMembers.end(),
552 [](const std::set<uint64_t> &O1, const std::set<uint64_t> &O2) {
553 return O1.size() < O2.size();
556 // Create a GlobalLayoutBuilder and provide it with index sets as layout
557 // fragments. The GlobalLayoutBuilder tries to lay out members of fragments
558 // as close together as possible.
559 GlobalLayoutBuilder GLB(Globals.size());
560 for (auto &&MemSet : BitSetMembers)
561 GLB.addFragment(MemSet);
563 // Build a vector of globals with the computed layout.
564 std::vector<GlobalVariable *> OrderedGlobals(Globals.size());
565 auto OGI = OrderedGlobals.begin();
566 for (auto &&F : GLB.Fragments)
567 for (auto &&Offset : F)
568 *OGI++ = Globals[Offset];
570 // Order bitsets by name for determinism.
571 std::sort(BitSets.begin(), BitSets.end(), [](MDString *S1, MDString *S2) {
572 return S1->getString() < S2->getString();
575 // Build the bitsets from this disjoint set.
576 buildBitSetsFromGlobals(M, BitSets, OrderedGlobals);
582 bool LowerBitSets::eraseBitSetMetadata(Module &M) {
586 M.eraseNamedMetadata(BitSetNM);
590 bool LowerBitSets::runOnModule(Module &M) {
591 bool Changed = buildBitSets(M);
592 Changed |= eraseBitSetMetadata(M);