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#include "src/base/export-template.h" 12 13namespace v8 { 14namespace base { 15 16// ---------------------------------------------------------------------------- 17 18// The magic numbers for division via multiplication, see Warren's "Hacker's 19// Delight", chapter 10. The template parameter must be one of the unsigned 20// integral types. 21template <class T> 22struct EXPORT_TEMPLATE_DECLARE(V8_BASE_EXPORT) MagicNumbersForDivision { 23 MagicNumbersForDivision(T m, unsigned s, bool a) 24 : multiplier(m), shift(s), add(a) {} 25 bool operator==(const MagicNumbersForDivision& rhs) const { 26 return multiplier == rhs.multiplier && shift == rhs.shift && add == rhs.add; 27 } 28 29 T multiplier; 30 unsigned shift; 31 bool add; 32}; 33 34 35// Calculate the multiplier and shift for signed division via multiplication. 36// The divisor must not be -1, 0 or 1 when interpreted as a signed value. 37template <class T> 38EXPORT_TEMPLATE_DECLARE(V8_BASE_EXPORT) 39MagicNumbersForDivision<T> SignedDivisionByConstant(T d); 40 41// Calculate the multiplier and shift for unsigned division via multiplication, 42// see Warren's "Hacker's Delight", chapter 10. The divisor must not be 0 and 43// leading_zeros can be used to speed up the calculation if the given number of 44// upper bits of the dividend value are known to be zero. 45template <class T> 46EXPORT_TEMPLATE_DECLARE(V8_BASE_EXPORT) 47MagicNumbersForDivision<T> UnsignedDivisionByConstant( 48 T d, unsigned leading_zeros = 0); 49 50// Explicit instantiation declarations. 51extern template struct EXPORT_TEMPLATE_DECLARE(V8_BASE_EXPORT) 52 MagicNumbersForDivision<uint32_t>; 53extern template struct EXPORT_TEMPLATE_DECLARE(V8_BASE_EXPORT) 54 MagicNumbersForDivision<uint64_t>; 55 56extern template EXPORT_TEMPLATE_DECLARE(V8_BASE_EXPORT) 57 MagicNumbersForDivision<uint32_t> SignedDivisionByConstant(uint32_t d); 58extern template EXPORT_TEMPLATE_DECLARE(V8_BASE_EXPORT) 59 MagicNumbersForDivision<uint64_t> SignedDivisionByConstant(uint64_t d); 60 61extern template EXPORT_TEMPLATE_DECLARE(V8_BASE_EXPORT) 62 MagicNumbersForDivision<uint32_t> UnsignedDivisionByConstant( 63 uint32_t d, unsigned leading_zeros); 64extern template EXPORT_TEMPLATE_DECLARE(V8_BASE_EXPORT) 65 MagicNumbersForDivision<uint64_t> UnsignedDivisionByConstant( 66 uint64_t d, unsigned leading_zeros); 67 68} // namespace base 69} // namespace v8 70 71#endif // V8_BASE_DIVISION_BY_CONSTANT_H_ 72