blob: 6f6ca1164730c912e2b1840729eefe3a5532df31 [file] [log] [blame]
Kostya Serebryanyc98ef712016-08-16 17:37:13 +00001//===- FuzzerValueBitMap.h - INTERNAL - Bit map -----------------*- C++ -* ===//
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// ValueBitMap.
10//===----------------------------------------------------------------------===//
11
12#ifndef LLVM_FUZZER_VALUE_BIT_MAP_H
13#define LLVM_FUZZER_VALUE_BIT_MAP_H
14
15namespace fuzzer {
16
17// A bit map containing kMapSizeInWords bits.
18struct ValueBitMap {
19 static const size_t kMapSizeInBits = 65371; // Prime.
20 static const size_t kMapSizeInBitsAligned = 65536; // 2^16
21 static const size_t kBitsInWord = (sizeof(uintptr_t) * 8);
22 static const size_t kMapSizeInWords = kMapSizeInBitsAligned / kBitsInWord;
23 public:
24 // Clears all bits.
25 void Reset() { memset(Map, 0, sizeof(Map)); }
26
Kostya Serebryany53501782016-09-15 04:36:45 +000027 // Computes a hash function of Value and sets the corresponding bit.
28 // Returns true if the bit was changed from 0 to 1.
29 inline bool AddValue(uintptr_t Value) {
Kostya Serebryany30443902016-08-16 21:28:05 +000030 uintptr_t Idx = Value < kMapSizeInBits ? Value : Value % kMapSizeInBits;
Kostya Serebryanyc98ef712016-08-16 17:37:13 +000031 uintptr_t WordIdx = Idx / kBitsInWord;
32 uintptr_t BitIdx = Idx % kBitsInWord;
Kostya Serebryany53501782016-09-15 04:36:45 +000033 uintptr_t Old = Map[WordIdx];
34 uintptr_t New = Old | (1UL << BitIdx);
35 Map[WordIdx] = New;
36 return New != Old;
Kostya Serebryanyc98ef712016-08-16 17:37:13 +000037 }
38
Kostya Serebryanyd46a59f2016-08-16 19:33:51 +000039 // Merges 'Other' into 'this', clears 'Other',
Kostya Serebryanyc98ef712016-08-16 17:37:13 +000040 // returns the number of set bits in 'this'.
Kostya Serebryanybceadcf2016-08-24 01:38:42 +000041 ATTRIBUTE_TARGET_POPCNT
Kostya Serebryanyc98ef712016-08-16 17:37:13 +000042 size_t MergeFrom(ValueBitMap &Other) {
43 uintptr_t Res = 0;
44 for (size_t i = 0; i < kMapSizeInWords; i++) {
45 auto O = Other.Map[i];
46 auto M = Map[i];
47 if (O) {
48 Map[i] = (M |= O);
49 Other.Map[i] = 0;
50 }
Kostya Serebryanyd46a59f2016-08-16 19:33:51 +000051 if (M)
52 Res += __builtin_popcountl(M);
Kostya Serebryanyc98ef712016-08-16 17:37:13 +000053 }
54 return Res;
55 }
56
57 private:
58 uintptr_t Map[kMapSizeInWords] __attribute__((aligned(512)));
59};
60
61} // namespace fuzzer
62
63#endif // LLVM_FUZZER_VALUE_BIT_MAP_H