blob: 032d6484ea2009966ee6c05728f5580214a39911 [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
Peter Collingbourne1baeaa32015-02-24 23:17:02 +0000121void 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;
126
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
131 // fragment.
132 Fragment.push_back(ObjIndex);
133 } else {
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
138 // indices.
139 std::vector<uint64_t> &OldFragment = Fragments[OldFragmentIndex];
140 Fragment.insert(Fragment.end(), OldFragment.begin(), OldFragment.end());
141 OldFragment.clear();
142 }
143 }
144
145 // Update the fragment map to point our object indices to this fragment.
146 for (uint64_t ObjIndex : Fragment)
147 FragmentMap[ObjIndex] = FragmentIndex;
148}
149
Peter Collingbournee6909c82015-02-20 20:30:47 +0000150namespace {
151
152struct LowerBitSets : public ModulePass {
153 static char ID;
154 LowerBitSets() : ModulePass(ID) {
155 initializeLowerBitSetsPass(*PassRegistry::getPassRegistry());
156 }
157
158 const DataLayout *DL;
159 IntegerType *Int1Ty;
160 IntegerType *Int32Ty;
161 Type *Int32PtrTy;
162 IntegerType *Int64Ty;
163 Type *IntPtrTy;
164
165 // The llvm.bitsets named metadata.
166 NamedMDNode *BitSetNM;
167
168 // Mapping from bitset mdstrings to the call sites that test them.
169 DenseMap<MDString *, std::vector<CallInst *>> BitSetTestCallSites;
170
171 BitSetInfo
172 buildBitSet(MDString *BitSet,
173 const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout);
174 Value *createBitSetTest(IRBuilder<> &B, const BitSetInfo &BSI,
175 GlobalVariable *BitSetGlobal, Value *BitOffset);
176 void
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);
185
186 bool doInitialization(Module &M) override;
187 bool runOnModule(Module &M) override;
188};
189
190} // namespace
191
192INITIALIZE_PASS_BEGIN(LowerBitSets, "lowerbitsets",
193 "Lower bitset metadata", false, false)
194INITIALIZE_PASS_END(LowerBitSets, "lowerbitsets",
195 "Lower bitset metadata", false, false)
196char LowerBitSets::ID = 0;
197
198ModulePass *llvm::createLowerBitSetsPass() { return new LowerBitSets; }
199
200bool LowerBitSets::doInitialization(Module &M) {
201 DL = M.getDataLayout();
202 if (!DL)
203 report_fatal_error("Data layout required");
204
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);
210
211 BitSetNM = M.getNamedMetadata("llvm.bitsets");
212
213 BitSetTestCallSites.clear();
214
215 return false;
216}
217
NAKAMURA Takumi6c246842015-02-22 09:51:42 +0000218/// Build a bit set for BitSet using the object layouts in
219/// GlobalLayout.
Peter Collingbournee6909c82015-02-20 20:30:47 +0000220BitSetInfo LowerBitSets::buildBitSet(
221 MDString *BitSet,
222 const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout) {
223 BitSetBuilder BSB;
224
225 // Compute the byte offset of each element of this bitset.
226 if (BitSetNM) {
227 for (MDNode *Op : BitSetNM->operands()) {
228 if (Op->getOperand(0) != BitSet || !Op->getOperand(1))
229 continue;
230 auto OpGlobal = cast<GlobalVariable>(
231 cast<ConstantAsMetadata>(Op->getOperand(1))->getValue());
232 uint64_t Offset =
233 cast<ConstantInt>(cast<ConstantAsMetadata>(Op->getOperand(2))
234 ->getValue())->getZExtValue();
235
236 Offset += GlobalLayout.find(OpGlobal)->second;
237
238 BSB.addOffset(Offset);
239 }
240 }
241
242 return BSB.build();
243}
244
NAKAMURA Takumi6c246842015-02-22 09:51:42 +0000245/// Build a test that bit BitOffset mod sizeof(Bits)*8 is set in
246/// Bits. This pattern matches to the bt instruction on x86.
Peter Collingbournee6909c82015-02-20 20:30:47 +0000247static Value *createMaskedBitTest(IRBuilder<> &B, Value *Bits,
248 Value *BitOffset) {
249 auto BitsType = cast<IntegerType>(Bits->getType());
250 unsigned BitWidth = BitsType->getBitWidth();
251
252 BitOffset = B.CreateZExtOrTrunc(BitOffset, BitsType);
253 Value *BitIndex =
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));
258}
259
NAKAMURA Takumi6c246842015-02-22 09:51:42 +0000260/// Build a test that bit BitOffset is set in BSI, where
261/// BitSetGlobal is a global containing the bits in BSI.
Peter Collingbournee6909c82015-02-20 20:30:47 +0000262Value *LowerBitSets::createBitSetTest(IRBuilder<> &B, const BitSetInfo &BSI,
263 GlobalVariable *BitSetGlobal,
264 Value *BitOffset) {
265 if (BSI.Bits.size() <= 8) {
266 // If the bit set is sufficiently small, we can avoid a load by bit testing
267 // a constant.
268 IntegerType *BitsTy;
269 if (BSI.Bits.size() <= 4)
270 BitsTy = Int32Ty;
271 else
272 BitsTy = Int64Ty;
273
274 uint64_t Bits = 0;
275 for (auto I = BSI.Bits.rbegin(), E = BSI.Bits.rend(); I != E; ++I) {
276 Bits <<= 8;
277 Bits |= *I;
278 }
279 Constant *BitsConst = ConstantInt::get(BitsTy, Bits);
280 return createMaskedBitTest(B, BitsConst, BitOffset);
281 } else {
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);
291
292 return createMaskedBitTest(B, BitSetEntry, BitOffset);
293 }
294}
295
296/// Lower a llvm.bitset.test call to its implementation.
297void 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);
302
303 if (BSI.containsValue(DL, GlobalLayout, Ptr)) {
304 CI->replaceAllUsesWith(
305 ConstantInt::getTrue(BitSetGlobal->getParent()->getContext()));
306 CI->eraseFromParent();
307 return;
308 }
309
310 Constant *GlobalAsInt = ConstantExpr::getPtrToInt(CombinedGlobal, IntPtrTy);
311 Constant *OffsetedGlobalAsInt = ConstantExpr::getAdd(
312 GlobalAsInt, ConstantInt::get(IntPtrTy, BSI.ByteOffset));
313
314 BasicBlock *InitialBB = CI->getParent();
315
316 IRBuilder<> B(CI);
317
318 Value *PtrAsInt = B.CreatePtrToInt(Ptr, IntPtrTy);
319
320 if (BSI.isSingleOffset()) {
321 Value *Eq = B.CreateICmpEQ(PtrAsInt, OffsetedGlobalAsInt);
322 CI->replaceAllUsesWith(Eq);
323 CI->eraseFromParent();
324 return;
325 }
326
327 Value *PtrOffset = B.CreateSub(PtrAsInt, OffsetedGlobalAsInt);
328
329 Value *BitOffset;
330 if (BSI.AlignLog2 == 0) {
331 BitOffset = PtrOffset;
332 } else {
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
340 // the bitset.
341 Value *OffsetSHR =
342 B.CreateLShr(PtrOffset, ConstantInt::get(IntPtrTy, BSI.AlignLog2));
343 Value *OffsetSHL = B.CreateShl(
344 PtrOffset, ConstantInt::get(IntPtrTy, DL->getPointerSizeInBits(0) -
345 BSI.AlignLog2));
346 BitOffset = B.CreateOr(OffsetSHR, OffsetSHL);
347 }
348
349 Constant *BitSizeConst = ConstantInt::get(IntPtrTy, BSI.BitSize);
350 Value *OffsetInRange = B.CreateICmpULT(BitOffset, BitSizeConst);
351
352 TerminatorInst *Term = SplitBlockAndInsertIfThen(OffsetInRange, CI, false);
353 IRBuilder<> ThenB(Term);
354
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);
358
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());
366
367 CI->replaceAllUsesWith(P);
368 CI->eraseFromParent();
369}
370
371/// Given a disjoint set of bitsets and globals, layout the globals, build the
372/// bit sets and lower the llvm.bitset.test calls.
373void LowerBitSets::buildBitSetsFromGlobals(
374 Module &M,
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);
385
386 const StructLayout *CombinedGlobalLayout =
387 DL->getStructLayout(cast<StructType>(NewInit->getType()));
388
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);
393
394 // For each bitset in this disjoint set...
395 for (MDString *BS : BitSets) {
396 // Build the bitset.
397 BitSetInfo BSI = buildBitSet(BS, GlobalLayout);
398
399 // Create a global in which to store it.
400 ++NumBitSetsCreated;
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");
405
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);
410 }
411 }
412
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();
428 }
429}
430
431/// Lower all bit sets in this module.
432bool LowerBitSets::buildBitSets(Module &M) {
433 Function *BitSetTestFunc =
434 M.getFunction(Intrinsic::getName(Intrinsic::bitset_test));
435 if (!BitSetTestFunc)
436 return false;
437
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
440 // sets.
441 typedef EquivalenceClasses<PointerUnion<GlobalVariable *, MDString *>>
442 GlobalClassesTy;
443 GlobalClassesTy GlobalClasses;
444
445 for (const Use &U : BitSetTestFunc->uses()) {
446 auto CI = cast<CallInst>(U.getUser());
447
448 auto BitSetMDVal = dyn_cast<MetadataAsValue>(CI->getArgOperand(1));
449 if (!BitSetMDVal || !isa<MDString>(BitSetMDVal->getMetadata()))
450 report_fatal_error(
451 "Second argument of llvm.bitset.test must be metadata string");
452 auto BitSet = cast<MDString>(BitSetMDVal->getMetadata());
453
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,
459 bool> Ins =
460 BitSetTestCallSites.insert(
461 std::make_pair(BitSet, std::vector<CallInst *>()));
462 Ins.first->second.push_back(CI);
463 if (!Ins.second)
464 continue;
465
466 // Add the bitset to the equivalence class.
467 GlobalClassesTy::iterator GCI = GlobalClasses.insert(BitSet);
468 GlobalClassesTy::member_iterator CurSet = GlobalClasses.findLeader(GCI);
469
470 if (!BitSetNM)
471 continue;
472
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)
477 report_fatal_error(
478 "All operands of llvm.bitsets metadata must have 3 elements");
479
480 if (Op->getOperand(0) != BitSet || !Op->getOperand(1))
481 continue;
482
483 auto OpConstMD = dyn_cast<ConstantAsMetadata>(Op->getOperand(1));
484 if (!OpConstMD)
485 report_fatal_error("Bit set element must be a constant");
486 auto OpGlobal = dyn_cast<GlobalVariable>(OpConstMD->getValue());
487 if (!OpGlobal)
488 report_fatal_error("Bit set element must refer to global");
489
490 auto OffsetConstMD = dyn_cast<ConstantAsMetadata>(Op->getOperand(2));
491 if (!OffsetConstMD)
492 report_fatal_error("Bit set element offset must be a constant");
493 auto OffsetInt = dyn_cast<ConstantInt>(OffsetConstMD->getValue());
494 if (!OffsetInt)
495 report_fatal_error(
496 "Bit set element offset must be an integer constant");
497
498 CurSet = GlobalClasses.unionSets(
499 CurSet, GlobalClasses.findLeader(GlobalClasses.insert(OpGlobal)));
500 }
501 }
502
503 if (GlobalClasses.empty())
504 return false;
505
506 // For each disjoint set we found...
507 for (GlobalClassesTy::iterator I = GlobalClasses.begin(),
508 E = GlobalClasses.end();
509 I != E; ++I) {
510 if (!I->isLeader()) continue;
511
512 ++NumBitSetDisjointSets;
513
514 // Build the list of bitsets and referenced globals in this disjoint set.
515 std::vector<MDString *> BitSets;
516 std::vector<GlobalVariable *> Globals;
Peter Collingbourne1baeaa32015-02-24 23:17:02 +0000517 llvm::DenseMap<MDString *, uint64_t> BitSetIndices;
518 llvm::DenseMap<GlobalVariable *, uint64_t> GlobalIndices;
Peter Collingbournee6909c82015-02-20 20:30:47 +0000519 for (GlobalClassesTy::member_iterator MI = GlobalClasses.member_begin(I);
520 MI != GlobalClasses.member_end(); ++MI) {
Peter Collingbourne1baeaa32015-02-24 23:17:02 +0000521 if ((*MI).is<MDString *>()) {
522 BitSetIndices[MI->get<MDString *>()] = BitSets.size();
Peter Collingbournee6909c82015-02-20 20:30:47 +0000523 BitSets.push_back(MI->get<MDString *>());
Peter Collingbourne1baeaa32015-02-24 23:17:02 +0000524 } else {
525 GlobalIndices[MI->get<GlobalVariable *>()] = Globals.size();
Peter Collingbournee6909c82015-02-20 20:30:47 +0000526 Globals.push_back(MI->get<GlobalVariable *>());
Peter Collingbourne1baeaa32015-02-24 23:17:02 +0000527 }
Peter Collingbournee6909c82015-02-20 20:30:47 +0000528 }
529
Peter Collingbourne1baeaa32015-02-24 23:17:02 +0000530 // For each bitset, build a set of indices that refer to globals referenced
531 // by the bitset.
532 std::vector<std::set<uint64_t>> BitSetMembers(BitSets.size());
533 if (BitSetNM) {
534 for (MDNode *Op : BitSetNM->operands()) {
535 // Op = { bitset name, global, offset }
536 if (!Op->getOperand(1))
537 continue;
538 auto I = BitSetIndices.find(cast<MDString>(Op->getOperand(0)));
539 if (I == BitSetIndices.end())
540 continue;
541
542 auto OpGlobal = cast<GlobalVariable>(
543 cast<ConstantAsMetadata>(Op->getOperand(1))->getValue());
544 BitSetMembers[I->second].insert(GlobalIndices[OpGlobal]);
545 }
546 }
547
548 // Order the sets of indices by size. The GlobalLayoutBuilder works best
549 // when given small index sets first.
550 std::stable_sort(
551 BitSetMembers.begin(), BitSetMembers.end(),
552 [](const std::set<uint64_t> &O1, const std::set<uint64_t> &O2) {
553 return O1.size() < O2.size();
554 });
555
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);
562
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];
569
570 // Order bitsets by name for determinism.
Peter Collingbournee6909c82015-02-20 20:30:47 +0000571 std::sort(BitSets.begin(), BitSets.end(), [](MDString *S1, MDString *S2) {
572 return S1->getString() < S2->getString();
573 });
Peter Collingbournee6909c82015-02-20 20:30:47 +0000574
575 // Build the bitsets from this disjoint set.
Peter Collingbourne1baeaa32015-02-24 23:17:02 +0000576 buildBitSetsFromGlobals(M, BitSets, OrderedGlobals);
Peter Collingbournee6909c82015-02-20 20:30:47 +0000577 }
578
579 return true;
580}
581
582bool LowerBitSets::eraseBitSetMetadata(Module &M) {
583 if (!BitSetNM)
584 return false;
585
586 M.eraseNamedMetadata(BitSetNM);
587 return true;
588}
589
590bool LowerBitSets::runOnModule(Module &M) {
591 bool Changed = buildBitSets(M);
592 Changed |= eraseBitSetMetadata(M);
593 return Changed;
594}