LowerBitSets: do not use private aliases at all on Darwin.
[oota-llvm.git] / lib / Transforms / IPO / LowerBitSets.cpp
1 //===-- 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/ADT/Triple.h"
20 #include "llvm/IR/Constant.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/GlobalVariable.h"
23 #include "llvm/IR/IRBuilder.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/Intrinsics.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/Operator.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
30
31 using namespace llvm;
32
33 #define DEBUG_TYPE "lowerbitsets"
34
35 STATISTIC(ByteArraySizeBits, "Byte array size in bits");
36 STATISTIC(ByteArraySizeBytes, "Byte array size in bytes");
37 STATISTIC(NumByteArraysCreated, "Number of byte arrays created");
38 STATISTIC(NumBitSetCallsLowered, "Number of bitset calls lowered");
39 STATISTIC(NumBitSetDisjointSets, "Number of disjoint sets of bitsets");
40
41 bool BitSetInfo::containsGlobalOffset(uint64_t Offset) const {
42   if (Offset < ByteOffset)
43     return false;
44
45   if ((Offset - ByteOffset) % (uint64_t(1) << AlignLog2) != 0)
46     return false;
47
48   uint64_t BitOffset = (Offset - ByteOffset) >> AlignLog2;
49   if (BitOffset >= BitSize)
50     return false;
51
52   return Bits.count(BitOffset);
53 }
54
55 bool BitSetInfo::containsValue(
56     const DataLayout &DL,
57     const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout, Value *V,
58     uint64_t COffset) const {
59   if (auto GV = dyn_cast<GlobalVariable>(V)) {
60     auto I = GlobalLayout.find(GV);
61     if (I == GlobalLayout.end())
62       return false;
63     return containsGlobalOffset(I->second + COffset);
64   }
65
66   if (auto GEP = dyn_cast<GEPOperator>(V)) {
67     APInt APOffset(DL.getPointerSizeInBits(0), 0);
68     bool Result = GEP->accumulateConstantOffset(DL, APOffset);
69     if (!Result)
70       return false;
71     COffset += APOffset.getZExtValue();
72     return containsValue(DL, GlobalLayout, GEP->getPointerOperand(),
73                          COffset);
74   }
75
76   if (auto Op = dyn_cast<Operator>(V)) {
77     if (Op->getOpcode() == Instruction::BitCast)
78       return containsValue(DL, GlobalLayout, Op->getOperand(0), COffset);
79
80     if (Op->getOpcode() == Instruction::Select)
81       return containsValue(DL, GlobalLayout, Op->getOperand(1), COffset) &&
82              containsValue(DL, GlobalLayout, Op->getOperand(2), COffset);
83   }
84
85   return false;
86 }
87
88 BitSetInfo BitSetBuilder::build() {
89   if (Min > Max)
90     Min = 0;
91
92   // Normalize each offset against the minimum observed offset, and compute
93   // the bitwise OR of each of the offsets. The number of trailing zeros
94   // in the mask gives us the log2 of the alignment of all offsets, which
95   // allows us to compress the bitset by only storing one bit per aligned
96   // address.
97   uint64_t Mask = 0;
98   for (uint64_t &Offset : Offsets) {
99     Offset -= Min;
100     Mask |= Offset;
101   }
102
103   BitSetInfo BSI;
104   BSI.ByteOffset = Min;
105
106   BSI.AlignLog2 = 0;
107   if (Mask != 0)
108     BSI.AlignLog2 = countTrailingZeros(Mask, ZB_Undefined);
109
110   // Build the compressed bitset while normalizing the offsets against the
111   // computed alignment.
112   BSI.BitSize = ((Max - Min) >> BSI.AlignLog2) + 1;
113   for (uint64_t Offset : Offsets) {
114     Offset >>= BSI.AlignLog2;
115     BSI.Bits.insert(Offset);
116   }
117
118   return BSI;
119 }
120
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;
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
150 void ByteArrayBuilder::allocate(const std::set<uint64_t> &Bits,
151                                 uint64_t BitSize, uint64_t &AllocByteOffset,
152                                 uint8_t &AllocMask) {
153   // Find the smallest current allocation.
154   unsigned Bit = 0;
155   for (unsigned I = 1; I != BitsPerByte; ++I)
156     if (BitAllocs[I] < BitAllocs[Bit])
157       Bit = I;
158
159   AllocByteOffset = BitAllocs[Bit];
160
161   // Add our size to it.
162   unsigned ReqSize = AllocByteOffset + BitSize;
163   BitAllocs[Bit] = ReqSize;
164   if (Bytes.size() < ReqSize)
165     Bytes.resize(ReqSize);
166
167   // Set our bits.
168   AllocMask = 1 << Bit;
169   for (uint64_t B : Bits)
170     Bytes[AllocByteOffset + B] |= AllocMask;
171 }
172
173 namespace {
174
175 struct ByteArrayInfo {
176   std::set<uint64_t> Bits;
177   uint64_t BitSize;
178   GlobalVariable *ByteArray;
179   Constant *Mask;
180 };
181
182 struct LowerBitSets : public ModulePass {
183   static char ID;
184   LowerBitSets() : ModulePass(ID) {
185     initializeLowerBitSetsPass(*PassRegistry::getPassRegistry());
186   }
187
188   Module *M;
189
190   bool LinkerSubsectionsViaSymbols;
191   IntegerType *Int1Ty;
192   IntegerType *Int8Ty;
193   IntegerType *Int32Ty;
194   Type *Int32PtrTy;
195   IntegerType *Int64Ty;
196   Type *IntPtrTy;
197
198   // The llvm.bitsets named metadata.
199   NamedMDNode *BitSetNM;
200
201   // Mapping from bitset mdstrings to the call sites that test them.
202   DenseMap<MDString *, std::vector<CallInst *>> BitSetTestCallSites;
203
204   std::vector<ByteArrayInfo> ByteArrayInfos;
205
206   BitSetInfo
207   buildBitSet(MDString *BitSet,
208               const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout);
209   ByteArrayInfo *createByteArray(BitSetInfo &BSI);
210   void allocateByteArrays();
211   Value *createBitSetTest(IRBuilder<> &B, BitSetInfo &BSI, ByteArrayInfo *&BAI,
212                           Value *BitOffset);
213   Value *
214   lowerBitSetCall(CallInst *CI, BitSetInfo &BSI, ByteArrayInfo *&BAI,
215                   GlobalVariable *CombinedGlobal,
216                   const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout);
217   void buildBitSetsFromGlobals(const std::vector<MDString *> &BitSets,
218                                const std::vector<GlobalVariable *> &Globals);
219   bool buildBitSets();
220   bool eraseBitSetMetadata();
221
222   bool doInitialization(Module &M) override;
223   bool runOnModule(Module &M) override;
224 };
225
226 } // namespace
227
228 INITIALIZE_PASS_BEGIN(LowerBitSets, "lowerbitsets",
229                 "Lower bitset metadata", false, false)
230 INITIALIZE_PASS_END(LowerBitSets, "lowerbitsets",
231                 "Lower bitset metadata", false, false)
232 char LowerBitSets::ID = 0;
233
234 ModulePass *llvm::createLowerBitSetsPass() { return new LowerBitSets; }
235
236 bool LowerBitSets::doInitialization(Module &Mod) {
237   M = &Mod;
238   const DataLayout &DL = Mod.getDataLayout();
239
240   Triple TargetTriple(M->getTargetTriple());
241   LinkerSubsectionsViaSymbols = TargetTriple.isMacOSX();
242
243   Int1Ty = Type::getInt1Ty(M->getContext());
244   Int8Ty = Type::getInt8Ty(M->getContext());
245   Int32Ty = Type::getInt32Ty(M->getContext());
246   Int32PtrTy = PointerType::getUnqual(Int32Ty);
247   Int64Ty = Type::getInt64Ty(M->getContext());
248   IntPtrTy = DL.getIntPtrType(M->getContext(), 0);
249
250   BitSetNM = M->getNamedMetadata("llvm.bitsets");
251
252   BitSetTestCallSites.clear();
253
254   return false;
255 }
256
257 /// Build a bit set for BitSet using the object layouts in
258 /// GlobalLayout.
259 BitSetInfo LowerBitSets::buildBitSet(
260     MDString *BitSet,
261     const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout) {
262   BitSetBuilder BSB;
263
264   // Compute the byte offset of each element of this bitset.
265   if (BitSetNM) {
266     for (MDNode *Op : BitSetNM->operands()) {
267       if (Op->getOperand(0) != BitSet || !Op->getOperand(1))
268         continue;
269       auto OpGlobal = cast<GlobalVariable>(
270           cast<ConstantAsMetadata>(Op->getOperand(1))->getValue());
271       uint64_t Offset =
272           cast<ConstantInt>(cast<ConstantAsMetadata>(Op->getOperand(2))
273                                 ->getValue())->getZExtValue();
274
275       Offset += GlobalLayout.find(OpGlobal)->second;
276
277       BSB.addOffset(Offset);
278     }
279   }
280
281   return BSB.build();
282 }
283
284 /// Build a test that bit BitOffset mod sizeof(Bits)*8 is set in
285 /// Bits. This pattern matches to the bt instruction on x86.
286 static Value *createMaskedBitTest(IRBuilder<> &B, Value *Bits,
287                                   Value *BitOffset) {
288   auto BitsType = cast<IntegerType>(Bits->getType());
289   unsigned BitWidth = BitsType->getBitWidth();
290
291   BitOffset = B.CreateZExtOrTrunc(BitOffset, BitsType);
292   Value *BitIndex =
293       B.CreateAnd(BitOffset, ConstantInt::get(BitsType, BitWidth - 1));
294   Value *BitMask = B.CreateShl(ConstantInt::get(BitsType, 1), BitIndex);
295   Value *MaskedBits = B.CreateAnd(Bits, BitMask);
296   return B.CreateICmpNE(MaskedBits, ConstantInt::get(BitsType, 0));
297 }
298
299 ByteArrayInfo *LowerBitSets::createByteArray(BitSetInfo &BSI) {
300   // Create globals to stand in for byte arrays and masks. These never actually
301   // get initialized, we RAUW and erase them later in allocateByteArrays() once
302   // we know the offset and mask to use.
303   auto ByteArrayGlobal = new GlobalVariable(
304       *M, Int8Ty, /*isConstant=*/true, GlobalValue::PrivateLinkage, nullptr);
305   auto MaskGlobal = new GlobalVariable(
306       *M, Int8Ty, /*isConstant=*/true, GlobalValue::PrivateLinkage, nullptr);
307
308   ByteArrayInfos.emplace_back();
309   ByteArrayInfo *BAI = &ByteArrayInfos.back();
310
311   BAI->Bits = BSI.Bits;
312   BAI->BitSize = BSI.BitSize;
313   BAI->ByteArray = ByteArrayGlobal;
314   BAI->Mask = ConstantExpr::getPtrToInt(MaskGlobal, Int8Ty);
315   return BAI;
316 }
317
318 void LowerBitSets::allocateByteArrays() {
319   std::stable_sort(ByteArrayInfos.begin(), ByteArrayInfos.end(),
320                    [](const ByteArrayInfo &BAI1, const ByteArrayInfo &BAI2) {
321                      return BAI1.BitSize > BAI2.BitSize;
322                    });
323
324   std::vector<uint64_t> ByteArrayOffsets(ByteArrayInfos.size());
325
326   ByteArrayBuilder BAB;
327   for (unsigned I = 0; I != ByteArrayInfos.size(); ++I) {
328     ByteArrayInfo *BAI = &ByteArrayInfos[I];
329
330     uint8_t Mask;
331     BAB.allocate(BAI->Bits, BAI->BitSize, ByteArrayOffsets[I], Mask);
332
333     BAI->Mask->replaceAllUsesWith(ConstantInt::get(Int8Ty, Mask));
334     cast<GlobalVariable>(BAI->Mask->getOperand(0))->eraseFromParent();
335   }
336
337   Constant *ByteArrayConst = ConstantDataArray::get(M->getContext(), BAB.Bytes);
338   auto ByteArray =
339       new GlobalVariable(*M, ByteArrayConst->getType(), /*isConstant=*/true,
340                          GlobalValue::PrivateLinkage, ByteArrayConst);
341
342   for (unsigned I = 0; I != ByteArrayInfos.size(); ++I) {
343     ByteArrayInfo *BAI = &ByteArrayInfos[I];
344
345     Constant *Idxs[] = {ConstantInt::get(IntPtrTy, 0),
346                         ConstantInt::get(IntPtrTy, ByteArrayOffsets[I])};
347     Constant *GEP = ConstantExpr::getInBoundsGetElementPtr(ByteArray, Idxs);
348
349     // Create an alias instead of RAUW'ing the gep directly. On x86 this ensures
350     // that the pc-relative displacement is folded into the lea instead of the
351     // test instruction getting another displacement.
352     if (LinkerSubsectionsViaSymbols) {
353       BAI->ByteArray->replaceAllUsesWith(GEP);
354     } else {
355       GlobalAlias *Alias = GlobalAlias::create(
356           Int8Ty, 0, GlobalValue::PrivateLinkage, "bits", GEP, M);
357       BAI->ByteArray->replaceAllUsesWith(Alias);
358     }
359     BAI->ByteArray->eraseFromParent();
360   }
361
362   ByteArraySizeBits = BAB.BitAllocs[0] + BAB.BitAllocs[1] + BAB.BitAllocs[2] +
363                       BAB.BitAllocs[3] + BAB.BitAllocs[4] + BAB.BitAllocs[5] +
364                       BAB.BitAllocs[6] + BAB.BitAllocs[7];
365   ByteArraySizeBytes = BAB.Bytes.size();
366 }
367
368 /// Build a test that bit BitOffset is set in BSI, where
369 /// BitSetGlobal is a global containing the bits in BSI.
370 Value *LowerBitSets::createBitSetTest(IRBuilder<> &B, BitSetInfo &BSI,
371                                       ByteArrayInfo *&BAI, Value *BitOffset) {
372   if (BSI.BitSize <= 64) {
373     // If the bit set is sufficiently small, we can avoid a load by bit testing
374     // a constant.
375     IntegerType *BitsTy;
376     if (BSI.BitSize <= 32)
377       BitsTy = Int32Ty;
378     else
379       BitsTy = Int64Ty;
380
381     uint64_t Bits = 0;
382     for (auto Bit : BSI.Bits)
383       Bits |= uint64_t(1) << Bit;
384     Constant *BitsConst = ConstantInt::get(BitsTy, Bits);
385     return createMaskedBitTest(B, BitsConst, BitOffset);
386   } else {
387     if (!BAI) {
388       ++NumByteArraysCreated;
389       BAI = createByteArray(BSI);
390     }
391
392     Value *ByteAddr = B.CreateGEP(BAI->ByteArray, BitOffset);
393     Value *Byte = B.CreateLoad(ByteAddr);
394
395     Value *ByteAndMask = B.CreateAnd(Byte, BAI->Mask);
396     return B.CreateICmpNE(ByteAndMask, ConstantInt::get(Int8Ty, 0));
397   }
398 }
399
400 /// Lower a llvm.bitset.test call to its implementation. Returns the value to
401 /// replace the call with.
402 Value *LowerBitSets::lowerBitSetCall(
403     CallInst *CI, BitSetInfo &BSI, ByteArrayInfo *&BAI,
404     GlobalVariable *CombinedGlobal,
405     const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout) {
406   Value *Ptr = CI->getArgOperand(0);
407   const DataLayout &DL = M->getDataLayout();
408
409   if (BSI.containsValue(DL, GlobalLayout, Ptr))
410     return ConstantInt::getTrue(CombinedGlobal->getParent()->getContext());
411
412   Constant *GlobalAsInt = ConstantExpr::getPtrToInt(CombinedGlobal, IntPtrTy);
413   Constant *OffsetedGlobalAsInt = ConstantExpr::getAdd(
414       GlobalAsInt, ConstantInt::get(IntPtrTy, BSI.ByteOffset));
415
416   BasicBlock *InitialBB = CI->getParent();
417
418   IRBuilder<> B(CI);
419
420   Value *PtrAsInt = B.CreatePtrToInt(Ptr, IntPtrTy);
421
422   if (BSI.isSingleOffset())
423     return B.CreateICmpEQ(PtrAsInt, OffsetedGlobalAsInt);
424
425   Value *PtrOffset = B.CreateSub(PtrAsInt, OffsetedGlobalAsInt);
426
427   Value *BitOffset;
428   if (BSI.AlignLog2 == 0) {
429     BitOffset = PtrOffset;
430   } else {
431     // We need to check that the offset both falls within our range and is
432     // suitably aligned. We can check both properties at the same time by
433     // performing a right rotate by log2(alignment) followed by an integer
434     // comparison against the bitset size. The rotate will move the lower
435     // order bits that need to be zero into the higher order bits of the
436     // result, causing the comparison to fail if they are nonzero. The rotate
437     // also conveniently gives us a bit offset to use during the load from
438     // the bitset.
439     Value *OffsetSHR =
440         B.CreateLShr(PtrOffset, ConstantInt::get(IntPtrTy, BSI.AlignLog2));
441     Value *OffsetSHL = B.CreateShl(
442         PtrOffset,
443         ConstantInt::get(IntPtrTy, DL.getPointerSizeInBits(0) - BSI.AlignLog2));
444     BitOffset = B.CreateOr(OffsetSHR, OffsetSHL);
445   }
446
447   Constant *BitSizeConst = ConstantInt::get(IntPtrTy, BSI.BitSize);
448   Value *OffsetInRange = B.CreateICmpULT(BitOffset, BitSizeConst);
449
450   // If the bit set is all ones, testing against it is unnecessary.
451   if (BSI.isAllOnes())
452     return OffsetInRange;
453
454   TerminatorInst *Term = SplitBlockAndInsertIfThen(OffsetInRange, CI, false);
455   IRBuilder<> ThenB(Term);
456
457   // Now that we know that the offset is in range and aligned, load the
458   // appropriate bit from the bitset.
459   Value *Bit = createBitSetTest(ThenB, BSI, BAI, BitOffset);
460
461   // The value we want is 0 if we came directly from the initial block
462   // (having failed the range or alignment checks), or the loaded bit if
463   // we came from the block in which we loaded it.
464   B.SetInsertPoint(CI);
465   PHINode *P = B.CreatePHI(Int1Ty, 2);
466   P->addIncoming(ConstantInt::get(Int1Ty, 0), InitialBB);
467   P->addIncoming(Bit, ThenB.GetInsertBlock());
468   return P;
469 }
470
471 /// Given a disjoint set of bitsets and globals, layout the globals, build the
472 /// bit sets and lower the llvm.bitset.test calls.
473 void LowerBitSets::buildBitSetsFromGlobals(
474     const std::vector<MDString *> &BitSets,
475     const std::vector<GlobalVariable *> &Globals) {
476   // Build a new global with the combined contents of the referenced globals.
477   std::vector<Constant *> GlobalInits;
478   const DataLayout &DL = M->getDataLayout();
479   for (GlobalVariable *G : Globals) {
480     GlobalInits.push_back(G->getInitializer());
481     uint64_t InitSize = DL.getTypeAllocSize(G->getInitializer()->getType());
482
483     // Compute the amount of padding required to align the next element to the
484     // next power of 2.
485     uint64_t Padding = NextPowerOf2(InitSize - 1) - InitSize;
486
487     // Cap at 128 was found experimentally to have a good data/instruction
488     // overhead tradeoff.
489     if (Padding > 128)
490       Padding = RoundUpToAlignment(InitSize, 128) - InitSize;
491
492     GlobalInits.push_back(
493         ConstantAggregateZero::get(ArrayType::get(Int8Ty, Padding)));
494   }
495   if (!GlobalInits.empty())
496     GlobalInits.pop_back();
497   Constant *NewInit = ConstantStruct::getAnon(M->getContext(), GlobalInits);
498   auto CombinedGlobal =
499       new GlobalVariable(*M, NewInit->getType(), /*isConstant=*/true,
500                          GlobalValue::PrivateLinkage, NewInit);
501
502   const StructLayout *CombinedGlobalLayout =
503       DL.getStructLayout(cast<StructType>(NewInit->getType()));
504
505   // Compute the offsets of the original globals within the new global.
506   DenseMap<GlobalVariable *, uint64_t> GlobalLayout;
507   for (unsigned I = 0; I != Globals.size(); ++I)
508     // Multiply by 2 to account for padding elements.
509     GlobalLayout[Globals[I]] = CombinedGlobalLayout->getElementOffset(I * 2);
510
511   // For each bitset in this disjoint set...
512   for (MDString *BS : BitSets) {
513     // Build the bitset.
514     BitSetInfo BSI = buildBitSet(BS, GlobalLayout);
515
516     ByteArrayInfo *BAI = 0;
517
518     // Lower each call to llvm.bitset.test for this bitset.
519     for (CallInst *CI : BitSetTestCallSites[BS]) {
520       ++NumBitSetCallsLowered;
521       Value *Lowered = lowerBitSetCall(CI, BSI, BAI, CombinedGlobal, GlobalLayout);
522       CI->replaceAllUsesWith(Lowered);
523       CI->eraseFromParent();
524     }
525   }
526
527   // Build aliases pointing to offsets into the combined global for each
528   // global from which we built the combined global, and replace references
529   // to the original globals with references to the aliases.
530   for (unsigned I = 0; I != Globals.size(); ++I) {
531     // Multiply by 2 to account for padding elements.
532     Constant *CombinedGlobalIdxs[] = {ConstantInt::get(Int32Ty, 0),
533                                       ConstantInt::get(Int32Ty, I * 2)};
534     Constant *CombinedGlobalElemPtr =
535         ConstantExpr::getGetElementPtr(CombinedGlobal, CombinedGlobalIdxs);
536     if (LinkerSubsectionsViaSymbols) {
537       Globals[I]->replaceAllUsesWith(CombinedGlobalElemPtr);
538     } else {
539       GlobalAlias *GAlias = GlobalAlias::create(
540           Globals[I]->getType()->getElementType(),
541           Globals[I]->getType()->getAddressSpace(), Globals[I]->getLinkage(),
542           "", CombinedGlobalElemPtr, M);
543       GAlias->takeName(Globals[I]);
544       Globals[I]->replaceAllUsesWith(GAlias);
545     }
546     Globals[I]->eraseFromParent();
547   }
548 }
549
550 /// Lower all bit sets in this module.
551 bool LowerBitSets::buildBitSets() {
552   Function *BitSetTestFunc =
553       M->getFunction(Intrinsic::getName(Intrinsic::bitset_test));
554   if (!BitSetTestFunc)
555     return false;
556
557   // Equivalence class set containing bitsets and the globals they reference.
558   // This is used to partition the set of bitsets in the module into disjoint
559   // sets.
560   typedef EquivalenceClasses<PointerUnion<GlobalVariable *, MDString *>>
561       GlobalClassesTy;
562   GlobalClassesTy GlobalClasses;
563
564   for (const Use &U : BitSetTestFunc->uses()) {
565     auto CI = cast<CallInst>(U.getUser());
566
567     auto BitSetMDVal = dyn_cast<MetadataAsValue>(CI->getArgOperand(1));
568     if (!BitSetMDVal || !isa<MDString>(BitSetMDVal->getMetadata()))
569       report_fatal_error(
570           "Second argument of llvm.bitset.test must be metadata string");
571     auto BitSet = cast<MDString>(BitSetMDVal->getMetadata());
572
573     // Add the call site to the list of call sites for this bit set. We also use
574     // BitSetTestCallSites to keep track of whether we have seen this bit set
575     // before. If we have, we don't need to re-add the referenced globals to the
576     // equivalence class.
577     std::pair<DenseMap<MDString *, std::vector<CallInst *>>::iterator,
578               bool> Ins =
579         BitSetTestCallSites.insert(
580             std::make_pair(BitSet, std::vector<CallInst *>()));
581     Ins.first->second.push_back(CI);
582     if (!Ins.second)
583       continue;
584
585     // Add the bitset to the equivalence class.
586     GlobalClassesTy::iterator GCI = GlobalClasses.insert(BitSet);
587     GlobalClassesTy::member_iterator CurSet = GlobalClasses.findLeader(GCI);
588
589     if (!BitSetNM)
590       continue;
591
592     // Verify the bitset metadata and add the referenced globals to the bitset's
593     // equivalence class.
594     for (MDNode *Op : BitSetNM->operands()) {
595       if (Op->getNumOperands() != 3)
596         report_fatal_error(
597             "All operands of llvm.bitsets metadata must have 3 elements");
598
599       if (Op->getOperand(0) != BitSet || !Op->getOperand(1))
600         continue;
601
602       auto OpConstMD = dyn_cast<ConstantAsMetadata>(Op->getOperand(1));
603       if (!OpConstMD)
604         report_fatal_error("Bit set element must be a constant");
605       auto OpGlobal = dyn_cast<GlobalVariable>(OpConstMD->getValue());
606       if (!OpGlobal)
607         report_fatal_error("Bit set element must refer to global");
608
609       auto OffsetConstMD = dyn_cast<ConstantAsMetadata>(Op->getOperand(2));
610       if (!OffsetConstMD)
611         report_fatal_error("Bit set element offset must be a constant");
612       auto OffsetInt = dyn_cast<ConstantInt>(OffsetConstMD->getValue());
613       if (!OffsetInt)
614         report_fatal_error(
615             "Bit set element offset must be an integer constant");
616
617       CurSet = GlobalClasses.unionSets(
618           CurSet, GlobalClasses.findLeader(GlobalClasses.insert(OpGlobal)));
619     }
620   }
621
622   if (GlobalClasses.empty())
623     return false;
624
625   // For each disjoint set we found...
626   for (GlobalClassesTy::iterator I = GlobalClasses.begin(),
627                                  E = GlobalClasses.end();
628        I != E; ++I) {
629     if (!I->isLeader()) continue;
630
631     ++NumBitSetDisjointSets;
632
633     // Build the list of bitsets and referenced globals in this disjoint set.
634     std::vector<MDString *> BitSets;
635     std::vector<GlobalVariable *> Globals;
636     llvm::DenseMap<MDString *, uint64_t> BitSetIndices;
637     llvm::DenseMap<GlobalVariable *, uint64_t> GlobalIndices;
638     for (GlobalClassesTy::member_iterator MI = GlobalClasses.member_begin(I);
639          MI != GlobalClasses.member_end(); ++MI) {
640       if ((*MI).is<MDString *>()) {
641         BitSetIndices[MI->get<MDString *>()] = BitSets.size();
642         BitSets.push_back(MI->get<MDString *>());
643       } else {
644         GlobalIndices[MI->get<GlobalVariable *>()] = Globals.size();
645         Globals.push_back(MI->get<GlobalVariable *>());
646       }
647     }
648
649     // For each bitset, build a set of indices that refer to globals referenced
650     // by the bitset.
651     std::vector<std::set<uint64_t>> BitSetMembers(BitSets.size());
652     if (BitSetNM) {
653       for (MDNode *Op : BitSetNM->operands()) {
654         // Op = { bitset name, global, offset }
655         if (!Op->getOperand(1))
656           continue;
657         auto I = BitSetIndices.find(cast<MDString>(Op->getOperand(0)));
658         if (I == BitSetIndices.end())
659           continue;
660
661         auto OpGlobal = cast<GlobalVariable>(
662             cast<ConstantAsMetadata>(Op->getOperand(1))->getValue());
663         BitSetMembers[I->second].insert(GlobalIndices[OpGlobal]);
664       }
665     }
666
667     // Order the sets of indices by size. The GlobalLayoutBuilder works best
668     // when given small index sets first.
669     std::stable_sort(
670         BitSetMembers.begin(), BitSetMembers.end(),
671         [](const std::set<uint64_t> &O1, const std::set<uint64_t> &O2) {
672           return O1.size() < O2.size();
673         });
674
675     // Create a GlobalLayoutBuilder and provide it with index sets as layout
676     // fragments. The GlobalLayoutBuilder tries to lay out members of fragments
677     // as close together as possible.
678     GlobalLayoutBuilder GLB(Globals.size());
679     for (auto &&MemSet : BitSetMembers)
680       GLB.addFragment(MemSet);
681
682     // Build a vector of globals with the computed layout.
683     std::vector<GlobalVariable *> OrderedGlobals(Globals.size());
684     auto OGI = OrderedGlobals.begin();
685     for (auto &&F : GLB.Fragments)
686       for (auto &&Offset : F)
687         *OGI++ = Globals[Offset];
688
689     // Order bitsets by name for determinism.
690     std::sort(BitSets.begin(), BitSets.end(), [](MDString *S1, MDString *S2) {
691       return S1->getString() < S2->getString();
692     });
693
694     // Build the bitsets from this disjoint set.
695     buildBitSetsFromGlobals(BitSets, OrderedGlobals);
696   }
697
698   allocateByteArrays();
699
700   return true;
701 }
702
703 bool LowerBitSets::eraseBitSetMetadata() {
704   if (!BitSetNM)
705     return false;
706
707   M->eraseNamedMetadata(BitSetNM);
708   return true;
709 }
710
711 bool LowerBitSets::runOnModule(Module &M) {
712   bool Changed = buildBitSets();
713   Changed |= eraseBitSetMetadata();
714   return Changed;
715 }