blob: 3be7dd504d938712f73b374c406ea29800cae019 [file] [log] [blame]
Peter Collingbournee6909c82015-02-20 20:30:47 +00001//===-- LowerBitSets.cpp - Bitset lowering pass ---------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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.
12//
13//===----------------------------------------------------------------------===//
14
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"
29
30using namespace llvm;
31
32#define DEBUG_TYPE "lowerbitsets"
33
34STATISTIC(NumBitSetsCreated, "Number of bitsets created");
35STATISTIC(NumBitSetCallsLowered, "Number of bitset calls lowered");
36STATISTIC(NumBitSetDisjointSets, "Number of disjoint sets of bitsets");
37
38bool BitSetInfo::containsGlobalOffset(uint64_t Offset) const {
39 if (Offset < ByteOffset)
40 return false;
41
42 if ((Offset - ByteOffset) % (uint64_t(1) << AlignLog2) != 0)
43 return false;
44
45 uint64_t BitOffset = (Offset - ByteOffset) >> AlignLog2;
46 if (BitOffset >= BitSize)
47 return false;
48
49 return (Bits[BitOffset / 8] >> (BitOffset % 8)) & 1;
50}
51
52bool BitSetInfo::containsValue(
53 const DataLayout *DL,
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())
59 return false;
60 return containsGlobalOffset(I->second + COffset);
61 }
62
63 if (auto GEP = dyn_cast<GEPOperator>(V)) {
64 APInt APOffset(DL->getPointerSizeInBits(0), 0);
65 bool Result = GEP->accumulateConstantOffset(*DL, APOffset);
66 if (!Result)
67 return false;
68 COffset += APOffset.getZExtValue();
69 return containsValue(DL, GlobalLayout, GEP->getPointerOperand(),
70 COffset);
71 }
72
73 if (auto Op = dyn_cast<Operator>(V)) {
74 if (Op->getOpcode() == Instruction::BitCast)
75 return containsValue(DL, GlobalLayout, Op->getOperand(0), COffset);
76
77 if (Op->getOpcode() == Instruction::Select)
78 return containsValue(DL, GlobalLayout, Op->getOperand(1), COffset) &&
79 containsValue(DL, GlobalLayout, Op->getOperand(2), COffset);
80 }
81
82 return false;
83}
84
85BitSetInfo BitSetBuilder::build() {
86 if (Min > Max)
87 Min = 0;
88
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
93 // address.
94 uint64_t Mask = 0;
95 for (uint64_t &Offset : Offsets) {
96 Offset -= Min;
97 Mask |= Offset;
98 }
99
100 BitSetInfo BSI;
101 BSI.ByteOffset = Min;
102
103 BSI.AlignLog2 = 0;
104 // FIXME: Can probably do something smarter if all offsets are 0.
105 if (Mask != 0)
106 BSI.AlignLog2 = countTrailingZeros(Mask, ZB_Undefined);
107
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);
116 }
117
118 return BSI;
119}
120
121namespace {
122
123struct LowerBitSets : public ModulePass {
124 static char ID;
125 LowerBitSets() : ModulePass(ID) {
126 initializeLowerBitSetsPass(*PassRegistry::getPassRegistry());
127 }
128
129 const DataLayout *DL;
130 IntegerType *Int1Ty;
131 IntegerType *Int32Ty;
132 Type *Int32PtrTy;
133 IntegerType *Int64Ty;
134 Type *IntPtrTy;
135
136 // The llvm.bitsets named metadata.
137 NamedMDNode *BitSetNM;
138
139 // Mapping from bitset mdstrings to the call sites that test them.
140 DenseMap<MDString *, std::vector<CallInst *>> BitSetTestCallSites;
141
142 BitSetInfo
143 buildBitSet(MDString *BitSet,
144 const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout);
145 Value *createBitSetTest(IRBuilder<> &B, const BitSetInfo &BSI,
146 GlobalVariable *BitSetGlobal, Value *BitOffset);
147 void
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);
156
157 bool doInitialization(Module &M) override;
158 bool runOnModule(Module &M) override;
159};
160
161} // namespace
162
163INITIALIZE_PASS_BEGIN(LowerBitSets, "lowerbitsets",
164 "Lower bitset metadata", false, false)
165INITIALIZE_PASS_END(LowerBitSets, "lowerbitsets",
166 "Lower bitset metadata", false, false)
167char LowerBitSets::ID = 0;
168
169ModulePass *llvm::createLowerBitSetsPass() { return new LowerBitSets; }
170
171bool LowerBitSets::doInitialization(Module &M) {
172 DL = M.getDataLayout();
173 if (!DL)
174 report_fatal_error("Data layout required");
175
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);
181
182 BitSetNM = M.getNamedMetadata("llvm.bitsets");
183
184 BitSetTestCallSites.clear();
185
186 return false;
187}
188
189/// Build a bit set for \param BitSet using the object layouts in
190/// \param GlobalLayout.
191BitSetInfo LowerBitSets::buildBitSet(
192 MDString *BitSet,
193 const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout) {
194 BitSetBuilder BSB;
195
196 // Compute the byte offset of each element of this bitset.
197 if (BitSetNM) {
198 for (MDNode *Op : BitSetNM->operands()) {
199 if (Op->getOperand(0) != BitSet || !Op->getOperand(1))
200 continue;
201 auto OpGlobal = cast<GlobalVariable>(
202 cast<ConstantAsMetadata>(Op->getOperand(1))->getValue());
203 uint64_t Offset =
204 cast<ConstantInt>(cast<ConstantAsMetadata>(Op->getOperand(2))
205 ->getValue())->getZExtValue();
206
207 Offset += GlobalLayout.find(OpGlobal)->second;
208
209 BSB.addOffset(Offset);
210 }
211 }
212
213 return BSB.build();
214}
215
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.
218static Value *createMaskedBitTest(IRBuilder<> &B, Value *Bits,
219 Value *BitOffset) {
220 auto BitsType = cast<IntegerType>(Bits->getType());
221 unsigned BitWidth = BitsType->getBitWidth();
222
223 BitOffset = B.CreateZExtOrTrunc(BitOffset, BitsType);
224 Value *BitIndex =
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));
229}
230
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.
233Value *LowerBitSets::createBitSetTest(IRBuilder<> &B, const BitSetInfo &BSI,
234 GlobalVariable *BitSetGlobal,
235 Value *BitOffset) {
236 if (BSI.Bits.size() <= 8) {
237 // If the bit set is sufficiently small, we can avoid a load by bit testing
238 // a constant.
239 IntegerType *BitsTy;
240 if (BSI.Bits.size() <= 4)
241 BitsTy = Int32Ty;
242 else
243 BitsTy = Int64Ty;
244
245 uint64_t Bits = 0;
246 for (auto I = BSI.Bits.rbegin(), E = BSI.Bits.rend(); I != E; ++I) {
247 Bits <<= 8;
248 Bits |= *I;
249 }
250 Constant *BitsConst = ConstantInt::get(BitsTy, Bits);
251 return createMaskedBitTest(B, BitsConst, BitOffset);
252 } else {
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);
262
263 return createMaskedBitTest(B, BitSetEntry, BitOffset);
264 }
265}
266
267/// Lower a llvm.bitset.test call to its implementation.
268void 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);
273
274 if (BSI.containsValue(DL, GlobalLayout, Ptr)) {
275 CI->replaceAllUsesWith(
276 ConstantInt::getTrue(BitSetGlobal->getParent()->getContext()));
277 CI->eraseFromParent();
278 return;
279 }
280
281 Constant *GlobalAsInt = ConstantExpr::getPtrToInt(CombinedGlobal, IntPtrTy);
282 Constant *OffsetedGlobalAsInt = ConstantExpr::getAdd(
283 GlobalAsInt, ConstantInt::get(IntPtrTy, BSI.ByteOffset));
284
285 BasicBlock *InitialBB = CI->getParent();
286
287 IRBuilder<> B(CI);
288
289 Value *PtrAsInt = B.CreatePtrToInt(Ptr, IntPtrTy);
290
291 if (BSI.isSingleOffset()) {
292 Value *Eq = B.CreateICmpEQ(PtrAsInt, OffsetedGlobalAsInt);
293 CI->replaceAllUsesWith(Eq);
294 CI->eraseFromParent();
295 return;
296 }
297
298 Value *PtrOffset = B.CreateSub(PtrAsInt, OffsetedGlobalAsInt);
299
300 Value *BitOffset;
301 if (BSI.AlignLog2 == 0) {
302 BitOffset = PtrOffset;
303 } else {
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
311 // the bitset.
312 Value *OffsetSHR =
313 B.CreateLShr(PtrOffset, ConstantInt::get(IntPtrTy, BSI.AlignLog2));
314 Value *OffsetSHL = B.CreateShl(
315 PtrOffset, ConstantInt::get(IntPtrTy, DL->getPointerSizeInBits(0) -
316 BSI.AlignLog2));
317 BitOffset = B.CreateOr(OffsetSHR, OffsetSHL);
318 }
319
320 Constant *BitSizeConst = ConstantInt::get(IntPtrTy, BSI.BitSize);
321 Value *OffsetInRange = B.CreateICmpULT(BitOffset, BitSizeConst);
322
323 TerminatorInst *Term = SplitBlockAndInsertIfThen(OffsetInRange, CI, false);
324 IRBuilder<> ThenB(Term);
325
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);
329
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());
337
338 CI->replaceAllUsesWith(P);
339 CI->eraseFromParent();
340}
341
342/// Given a disjoint set of bitsets and globals, layout the globals, build the
343/// bit sets and lower the llvm.bitset.test calls.
344void LowerBitSets::buildBitSetsFromGlobals(
345 Module &M,
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);
356
357 const StructLayout *CombinedGlobalLayout =
358 DL->getStructLayout(cast<StructType>(NewInit->getType()));
359
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);
364
365 // For each bitset in this disjoint set...
366 for (MDString *BS : BitSets) {
367 // Build the bitset.
368 BitSetInfo BSI = buildBitSet(BS, GlobalLayout);
369
370 // Create a global in which to store it.
371 ++NumBitSetsCreated;
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");
376
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);
381 }
382 }
383
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();
399 }
400}
401
402/// Lower all bit sets in this module.
403bool LowerBitSets::buildBitSets(Module &M) {
404 Function *BitSetTestFunc =
405 M.getFunction(Intrinsic::getName(Intrinsic::bitset_test));
406 if (!BitSetTestFunc)
407 return false;
408
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
411 // sets.
412 typedef EquivalenceClasses<PointerUnion<GlobalVariable *, MDString *>>
413 GlobalClassesTy;
414 GlobalClassesTy GlobalClasses;
415
416 for (const Use &U : BitSetTestFunc->uses()) {
417 auto CI = cast<CallInst>(U.getUser());
418
419 auto BitSetMDVal = dyn_cast<MetadataAsValue>(CI->getArgOperand(1));
420 if (!BitSetMDVal || !isa<MDString>(BitSetMDVal->getMetadata()))
421 report_fatal_error(
422 "Second argument of llvm.bitset.test must be metadata string");
423 auto BitSet = cast<MDString>(BitSetMDVal->getMetadata());
424
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,
430 bool> Ins =
431 BitSetTestCallSites.insert(
432 std::make_pair(BitSet, std::vector<CallInst *>()));
433 Ins.first->second.push_back(CI);
434 if (!Ins.second)
435 continue;
436
437 // Add the bitset to the equivalence class.
438 GlobalClassesTy::iterator GCI = GlobalClasses.insert(BitSet);
439 GlobalClassesTy::member_iterator CurSet = GlobalClasses.findLeader(GCI);
440
441 if (!BitSetNM)
442 continue;
443
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)
448 report_fatal_error(
449 "All operands of llvm.bitsets metadata must have 3 elements");
450
451 if (Op->getOperand(0) != BitSet || !Op->getOperand(1))
452 continue;
453
454 auto OpConstMD = dyn_cast<ConstantAsMetadata>(Op->getOperand(1));
455 if (!OpConstMD)
456 report_fatal_error("Bit set element must be a constant");
457 auto OpGlobal = dyn_cast<GlobalVariable>(OpConstMD->getValue());
458 if (!OpGlobal)
459 report_fatal_error("Bit set element must refer to global");
460
461 auto OffsetConstMD = dyn_cast<ConstantAsMetadata>(Op->getOperand(2));
462 if (!OffsetConstMD)
463 report_fatal_error("Bit set element offset must be a constant");
464 auto OffsetInt = dyn_cast<ConstantInt>(OffsetConstMD->getValue());
465 if (!OffsetInt)
466 report_fatal_error(
467 "Bit set element offset must be an integer constant");
468
469 CurSet = GlobalClasses.unionSets(
470 CurSet, GlobalClasses.findLeader(GlobalClasses.insert(OpGlobal)));
471 }
472 }
473
474 if (GlobalClasses.empty())
475 return false;
476
477 // For each disjoint set we found...
478 for (GlobalClassesTy::iterator I = GlobalClasses.begin(),
479 E = GlobalClasses.end();
480 I != E; ++I) {
481 if (!I->isLeader()) continue;
482
483 ++NumBitSetDisjointSets;
484
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 *>());
492 else
493 Globals.push_back(MI->get<GlobalVariable *>());
494 }
495
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();
501 });
502 std::sort(Globals.begin(), Globals.end(),
503 [](GlobalVariable *GV1, GlobalVariable *GV2) {
504 return GV1->getName() < GV2->getName();
505 });
506
507 // Build the bitsets from this disjoint set.
508 buildBitSetsFromGlobals(M, BitSets, Globals);
509 }
510
511 return true;
512}
513
514bool LowerBitSets::eraseBitSetMetadata(Module &M) {
515 if (!BitSetNM)
516 return false;
517
518 M.eraseNamedMetadata(BitSetNM);
519 return true;
520}
521
522bool LowerBitSets::runOnModule(Module &M) {
523 bool Changed = buildBitSets(M);
524 Changed |= eraseBitSetMetadata(M);
525 return Changed;
526}