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