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);
123 struct LowerBitSets : public ModulePass {
125 LowerBitSets() : ModulePass(ID) {
126 initializeLowerBitSetsPass(*PassRegistry::getPassRegistry());
129 const DataLayout *DL;
131 IntegerType *Int32Ty;
133 IntegerType *Int64Ty;
136 // The llvm.bitsets named metadata.
137 NamedMDNode *BitSetNM;
139 // Mapping from bitset mdstrings to the call sites that test them.
140 DenseMap<MDString *, std::vector<CallInst *>> BitSetTestCallSites;
143 buildBitSet(MDString *BitSet,
144 const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout);
145 Value *createBitSetTest(IRBuilder<> &B, const BitSetInfo &BSI,
146 GlobalVariable *BitSetGlobal, Value *BitOffset);
148 lowerBitSetCall(CallInst *CI, const BitSetInfo &BSI,
149 GlobalVariable *BitSetGlobal, GlobalVariable *CombinedGlobal,
150 const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout);
151 void buildBitSetsFromGlobals(Module &M,
152 const std::vector<MDString *> &BitSets,
153 const std::vector<GlobalVariable *> &Globals);
154 bool buildBitSets(Module &M);
155 bool eraseBitSetMetadata(Module &M);
157 bool doInitialization(Module &M) override;
158 bool runOnModule(Module &M) override;
163 INITIALIZE_PASS_BEGIN(LowerBitSets, "lowerbitsets",
164 "Lower bitset metadata", false, false)
165 INITIALIZE_PASS_END(LowerBitSets, "lowerbitsets",
166 "Lower bitset metadata", false, false)
167 char LowerBitSets::ID = 0;
169 ModulePass *llvm::createLowerBitSetsPass() { return new LowerBitSets; }
171 bool LowerBitSets::doInitialization(Module &M) {
172 DL = M.getDataLayout();
174 report_fatal_error("Data layout required");
176 Int1Ty = Type::getInt1Ty(M.getContext());
177 Int32Ty = Type::getInt32Ty(M.getContext());
178 Int32PtrTy = PointerType::getUnqual(Int32Ty);
179 Int64Ty = Type::getInt64Ty(M.getContext());
180 IntPtrTy = DL->getIntPtrType(M.getContext(), 0);
182 BitSetNM = M.getNamedMetadata("llvm.bitsets");
184 BitSetTestCallSites.clear();
189 /// Build a bit set for \param BitSet using the object layouts in
190 /// \param GlobalLayout.
191 BitSetInfo LowerBitSets::buildBitSet(
193 const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout) {
196 // Compute the byte offset of each element of this bitset.
198 for (MDNode *Op : BitSetNM->operands()) {
199 if (Op->getOperand(0) != BitSet || !Op->getOperand(1))
201 auto OpGlobal = cast<GlobalVariable>(
202 cast<ConstantAsMetadata>(Op->getOperand(1))->getValue());
204 cast<ConstantInt>(cast<ConstantAsMetadata>(Op->getOperand(2))
205 ->getValue())->getZExtValue();
207 Offset += GlobalLayout.find(OpGlobal)->second;
209 BSB.addOffset(Offset);
216 /// Build a test that bit \param BitOffset mod sizeof(Bits)*8 is set in
217 /// \param Bits. This pattern matches to the bt instruction on x86.
218 static Value *createMaskedBitTest(IRBuilder<> &B, Value *Bits,
220 auto BitsType = cast<IntegerType>(Bits->getType());
221 unsigned BitWidth = BitsType->getBitWidth();
223 BitOffset = B.CreateZExtOrTrunc(BitOffset, BitsType);
225 B.CreateAnd(BitOffset, ConstantInt::get(BitsType, BitWidth - 1));
226 Value *BitMask = B.CreateShl(ConstantInt::get(BitsType, 1), BitIndex);
227 Value *MaskedBits = B.CreateAnd(Bits, BitMask);
228 return B.CreateICmpNE(MaskedBits, ConstantInt::get(BitsType, 0));
231 /// Build a test that bit \param BitOffset is set in \param BSI, where
232 /// \param BitSetGlobal is a global containing the bits in \param BSI.
233 Value *LowerBitSets::createBitSetTest(IRBuilder<> &B, const BitSetInfo &BSI,
234 GlobalVariable *BitSetGlobal,
236 if (BSI.Bits.size() <= 8) {
237 // If the bit set is sufficiently small, we can avoid a load by bit testing
240 if (BSI.Bits.size() <= 4)
246 for (auto I = BSI.Bits.rbegin(), E = BSI.Bits.rend(); I != E; ++I) {
250 Constant *BitsConst = ConstantInt::get(BitsTy, Bits);
251 return createMaskedBitTest(B, BitsConst, BitOffset);
253 // TODO: We might want to use the memory variant of the bt instruction
254 // with the previously computed bit offset at -Os. This instruction does
255 // exactly what we want but has been benchmarked as being slower than open
256 // coding the load+bt.
257 Value *BitSetGlobalOffset =
258 B.CreateLShr(BitOffset, ConstantInt::get(IntPtrTy, 5));
259 Value *BitSetEntryAddr = B.CreateGEP(
260 ConstantExpr::getBitCast(BitSetGlobal, Int32PtrTy), BitSetGlobalOffset);
261 Value *BitSetEntry = B.CreateLoad(BitSetEntryAddr);
263 return createMaskedBitTest(B, BitSetEntry, BitOffset);
267 /// Lower a llvm.bitset.test call to its implementation.
268 void LowerBitSets::lowerBitSetCall(
269 CallInst *CI, const BitSetInfo &BSI, GlobalVariable *BitSetGlobal,
270 GlobalVariable *CombinedGlobal,
271 const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout) {
272 Value *Ptr = CI->getArgOperand(0);
274 if (BSI.containsValue(DL, GlobalLayout, Ptr)) {
275 CI->replaceAllUsesWith(
276 ConstantInt::getTrue(BitSetGlobal->getParent()->getContext()));
277 CI->eraseFromParent();
281 Constant *GlobalAsInt = ConstantExpr::getPtrToInt(CombinedGlobal, IntPtrTy);
282 Constant *OffsetedGlobalAsInt = ConstantExpr::getAdd(
283 GlobalAsInt, ConstantInt::get(IntPtrTy, BSI.ByteOffset));
285 BasicBlock *InitialBB = CI->getParent();
289 Value *PtrAsInt = B.CreatePtrToInt(Ptr, IntPtrTy);
291 if (BSI.isSingleOffset()) {
292 Value *Eq = B.CreateICmpEQ(PtrAsInt, OffsetedGlobalAsInt);
293 CI->replaceAllUsesWith(Eq);
294 CI->eraseFromParent();
298 Value *PtrOffset = B.CreateSub(PtrAsInt, OffsetedGlobalAsInt);
301 if (BSI.AlignLog2 == 0) {
302 BitOffset = PtrOffset;
304 // We need to check that the offset both falls within our range and is
305 // suitably aligned. We can check both properties at the same time by
306 // performing a right rotate by log2(alignment) followed by an integer
307 // comparison against the bitset size. The rotate will move the lower
308 // order bits that need to be zero into the higher order bits of the
309 // result, causing the comparison to fail if they are nonzero. The rotate
310 // also conveniently gives us a bit offset to use during the load from
313 B.CreateLShr(PtrOffset, ConstantInt::get(IntPtrTy, BSI.AlignLog2));
314 Value *OffsetSHL = B.CreateShl(
315 PtrOffset, ConstantInt::get(IntPtrTy, DL->getPointerSizeInBits(0) -
317 BitOffset = B.CreateOr(OffsetSHR, OffsetSHL);
320 Constant *BitSizeConst = ConstantInt::get(IntPtrTy, BSI.BitSize);
321 Value *OffsetInRange = B.CreateICmpULT(BitOffset, BitSizeConst);
323 TerminatorInst *Term = SplitBlockAndInsertIfThen(OffsetInRange, CI, false);
324 IRBuilder<> ThenB(Term);
326 // Now that we know that the offset is in range and aligned, load the
327 // appropriate bit from the bitset.
328 Value *Bit = createBitSetTest(ThenB, BSI, BitSetGlobal, BitOffset);
330 // The value we want is 0 if we came directly from the initial block
331 // (having failed the range or alignment checks), or the loaded bit if
332 // we came from the block in which we loaded it.
333 B.SetInsertPoint(CI);
334 PHINode *P = B.CreatePHI(Int1Ty, 2);
335 P->addIncoming(ConstantInt::get(Int1Ty, 0), InitialBB);
336 P->addIncoming(Bit, ThenB.GetInsertBlock());
338 CI->replaceAllUsesWith(P);
339 CI->eraseFromParent();
342 /// Given a disjoint set of bitsets and globals, layout the globals, build the
343 /// bit sets and lower the llvm.bitset.test calls.
344 void LowerBitSets::buildBitSetsFromGlobals(
346 const std::vector<MDString *> &BitSets,
347 const std::vector<GlobalVariable *> &Globals) {
348 // Build a new global with the combined contents of the referenced globals.
349 std::vector<Constant *> GlobalInits;
350 for (GlobalVariable *G : Globals)
351 GlobalInits.push_back(G->getInitializer());
352 Constant *NewInit = ConstantStruct::getAnon(M.getContext(), GlobalInits);
353 auto CombinedGlobal =
354 new GlobalVariable(M, NewInit->getType(), /*isConstant=*/true,
355 GlobalValue::PrivateLinkage, NewInit);
357 const StructLayout *CombinedGlobalLayout =
358 DL->getStructLayout(cast<StructType>(NewInit->getType()));
360 // Compute the offsets of the original globals within the new global.
361 DenseMap<GlobalVariable *, uint64_t> GlobalLayout;
362 for (unsigned I = 0; I != Globals.size(); ++I)
363 GlobalLayout[Globals[I]] = CombinedGlobalLayout->getElementOffset(I);
365 // For each bitset in this disjoint set...
366 for (MDString *BS : BitSets) {
368 BitSetInfo BSI = buildBitSet(BS, GlobalLayout);
370 // Create a global in which to store it.
372 Constant *BitsConst = ConstantDataArray::get(M.getContext(), BSI.Bits);
373 auto BitSetGlobal = new GlobalVariable(
374 M, BitsConst->getType(), /*isConstant=*/true,
375 GlobalValue::PrivateLinkage, BitsConst, BS->getString() + ".bits");
377 // Lower each call to llvm.bitset.test for this bitset.
378 for (CallInst *CI : BitSetTestCallSites[BS]) {
379 ++NumBitSetCallsLowered;
380 lowerBitSetCall(CI, BSI, BitSetGlobal, CombinedGlobal, GlobalLayout);
384 // Build aliases pointing to offsets into the combined global for each
385 // global from which we built the combined global, and replace references
386 // to the original globals with references to the aliases.
387 for (unsigned I = 0; I != Globals.size(); ++I) {
388 Constant *CombinedGlobalIdxs[] = {ConstantInt::get(Int32Ty, 0),
389 ConstantInt::get(Int32Ty, I)};
390 Constant *CombinedGlobalElemPtr =
391 ConstantExpr::getGetElementPtr(CombinedGlobal, CombinedGlobalIdxs);
392 GlobalAlias *GAlias = GlobalAlias::create(
393 Globals[I]->getType()->getElementType(),
394 Globals[I]->getType()->getAddressSpace(), Globals[I]->getLinkage(),
395 "", CombinedGlobalElemPtr, &M);
396 GAlias->takeName(Globals[I]);
397 Globals[I]->replaceAllUsesWith(GAlias);
398 Globals[I]->eraseFromParent();
402 /// Lower all bit sets in this module.
403 bool LowerBitSets::buildBitSets(Module &M) {
404 Function *BitSetTestFunc =
405 M.getFunction(Intrinsic::getName(Intrinsic::bitset_test));
409 // Equivalence class set containing bitsets and the globals they reference.
410 // This is used to partition the set of bitsets in the module into disjoint
412 typedef EquivalenceClasses<PointerUnion<GlobalVariable *, MDString *>>
414 GlobalClassesTy GlobalClasses;
416 for (const Use &U : BitSetTestFunc->uses()) {
417 auto CI = cast<CallInst>(U.getUser());
419 auto BitSetMDVal = dyn_cast<MetadataAsValue>(CI->getArgOperand(1));
420 if (!BitSetMDVal || !isa<MDString>(BitSetMDVal->getMetadata()))
422 "Second argument of llvm.bitset.test must be metadata string");
423 auto BitSet = cast<MDString>(BitSetMDVal->getMetadata());
425 // Add the call site to the list of call sites for this bit set. We also use
426 // BitSetTestCallSites to keep track of whether we have seen this bit set
427 // before. If we have, we don't need to re-add the referenced globals to the
428 // equivalence class.
429 std::pair<DenseMap<MDString *, std::vector<CallInst *>>::iterator,
431 BitSetTestCallSites.insert(
432 std::make_pair(BitSet, std::vector<CallInst *>()));
433 Ins.first->second.push_back(CI);
437 // Add the bitset to the equivalence class.
438 GlobalClassesTy::iterator GCI = GlobalClasses.insert(BitSet);
439 GlobalClassesTy::member_iterator CurSet = GlobalClasses.findLeader(GCI);
444 // Verify the bitset metadata and add the referenced globals to the bitset's
445 // equivalence class.
446 for (MDNode *Op : BitSetNM->operands()) {
447 if (Op->getNumOperands() != 3)
449 "All operands of llvm.bitsets metadata must have 3 elements");
451 if (Op->getOperand(0) != BitSet || !Op->getOperand(1))
454 auto OpConstMD = dyn_cast<ConstantAsMetadata>(Op->getOperand(1));
456 report_fatal_error("Bit set element must be a constant");
457 auto OpGlobal = dyn_cast<GlobalVariable>(OpConstMD->getValue());
459 report_fatal_error("Bit set element must refer to global");
461 auto OffsetConstMD = dyn_cast<ConstantAsMetadata>(Op->getOperand(2));
463 report_fatal_error("Bit set element offset must be a constant");
464 auto OffsetInt = dyn_cast<ConstantInt>(OffsetConstMD->getValue());
467 "Bit set element offset must be an integer constant");
469 CurSet = GlobalClasses.unionSets(
470 CurSet, GlobalClasses.findLeader(GlobalClasses.insert(OpGlobal)));
474 if (GlobalClasses.empty())
477 // For each disjoint set we found...
478 for (GlobalClassesTy::iterator I = GlobalClasses.begin(),
479 E = GlobalClasses.end();
481 if (!I->isLeader()) continue;
483 ++NumBitSetDisjointSets;
485 // Build the list of bitsets and referenced globals in this disjoint set.
486 std::vector<MDString *> BitSets;
487 std::vector<GlobalVariable *> Globals;
488 for (GlobalClassesTy::member_iterator MI = GlobalClasses.member_begin(I);
489 MI != GlobalClasses.member_end(); ++MI) {
490 if ((*MI).is<MDString *>())
491 BitSets.push_back(MI->get<MDString *>());
493 Globals.push_back(MI->get<GlobalVariable *>());
496 // Order bitsets and globals by name for determinism. TODO: We may later
497 // want to use a more sophisticated ordering that lays out globals so as to
498 // minimize the sizes of the bitsets.
499 std::sort(BitSets.begin(), BitSets.end(), [](MDString *S1, MDString *S2) {
500 return S1->getString() < S2->getString();
502 std::sort(Globals.begin(), Globals.end(),
503 [](GlobalVariable *GV1, GlobalVariable *GV2) {
504 return GV1->getName() < GV2->getName();
507 // Build the bitsets from this disjoint set.
508 buildBitSetsFromGlobals(M, BitSets, Globals);
514 bool LowerBitSets::eraseBitSetMetadata(Module &M) {
518 M.eraseNamedMetadata(BitSetNM);
522 bool LowerBitSets::runOnModule(Module &M) {
523 bool Changed = buildBitSets(M);
524 Changed |= eraseBitSetMetadata(M);