Line data Source code
1 : // Copyright 2014 the V8 project authors. All rights reserved.
2 : // Use of this source code is governed by a BSD-style license that can be
3 : // found in the LICENSE file.
4 :
5 : #ifndef V8_BASE_DIVISION_BY_CONSTANT_H_
6 : #define V8_BASE_DIVISION_BY_CONSTANT_H_
7 :
8 : #include <stdint.h>
9 :
10 : #include "src/base/base-export.h"
11 :
12 : namespace v8 {
13 : namespace base {
14 :
15 : // ----------------------------------------------------------------------------
16 :
17 : // The magic numbers for division via multiplication, see Warren's "Hacker's
18 : // Delight", chapter 10. The template parameter must be one of the unsigned
19 : // integral types.
20 : template <class T>
21 : struct V8_BASE_EXPORT MagicNumbersForDivision {
22 0 : MagicNumbersForDivision(T m, unsigned s, bool a)
23 1686 : : multiplier(m), shift(s), add(a) {}
24 0 : bool operator==(const MagicNumbersForDivision& rhs) const {
25 328 : return multiplier == rhs.multiplier && shift == rhs.shift && add == rhs.add;
26 : }
27 :
28 : T multiplier;
29 : unsigned shift;
30 : bool add;
31 : };
32 :
33 :
34 : // Calculate the multiplier and shift for signed division via multiplication.
35 : // The divisor must not be -1, 0 or 1 when interpreted as a signed value.
36 : template <class T>
37 : V8_BASE_EXPORT MagicNumbersForDivision<T> SignedDivisionByConstant(T d);
38 :
39 : // Calculate the multiplier and shift for unsigned division via multiplication,
40 : // see Warren's "Hacker's Delight", chapter 10. The divisor must not be 0 and
41 : // leading_zeros can be used to speed up the calculation if the given number of
42 : // upper bits of the dividend value are known to be zero.
43 : template <class T>
44 : V8_BASE_EXPORT MagicNumbersForDivision<T> UnsignedDivisionByConstant(
45 : T d, unsigned leading_zeros = 0);
46 :
47 : extern template V8_BASE_EXPORT MagicNumbersForDivision<uint32_t>
48 : SignedDivisionByConstant(uint32_t d);
49 : extern template V8_BASE_EXPORT MagicNumbersForDivision<uint64_t>
50 : SignedDivisionByConstant(uint64_t d);
51 :
52 : extern template V8_BASE_EXPORT MagicNumbersForDivision<uint32_t>
53 : UnsignedDivisionByConstant(uint32_t d, unsigned leading_zeros);
54 : extern template V8_BASE_EXPORT MagicNumbersForDivision<uint64_t>
55 : UnsignedDivisionByConstant(uint64_t d, unsigned leading_zeros);
56 :
57 : } // namespace base
58 : } // namespace v8
59 :
60 : #endif // V8_BASE_DIVISION_BY_CONSTANT_H_
|