folly: accommodate use of -Wshadow in other projects
[folly.git] / folly / experimental / EliasFanoCoding.h
1 /*
2  * Copyright 2013 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /**
18  * @author Philip Pronin (philipp@fb.com)
19  *
20  * Based on the paper by Sebastiano Vigna,
21  * "Quasi-succinct indices" (arxiv:1206.4300).
22  */
23
24 #ifndef FOLLY_EXPERIMENTAL_ELIAS_FANO_CODING_H
25 #define FOLLY_EXPERIMENTAL_ELIAS_FANO_CODING_H
26
27 #ifndef __GNUC__
28 #error EliasFanoCoding.h requires GCC
29 #endif
30
31 #if !defined(__x86_64__)
32 #error EliasFanoCoding.h requires x86_64
33 #endif
34
35 #include <cstdlib>
36 #include <algorithm>
37 #include <limits>
38 #include <type_traits>
39 #include <boost/noncopyable.hpp>
40 #include <glog/logging.h>
41 #include "folly/Bits.h"
42 #include "folly/CpuId.h"
43 #include "folly/Likely.h"
44 #include "folly/Range.h"
45
46 #if __BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__
47 #error EliasFanoCoding.h requires little endianness
48 #endif
49
50 namespace folly { namespace compression {
51
52 template <class Value,
53           class SkipValue = size_t,
54           size_t kSkipQuantum = 0,     // 0 = disabled
55           size_t kForwardQuantum = 0>  // 0 = disabled
56 struct EliasFanoCompressedList {
57   static_assert(std::is_integral<Value>::value &&
58                 std::is_unsigned<Value>::value,
59                 "Value should be unsigned integral");
60
61   typedef Value ValueType;
62   typedef SkipValue SkipValueType;
63
64   EliasFanoCompressedList()
65     : size(0), numLowerBits(0) { }
66
67   static constexpr size_t skipQuantum = kSkipQuantum;
68   static constexpr size_t forwardQuantum = kForwardQuantum;
69
70   size_t size;
71   uint8_t numLowerBits;
72
73   // WARNING: EliasFanoCompressedList has no ownership of
74   // lower, upper, skipPointers and forwardPointers.
75   // The 7 bytes following the last byte of lower and upper
76   // sequences should be readable.
77   folly::ByteRange lower;
78   folly::ByteRange upper;
79
80   folly::ByteRange skipPointers;
81   folly::ByteRange forwardPointers;
82
83   void free() {
84     ::free(const_cast<unsigned char*>(lower.data()));
85     ::free(const_cast<unsigned char*>(upper.data()));
86     ::free(const_cast<unsigned char*>(skipPointers.data()));
87     ::free(const_cast<unsigned char*>(forwardPointers.data()));
88   }
89
90   static uint8_t defaultNumLowerBits(size_t upperBound, size_t size) {
91     if (size == 0 || upperBound < size) {
92       return 0;
93     }
94     // floor(log(upperBound / size));
95     return folly::findLastSet(upperBound / size) - 1;
96   }
97
98   // WARNING: encode() mallocates lower, upper, skipPointers
99   // and forwardPointers. As EliasFanoCompressedList has
100   // no ownership of them, you need to call free() explicitly.
101   static void encode(const ValueType* list, size_t size,
102                      EliasFanoCompressedList& result) {
103     encode(list, list + size, result);
104   }
105
106   template <class RandomAccessIterator>
107   static void encode(RandomAccessIterator begin,
108                      RandomAccessIterator end,
109                      EliasFanoCompressedList& result) {
110     auto list = begin;
111     const size_t size = end - begin;
112
113     if (size == 0) {
114       result = EliasFanoCompressedList();
115       return;
116     }
117
118     DCHECK(std::is_sorted(list, list + size));
119
120     const ValueType upperBound = list[size - 1];
121     uint8_t numLowerBits = defaultNumLowerBits(upperBound, size);
122
123     // This is detail::writeBits56 limitation.
124     numLowerBits = std::min<uint8_t>(numLowerBits, 56);
125     CHECK_LT(numLowerBits, 8 * sizeof(Value));  // As we shift by numLowerBits.
126
127     // WARNING: Current read/write logic assumes that the 7 bytes
128     // following the last byte of lower and upper sequences are
129     // readable (stored value doesn't matter and won't be changed),
130     // so we allocate additional 7B, but do not include them in size
131     // of returned value.
132
133     // *** Lower bits.
134     const size_t lowerSize = (numLowerBits * size + 7) / 8;
135     unsigned char* const lower =
136       static_cast<unsigned char*>(calloc(lowerSize + 7, 1));
137     const ValueType lowerMask = (ValueType(1) << numLowerBits) - 1;
138     for (size_t i = 0; i < size; ++i) {
139       const ValueType lowerBits = list[i] & lowerMask;
140       writeBits56(lower, i * numLowerBits, numLowerBits, lowerBits);
141     }
142
143     // *** Upper bits.
144     // Upper bits are stored using unary delta encoding.
145     // For example, (3 5 5 9) will be encoded as 1000011001000_2.
146     const size_t upperSizeBits =
147       (upperBound >> numLowerBits) +  // Number of 0-bits to be stored.
148       size;                           // 1-bits.
149     const size_t upperSize = (upperSizeBits + 7) / 8;
150     unsigned char* const upper =
151       static_cast<unsigned char*>(calloc(upperSize + 7, 1));
152     for (size_t i = 0; i < size; ++i) {
153       const ValueType upperBits = list[i] >> numLowerBits;
154       const size_t pos = upperBits + i;  // upperBits 0-bits and (i + 1) 1-bits.
155       upper[pos / 8] |= 1U << (pos % 8);
156     }
157
158     // *** Skip pointers.
159     // Store (1-indexed) position of every skipQuantum-th
160     // 0-bit in upper bits sequence.
161     SkipValueType* skipPointers = nullptr;
162     size_t numSkipPointers = 0;
163     /* static */ if (skipQuantum != 0) {
164       // Workaround to avoid 'division by zero' compile-time error.
165       constexpr size_t q = skipQuantum ?: 1;
166       CHECK_LT(upperSizeBits, std::numeric_limits<SkipValueType>::max());
167       // 8 * upperSize is used here instead of upperSizeBits, as that is
168       // more serialization-friendly way.
169       numSkipPointers = (8 * upperSize - size) / q;
170       skipPointers = static_cast<SkipValueType*>(
171           numSkipPointers == 0
172             ? nullptr
173             : calloc(numSkipPointers, sizeof(SkipValueType)));
174
175       for (size_t i = 0, pos = 0; i < size; ++i) {
176         const ValueType upperBits = list[i] >> numLowerBits;
177         for (; (pos + 1) * q <= upperBits; ++pos) {
178           skipPointers[pos] = i + (pos + 1) * q;
179         }
180       }
181     }
182
183     // *** Forward pointers.
184     // Store (1-indexed) position of every forwardQuantum-th
185     // 1-bit in upper bits sequence.
186     SkipValueType* forwardPointers = nullptr;
187     size_t numForwardPointers = 0;
188     /* static */ if (forwardQuantum != 0) {
189       // Workaround to avoid 'division by zero' compile-time error.
190       constexpr size_t q = forwardQuantum ?: 1;
191       CHECK_LT(upperSizeBits, std::numeric_limits<SkipValueType>::max());
192
193       numForwardPointers = size / q;
194       forwardPointers = static_cast<SkipValueType*>(
195         numForwardPointers == 0
196           ? nullptr
197           : malloc(numForwardPointers * sizeof(SkipValueType)));
198
199       for (size_t i = q - 1, pos = 0; i < size; i += q, ++pos) {
200         const ValueType upperBits = list[i] >> numLowerBits;
201         forwardPointers[pos] = upperBits + i + 1;
202       }
203     }
204
205     // *** Result.
206     result.size = size;
207     result.numLowerBits = numLowerBits;
208     result.lower.reset(lower, lowerSize);
209     result.upper.reset(upper, upperSize);
210     result.skipPointers.reset(
211         reinterpret_cast<unsigned char*>(skipPointers),
212         numSkipPointers * sizeof(SkipValueType));
213     result.forwardPointers.reset(
214         reinterpret_cast<unsigned char*>(forwardPointers),
215         numForwardPointers * sizeof(SkipValueType));
216   }
217
218  private:
219   // Writes value (with len up to 56 bits) to data starting at pos-th bit.
220   static void writeBits56(unsigned char* data, size_t pos,
221                           uint8_t len, uint64_t value) {
222     DCHECK_LE(uint32_t(len), 56);
223     DCHECK_EQ(0, value & ~((uint64_t(1) << len) - 1));
224     unsigned char* const ptr = data + (pos / 8);
225     uint64_t ptrv = folly::loadUnaligned<uint64_t>(ptr);
226     ptrv |=  value << (pos % 8);
227     folly::storeUnaligned<uint64_t>(ptr, ptrv);
228   }
229 };
230
231 // NOTE: It's recommended to compile EF coding with -msse4.2, starting
232 // with Nehalem, Intel CPUs support POPCNT instruction and gcc will emit
233 // it for __builtin_popcountll intrinsic.
234 // But we provide an alternative way for the client code: it can switch to
235 // the appropriate version of EliasFanoReader<> in realtime (client should
236 // implement this switching logic itself) by specifying instruction set to
237 // use explicitly.
238 namespace instructions {
239
240 struct Default {
241   static bool supported() {
242     return true;
243   }
244   static inline uint64_t popcount(uint64_t value) {
245     return __builtin_popcountll(value);
246   }
247   static inline int ctz(uint64_t value) {
248     DCHECK_GT(value, 0);
249     return __builtin_ctzll(value);
250   }
251 };
252
253 struct Fast : public Default {
254   static bool supported() {
255     folly::CpuId cpuId;
256     return cpuId.popcnt();
257   }
258   static inline uint64_t popcount(uint64_t value) {
259     uint64_t result;
260     asm ("popcntq %1, %0" : "=r" (result) : "r" (value));
261     return result;
262   }
263 };
264
265 }  // namespace instructions
266
267 namespace detail {
268
269 template <class CompressedList, class Instructions>
270 class UpperBitsReader {
271   typedef typename CompressedList::SkipValueType SkipValueType;
272  public:
273   typedef typename CompressedList::ValueType ValueType;
274
275   explicit UpperBitsReader(const CompressedList& list)
276     : forwardPointers_(list.forwardPointers.data()),
277       skipPointers_(list.skipPointers.data()),
278       start_(list.upper.data()),
279       block_(start_ != nullptr ? folly::loadUnaligned<block_t>(start_) : 0),
280       outer_(0),  // outer offset: number of consumed bytes in upper.
281       inner_(-1),  // inner offset: (bit) position in current block.
282       position_(-1),  // index of current value (= #reads - 1).
283       value_(0) { }
284
285   size_t position() const { return position_; }
286   ValueType value() const { return value_; }
287
288   ValueType next() {
289     // Skip to the first non-zero block.
290     while (block_ == 0) {
291       outer_ += sizeof(block_t);
292       block_ = folly::loadUnaligned<block_t>(start_ + outer_);
293     }
294
295     ++position_;
296     inner_ = Instructions::ctz(block_);
297     block_ &= block_ - 1;
298
299     return setValue();
300   }
301
302   ValueType skip(size_t n) {
303     DCHECK_GT(n, 0);
304
305     position_ += n;  // n 1-bits will be read.
306
307     // Use forward pointer.
308     if (CompressedList::forwardQuantum > 0 &&
309         n > CompressedList::forwardQuantum) {
310       // Workaround to avoid 'division by zero' compile-time error.
311       constexpr size_t q = CompressedList::forwardQuantum ?: 1;
312
313       const size_t steps = position_ / q;
314       const size_t dest =
315         folly::loadUnaligned<SkipValueType>(
316             forwardPointers_ + (steps - 1) * sizeof(SkipValueType));
317
318       reposition(dest);
319       n = position_ + 1 - steps * q;  // n is > 0.
320       // correct inner_ will be set at the end.
321     }
322
323     size_t cnt;
324     // Find necessary block.
325     while ((cnt = Instructions::popcount(block_)) < n) {
326       n -= cnt;
327       outer_ += sizeof(block_t);
328       block_ = folly::loadUnaligned<block_t>(start_ + outer_);
329     }
330
331     // NOTE: Trying to skip half-block here didn't show any
332     // performance improvements.
333
334     DCHECK_GT(n, 0);
335
336     // Kill n - 1 least significant 1-bits.
337     for (size_t i = 0; i < n - 1; ++i) {
338       block_ &= block_ - 1;
339     }
340
341     inner_ = Instructions::ctz(block_);
342     block_ &= block_ - 1;
343
344     return setValue();
345   }
346
347   // Skip to the first element that is >= v and located *after* the current
348   // one (so even if current value equals v, position will be increased by 1).
349   ValueType skipToNext(ValueType v) {
350     DCHECK_GE(v, value_);
351
352     // Use skip pointer.
353     if (CompressedList::skipQuantum > 0 &&
354         v >= value_ + CompressedList::skipQuantum) {
355       // Workaround to avoid 'division by zero' compile-time error.
356       constexpr size_t q = CompressedList::skipQuantum ?: 1;
357
358       const size_t steps = v / q;
359       const size_t dest =
360         folly::loadUnaligned<SkipValueType>(
361             skipPointers_ + (steps - 1) * sizeof(SkipValueType));
362
363       reposition(dest);
364       position_ = dest - q * steps - 1;
365       // Correct inner_ and value_ will be set during the next()
366       // call at the end.
367
368       // NOTE: Corresponding block of lower bits sequence may be
369       // prefetched here (via __builtin_prefetch), but experiments
370       // didn't show any significant improvements.
371     }
372
373     // Skip by blocks.
374     size_t cnt;
375     size_t skip = v - (8 * outer_ - position_ - 1);
376
377     constexpr size_t kBitsPerBlock = 8 * sizeof(block_t);
378     while ((cnt = Instructions::popcount(~block_)) < skip) {
379       skip -= cnt;
380       position_ += kBitsPerBlock - cnt;
381       outer_ += sizeof(block_t);
382       block_ = folly::loadUnaligned<block_t>(start_ + outer_);
383     }
384
385     // Try to skip half-block.
386     constexpr size_t kBitsPerHalfBlock = 4 * sizeof(block_t);
387     constexpr block_t halfBlockMask = (block_t(1) << kBitsPerHalfBlock) - 1;
388     if ((cnt = Instructions::popcount(~block_ & halfBlockMask)) < skip) {
389       position_ += kBitsPerHalfBlock - cnt;
390       block_ &= ~halfBlockMask;
391     }
392
393     // Just skip until we see expected value.
394     while (next() < v) { }
395     return value_;
396   }
397
398  private:
399   ValueType setValue() {
400     value_ = static_cast<ValueType>(8 * outer_ + inner_ - position_);
401     return value_;
402   }
403
404   void reposition(size_t dest) {
405     outer_ = dest / 8;
406     block_ = folly::loadUnaligned<block_t>(start_ + outer_);
407     block_ &= ~((block_t(1) << (dest % 8)) - 1);
408   }
409
410   typedef unsigned long long block_t;
411   const unsigned char* const forwardPointers_;
412   const unsigned char* const skipPointers_;
413   const unsigned char* const start_;
414   block_t block_;
415   size_t outer_;
416   size_t inner_;
417   size_t position_;
418   ValueType value_;
419 };
420
421 }  // namespace detail
422
423 template <class CompressedList,
424           class Instructions = instructions::Default>
425 class EliasFanoReader : private boost::noncopyable {
426  public:
427   typedef typename CompressedList::ValueType ValueType;
428
429   explicit EliasFanoReader(const CompressedList& list)
430     : list_(list),
431       lowerMask_((ValueType(1) << list_.numLowerBits) - 1),
432       upper_(list),
433       progress_(0),
434       value_(0) {
435     DCHECK(Instructions::supported());
436     // To avoid extra branching during skipTo() while reading
437     // upper sequence we need to know the last element.
438     if (UNLIKELY(list_.size == 0)) {
439       lastValue_ = 0;
440       return;
441     }
442     ValueType lastUpperValue = 8 * list_.upper.size() - list_.size;
443     auto it = list_.upper.end() - 1;
444     DCHECK_NE(*it, 0);
445     lastUpperValue -= 8 - folly::findLastSet(*it);
446     lastValue_ = readLowerPart(list_.size - 1) |
447                  (lastUpperValue << list_.numLowerBits);
448   }
449
450   size_t size() const { return list_.size; }
451
452   size_t position() const { return progress_ - 1; }
453   ValueType value() const { return value_; }
454
455   bool next() {
456     if (UNLIKELY(progress_ == list_.size)) {
457       value_ = std::numeric_limits<ValueType>::max();
458       return false;
459     }
460     value_ = readLowerPart(progress_) |
461              (upper_.next() << list_.numLowerBits);
462     ++progress_;
463     return true;
464   }
465
466   bool skip(size_t n) {
467     CHECK_GT(n, 0);
468
469     progress_ += n - 1;
470     if (LIKELY(progress_ < list_.size)) {
471       value_ = readLowerPart(progress_) |
472                (upper_.skip(n) << list_.numLowerBits);
473       ++progress_;
474       return true;
475     }
476
477     progress_ = list_.size;
478     value_ = std::numeric_limits<ValueType>::max();
479     return false;
480   }
481
482   bool skipTo(ValueType value) {
483     DCHECK_GE(value, value_);
484     if (value <= value_) {
485       return true;
486     }
487     if (value > lastValue_) {
488       progress_ = list_.size;
489       value_ = std::numeric_limits<ValueType>::max();
490       return false;
491     }
492
493     upper_.skipToNext(value >> list_.numLowerBits);
494     progress_ = upper_.position();
495     value_ = readLowerPart(progress_) |
496              (upper_.value() << list_.numLowerBits);
497     ++progress_;
498     while (value_ < value) {
499       value_ = readLowerPart(progress_) |
500                (upper_.next() << list_.numLowerBits);
501       ++progress_;
502     }
503
504     return true;
505   }
506
507  private:
508   ValueType readLowerPart(size_t i) const {
509     const size_t pos = i * list_.numLowerBits;
510     const unsigned char* ptr = list_.lower.data() + (pos / 8);
511     const uint64_t ptrv = folly::loadUnaligned<uint64_t>(ptr);
512     return lowerMask_ & (ptrv >> (pos % 8));
513   }
514
515   const CompressedList list_;
516   const ValueType lowerMask_;
517   detail::UpperBitsReader<CompressedList, Instructions> upper_;
518   size_t progress_;
519   ValueType value_;
520   ValueType lastValue_;
521 };
522
523 }}  // namespaces
524
525 #endif  // FOLLY_EXPERIMENTAL_ELIAS_FANO_CODING_H