blob: bf386a6c618636cd4043304a0334e71b199d0c78 [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"
Peter Collingbournec9f277f2015-03-14 00:00:49 +000019#include "llvm/ADT/Triple.h"
Peter Collingbournee6909c82015-02-20 20:30:47 +000020#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"
Peter Collingbourne3eddf492015-07-29 18:12:36 +000029#include "llvm/Support/Debug.h"
30#include "llvm/Support/raw_ostream.h"
Peter Collingbournee6909c82015-02-20 20:30:47 +000031#include "llvm/Transforms/Utils/BasicBlockUtils.h"
32
33using namespace llvm;
34
35#define DEBUG_TYPE "lowerbitsets"
36
Peter Collingbourneda2dbf22015-03-03 00:49:28 +000037STATISTIC(ByteArraySizeBits, "Byte array size in bits");
38STATISTIC(ByteArraySizeBytes, "Byte array size in bytes");
39STATISTIC(NumByteArraysCreated, "Number of byte arrays created");
Peter Collingbournee6909c82015-02-20 20:30:47 +000040STATISTIC(NumBitSetCallsLowered, "Number of bitset calls lowered");
41STATISTIC(NumBitSetDisjointSets, "Number of disjoint sets of bitsets");
42
Peter Collingbourne994ba3d2015-03-19 22:02:10 +000043static 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
Peter Collingbournee6909c82015-02-20 20:30:47 +000048bool 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
Peter Collingbourneda2dbf22015-03-03 00:49:28 +000059 return Bits.count(BitOffset);
Peter Collingbournee6909c82015-02-20 20:30:47 +000060}
61
62bool BitSetInfo::containsValue(
Mehdi Aminia28d91d2015-03-10 02:37:25 +000063 const DataLayout &DL,
Peter Collingbournee6909c82015-02-20 20:30:47 +000064 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)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +000074 APInt APOffset(DL.getPointerSizeInBits(0), 0);
75 bool Result = GEP->accumulateConstantOffset(DL, APOffset);
Peter Collingbournee6909c82015-02-20 20:30:47 +000076 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
Peter Collingbourne3eddf492015-07-29 18:12:36 +000095void 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
Peter Collingbournee6909c82015-02-20 20:30:47 +0000111BitSetInfo 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;
Peter Collingbournee6909c82015-02-20 20:30:47 +0000130 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;
Peter Collingbournee6909c82015-02-20 20:30:47 +0000136 for (uint64_t Offset : Offsets) {
137 Offset >>= BSI.AlignLog2;
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000138 BSI.Bits.insert(Offset);
Peter Collingbournee6909c82015-02-20 20:30:47 +0000139 }
140
141 return BSI;
142}
143
Peter Collingbourne1baeaa32015-02-24 23:17:02 +0000144void 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
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000173void 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
Peter Collingbournee6909c82015-02-20 20:30:47 +0000196namespace {
197
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000198struct ByteArrayInfo {
199 std::set<uint64_t> Bits;
200 uint64_t BitSize;
201 GlobalVariable *ByteArray;
202 Constant *Mask;
203};
204
Peter Collingbournee6909c82015-02-20 20:30:47 +0000205struct LowerBitSets : public ModulePass {
206 static char ID;
207 LowerBitSets() : ModulePass(ID) {
208 initializeLowerBitSetsPass(*PassRegistry::getPassRegistry());
209 }
210
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000211 Module *M;
212
Peter Collingbournec9f277f2015-03-14 00:00:49 +0000213 bool LinkerSubsectionsViaSymbols;
Peter Collingbournee6909c82015-02-20 20:30:47 +0000214 IntegerType *Int1Ty;
Peter Collingbourneeba7f732015-02-25 20:42:41 +0000215 IntegerType *Int8Ty;
Peter Collingbournee6909c82015-02-20 20:30:47 +0000216 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
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000227 std::vector<ByteArrayInfo> ByteArrayInfos;
228
Peter Collingbournee6909c82015-02-20 20:30:47 +0000229 BitSetInfo
230 buildBitSet(MDString *BitSet,
231 const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout);
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000232 ByteArrayInfo *createByteArray(BitSetInfo &BSI);
233 void allocateByteArrays();
234 Value *createBitSetTest(IRBuilder<> &B, BitSetInfo &BSI, ByteArrayInfo *&BAI,
235 Value *BitOffset);
Peter Collingbourneeba7f732015-02-25 20:42:41 +0000236 Value *
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000237 lowerBitSetCall(CallInst *CI, BitSetInfo &BSI, ByteArrayInfo *&BAI,
238 GlobalVariable *CombinedGlobal,
Peter Collingbournee6909c82015-02-20 20:30:47 +0000239 const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout);
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000240 void buildBitSetsFromGlobals(const std::vector<MDString *> &BitSets,
Peter Collingbournee6909c82015-02-20 20:30:47 +0000241 const std::vector<GlobalVariable *> &Globals);
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000242 bool buildBitSets();
243 bool eraseBitSetMetadata();
Peter Collingbournee6909c82015-02-20 20:30:47 +0000244
245 bool doInitialization(Module &M) override;
246 bool runOnModule(Module &M) override;
247};
248
249} // namespace
250
251INITIALIZE_PASS_BEGIN(LowerBitSets, "lowerbitsets",
252 "Lower bitset metadata", false, false)
253INITIALIZE_PASS_END(LowerBitSets, "lowerbitsets",
254 "Lower bitset metadata", false, false)
255char LowerBitSets::ID = 0;
256
257ModulePass *llvm::createLowerBitSetsPass() { return new LowerBitSets; }
258
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000259bool LowerBitSets::doInitialization(Module &Mod) {
260 M = &Mod;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000261 const DataLayout &DL = Mod.getDataLayout();
Peter Collingbournee6909c82015-02-20 20:30:47 +0000262
Peter Collingbournec9f277f2015-03-14 00:00:49 +0000263 Triple TargetTriple(M->getTargetTriple());
264 LinkerSubsectionsViaSymbols = TargetTriple.isMacOSX();
265
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000266 Int1Ty = Type::getInt1Ty(M->getContext());
267 Int8Ty = Type::getInt8Ty(M->getContext());
268 Int32Ty = Type::getInt32Ty(M->getContext());
Peter Collingbournee6909c82015-02-20 20:30:47 +0000269 Int32PtrTy = PointerType::getUnqual(Int32Ty);
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000270 Int64Ty = Type::getInt64Ty(M->getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000271 IntPtrTy = DL.getIntPtrType(M->getContext(), 0);
Peter Collingbournee6909c82015-02-20 20:30:47 +0000272
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000273 BitSetNM = M->getNamedMetadata("llvm.bitsets");
Peter Collingbournee6909c82015-02-20 20:30:47 +0000274
275 BitSetTestCallSites.clear();
276
277 return false;
278}
279
NAKAMURA Takumi6c246842015-02-22 09:51:42 +0000280/// Build a bit set for BitSet using the object layouts in
281/// GlobalLayout.
Peter Collingbournee6909c82015-02-20 20:30:47 +0000282BitSetInfo 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;
Peter Collingbourneba4c8b52015-06-27 00:17:51 +0000292 auto OpGlobal = dyn_cast<GlobalVariable>(
Peter Collingbournee6909c82015-02-20 20:30:47 +0000293 cast<ConstantAsMetadata>(Op->getOperand(1))->getValue());
Peter Collingbourneba4c8b52015-06-27 00:17:51 +0000294 if (!OpGlobal)
295 continue;
Peter Collingbournee6909c82015-02-20 20:30:47 +0000296 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
NAKAMURA Takumi6c246842015-02-22 09:51:42 +0000309/// Build a test that bit BitOffset mod sizeof(Bits)*8 is set in
310/// Bits. This pattern matches to the bt instruction on x86.
Peter Collingbournee6909c82015-02-20 20:30:47 +0000311static 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
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000324ByteArrayInfo *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
343void 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])};
David Blaikie4a2e73b2015-04-02 18:55:32 +0000372 Constant *GEP = ConstantExpr::getInBoundsGetElementPtr(
373 ByteArrayConst->getType(), ByteArray, Idxs);
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000374
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.
Peter Collingbournead0bdcd2015-03-16 23:36:24 +0000378 if (LinkerSubsectionsViaSymbols) {
379 BAI->ByteArray->replaceAllUsesWith(GEP);
380 } else {
David Blaikief64246b2015-04-29 21:22:39 +0000381 GlobalAlias *Alias =
382 GlobalAlias::create(PointerType::getUnqual(Int8Ty),
383 GlobalValue::PrivateLinkage, "bits", GEP, M);
Peter Collingbournead0bdcd2015-03-16 23:36:24 +0000384 BAI->ByteArray->replaceAllUsesWith(Alias);
385 }
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000386 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
NAKAMURA Takumi6c246842015-02-22 09:51:42 +0000395/// Build a test that bit BitOffset is set in BSI, where
396/// BitSetGlobal is a global containing the bits in BSI.
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000397Value *LowerBitSets::createBitSetTest(IRBuilder<> &B, BitSetInfo &BSI,
398 ByteArrayInfo *&BAI, Value *BitOffset) {
399 if (BSI.BitSize <= 64) {
Peter Collingbournee6909c82015-02-20 20:30:47 +0000400 // If the bit set is sufficiently small, we can avoid a load by bit testing
401 // a constant.
402 IntegerType *BitsTy;
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000403 if (BSI.BitSize <= 32)
Peter Collingbournee6909c82015-02-20 20:30:47 +0000404 BitsTy = Int32Ty;
405 else
406 BitsTy = Int64Ty;
407
408 uint64_t Bits = 0;
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000409 for (auto Bit : BSI.Bits)
410 Bits |= uint64_t(1) << Bit;
Peter Collingbournee6909c82015-02-20 20:30:47 +0000411 Constant *BitsConst = ConstantInt::get(BitsTy, Bits);
412 return createMaskedBitTest(B, BitsConst, BitOffset);
413 } else {
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000414 if (!BAI) {
415 ++NumByteArraysCreated;
416 BAI = createByteArray(BSI);
417 }
Peter Collingbournee6909c82015-02-20 20:30:47 +0000418
Peter Collingbourne994ba3d2015-03-19 22:02:10 +0000419 Constant *ByteArray = BAI->ByteArray;
David Blaikie93c54442015-04-03 19:41:44 +0000420 Type *Ty = BAI->ByteArray->getValueType();
Peter Collingbourne994ba3d2015-03-19 22:02:10 +0000421 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.
David Blaikief64246b2015-04-29 21:22:39 +0000425 ByteArray = GlobalAlias::create(BAI->ByteArray->getType(),
David Blaikie93c54442015-04-03 19:41:44 +0000426 GlobalValue::PrivateLinkage, "bits_use",
427 ByteArray, M);
Peter Collingbourne994ba3d2015-03-19 22:02:10 +0000428 }
429
David Blaikie93c54442015-04-03 19:41:44 +0000430 Value *ByteAddr = B.CreateGEP(Ty, ByteArray, BitOffset);
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000431 Value *Byte = B.CreateLoad(ByteAddr);
432
433 Value *ByteAndMask = B.CreateAnd(Byte, BAI->Mask);
434 return B.CreateICmpNE(ByteAndMask, ConstantInt::get(Int8Ty, 0));
Peter Collingbournee6909c82015-02-20 20:30:47 +0000435 }
436}
437
Peter Collingbourneeba7f732015-02-25 20:42:41 +0000438/// Lower a llvm.bitset.test call to its implementation. Returns the value to
439/// replace the call with.
440Value *LowerBitSets::lowerBitSetCall(
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000441 CallInst *CI, BitSetInfo &BSI, ByteArrayInfo *&BAI,
Peter Collingbournee6909c82015-02-20 20:30:47 +0000442 GlobalVariable *CombinedGlobal,
443 const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout) {
444 Value *Ptr = CI->getArgOperand(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000445 const DataLayout &DL = M->getDataLayout();
Peter Collingbournee6909c82015-02-20 20:30:47 +0000446
Peter Collingbourneeba7f732015-02-25 20:42:41 +0000447 if (BSI.containsValue(DL, GlobalLayout, Ptr))
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000448 return ConstantInt::getTrue(CombinedGlobal->getParent()->getContext());
Peter Collingbournee6909c82015-02-20 20:30:47 +0000449
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
Peter Collingbourneeba7f732015-02-25 20:42:41 +0000460 if (BSI.isSingleOffset())
461 return B.CreateICmpEQ(PtrAsInt, OffsetedGlobalAsInt);
Peter Collingbournee6909c82015-02-20 20:30:47 +0000462
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(
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000480 PtrOffset,
481 ConstantInt::get(IntPtrTy, DL.getPointerSizeInBits(0) - BSI.AlignLog2));
Peter Collingbournee6909c82015-02-20 20:30:47 +0000482 BitOffset = B.CreateOr(OffsetSHR, OffsetSHL);
483 }
484
485 Constant *BitSizeConst = ConstantInt::get(IntPtrTy, BSI.BitSize);
486 Value *OffsetInRange = B.CreateICmpULT(BitOffset, BitSizeConst);
487
Peter Collingbourneeba7f732015-02-25 20:42:41 +0000488 // If the bit set is all ones, testing against it is unnecessary.
489 if (BSI.isAllOnes())
490 return OffsetInRange;
491
Peter Collingbournee6909c82015-02-20 20:30:47 +0000492 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.
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000497 Value *Bit = createBitSetTest(ThenB, BSI, BAI, BitOffset);
Peter Collingbournee6909c82015-02-20 20:30:47 +0000498
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());
Peter Collingbourneeba7f732015-02-25 20:42:41 +0000506 return P;
Peter Collingbournee6909c82015-02-20 20:30:47 +0000507}
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.
511void LowerBitSets::buildBitSetsFromGlobals(
Peter Collingbournee6909c82015-02-20 20:30:47 +0000512 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;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000516 const DataLayout &DL = M->getDataLayout();
Peter Collingbourneeba7f732015-02-25 20:42:41 +0000517 for (GlobalVariable *G : Globals) {
Peter Collingbournee6909c82015-02-20 20:30:47 +0000518 GlobalInits.push_back(G->getInitializer());
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000519 uint64_t InitSize = DL.getTypeAllocSize(G->getInitializer()->getType());
Peter Collingbourneeba7f732015-02-25 20:42:41 +0000520
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();
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000535 Constant *NewInit = ConstantStruct::getAnon(M->getContext(), GlobalInits);
Peter Collingbournee6909c82015-02-20 20:30:47 +0000536 auto CombinedGlobal =
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000537 new GlobalVariable(*M, NewInit->getType(), /*isConstant=*/true,
Peter Collingbournee6909c82015-02-20 20:30:47 +0000538 GlobalValue::PrivateLinkage, NewInit);
539
540 const StructLayout *CombinedGlobalLayout =
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000541 DL.getStructLayout(cast<StructType>(NewInit->getType()));
Peter Collingbournee6909c82015-02-20 20:30:47 +0000542
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)
Peter Collingbourneeba7f732015-02-25 20:42:41 +0000546 // Multiply by 2 to account for padding elements.
547 GlobalLayout[Globals[I]] = CombinedGlobalLayout->getElementOffset(I * 2);
Peter Collingbournee6909c82015-02-20 20:30:47 +0000548
549 // For each bitset in this disjoint set...
550 for (MDString *BS : BitSets) {
551 // Build the bitset.
552 BitSetInfo BSI = buildBitSet(BS, GlobalLayout);
Peter Collingbourne3eddf492015-07-29 18:12:36 +0000553 DEBUG({
554 dbgs() << BS->getString() << ": ";
555 BSI.print(dbgs());
556 });
Peter Collingbournee6909c82015-02-20 20:30:47 +0000557
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000558 ByteArrayInfo *BAI = 0;
Peter Collingbournee6909c82015-02-20 20:30:47 +0000559
560 // Lower each call to llvm.bitset.test for this bitset.
561 for (CallInst *CI : BitSetTestCallSites[BS]) {
562 ++NumBitSetCallsLowered;
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000563 Value *Lowered = lowerBitSetCall(CI, BSI, BAI, CombinedGlobal, GlobalLayout);
Peter Collingbourneeba7f732015-02-25 20:42:41 +0000564 CI->replaceAllUsesWith(Lowered);
565 CI->eraseFromParent();
Peter Collingbournee6909c82015-02-20 20:30:47 +0000566 }
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) {
Peter Collingbourneeba7f732015-02-25 20:42:41 +0000573 // Multiply by 2 to account for padding elements.
Peter Collingbournee6909c82015-02-20 20:30:47 +0000574 Constant *CombinedGlobalIdxs[] = {ConstantInt::get(Int32Ty, 0),
Peter Collingbourneeba7f732015-02-25 20:42:41 +0000575 ConstantInt::get(Int32Ty, I * 2)};
David Blaikie4a2e73b2015-04-02 18:55:32 +0000576 Constant *CombinedGlobalElemPtr = ConstantExpr::getGetElementPtr(
577 NewInit->getType(), CombinedGlobal, CombinedGlobalIdxs);
Peter Collingbournead0bdcd2015-03-16 23:36:24 +0000578 if (LinkerSubsectionsViaSymbols) {
579 Globals[I]->replaceAllUsesWith(CombinedGlobalElemPtr);
580 } else {
David Blaikief64246b2015-04-29 21:22:39 +0000581 GlobalAlias *GAlias =
582 GlobalAlias::create(Globals[I]->getType(), Globals[I]->getLinkage(),
Peter Collingbourne4fc603d2015-06-17 18:31:02 +0000583 "", CombinedGlobalElemPtr, M);
584 GAlias->takeName(Globals[I]);
Peter Collingbournead0bdcd2015-03-16 23:36:24 +0000585 Globals[I]->replaceAllUsesWith(GAlias);
586 }
Peter Collingbournee6909c82015-02-20 20:30:47 +0000587 Globals[I]->eraseFromParent();
588 }
589}
590
591/// Lower all bit sets in this module.
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000592bool LowerBitSets::buildBitSets() {
Peter Collingbournee6909c82015-02-20 20:30:47 +0000593 Function *BitSetTestFunc =
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000594 M->getFunction(Intrinsic::getName(Intrinsic::bitset_test));
Peter Collingbournee6909c82015-02-20 20:30:47 +0000595 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)
Peter Collingbourneba4c8b52015-06-27 00:17:51 +0000648 continue;
Peter Collingbournee6909c82015-02-20 20:30:47 +0000649
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;
Peter Collingbourne1baeaa32015-02-24 23:17:02 +0000677 llvm::DenseMap<MDString *, uint64_t> BitSetIndices;
678 llvm::DenseMap<GlobalVariable *, uint64_t> GlobalIndices;
Peter Collingbournee6909c82015-02-20 20:30:47 +0000679 for (GlobalClassesTy::member_iterator MI = GlobalClasses.member_begin(I);
680 MI != GlobalClasses.member_end(); ++MI) {
Peter Collingbourne1baeaa32015-02-24 23:17:02 +0000681 if ((*MI).is<MDString *>()) {
682 BitSetIndices[MI->get<MDString *>()] = BitSets.size();
Peter Collingbournee6909c82015-02-20 20:30:47 +0000683 BitSets.push_back(MI->get<MDString *>());
Peter Collingbourne1baeaa32015-02-24 23:17:02 +0000684 } else {
685 GlobalIndices[MI->get<GlobalVariable *>()] = Globals.size();
Peter Collingbournee6909c82015-02-20 20:30:47 +0000686 Globals.push_back(MI->get<GlobalVariable *>());
Peter Collingbourne1baeaa32015-02-24 23:17:02 +0000687 }
Peter Collingbournee6909c82015-02-20 20:30:47 +0000688 }
689
Peter Collingbourne1baeaa32015-02-24 23:17:02 +0000690 // 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
Peter Collingbourneba4c8b52015-06-27 00:17:51 +0000702 auto OpGlobal = dyn_cast<GlobalVariable>(
Peter Collingbourne1baeaa32015-02-24 23:17:02 +0000703 cast<ConstantAsMetadata>(Op->getOperand(1))->getValue());
Peter Collingbourneba4c8b52015-06-27 00:17:51 +0000704 if (!OpGlobal)
705 continue;
Peter Collingbourne1baeaa32015-02-24 23:17:02 +0000706 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.
Peter Collingbournee6909c82015-02-20 20:30:47 +0000733 std::sort(BitSets.begin(), BitSets.end(), [](MDString *S1, MDString *S2) {
734 return S1->getString() < S2->getString();
735 });
Peter Collingbournee6909c82015-02-20 20:30:47 +0000736
737 // Build the bitsets from this disjoint set.
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000738 buildBitSetsFromGlobals(BitSets, OrderedGlobals);
Peter Collingbournee6909c82015-02-20 20:30:47 +0000739 }
740
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000741 allocateByteArrays();
742
Peter Collingbournee6909c82015-02-20 20:30:47 +0000743 return true;
744}
745
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000746bool LowerBitSets::eraseBitSetMetadata() {
Peter Collingbournee6909c82015-02-20 20:30:47 +0000747 if (!BitSetNM)
748 return false;
749
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000750 M->eraseNamedMetadata(BitSetNM);
Peter Collingbournee6909c82015-02-20 20:30:47 +0000751 return true;
752}
753
754bool LowerBitSets::runOnModule(Module &M) {
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000755 bool Changed = buildBitSets();
756 Changed |= eraseBitSetMetadata();
Peter Collingbournee6909c82015-02-20 20:30:47 +0000757 return Changed;
758}