blob: 74d747fc9059f135cc2986b9b73f6ce473391534 [file] [log] [blame]
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001// 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#include "src/base/bits.h"
Emily Bernierd0a1eb72015-03-24 16:35:39 -04006
7#include <limits>
8
Ben Murdochb8a8cc12014-11-26 15:28:44 +00009#include "src/base/logging.h"
10
11namespace v8 {
12namespace base {
13namespace bits {
14
15uint32_t RoundUpToPowerOfTwo32(uint32_t value) {
16 DCHECK_LE(value, 0x80000000u);
17 value = value - 1;
18 value = value | (value >> 1);
19 value = value | (value >> 2);
20 value = value | (value >> 4);
21 value = value | (value >> 8);
22 value = value | (value >> 16);
23 return value + 1;
24}
25
Emily Bernierd0a1eb72015-03-24 16:35:39 -040026
27int32_t SignedMulHigh32(int32_t lhs, int32_t rhs) {
28 int64_t const value = static_cast<int64_t>(lhs) * static_cast<int64_t>(rhs);
29 return bit_cast<int32_t, uint32_t>(bit_cast<uint64_t>(value) >> 32u);
30}
31
32
33int32_t SignedMulHighAndAdd32(int32_t lhs, int32_t rhs, int32_t acc) {
34 return bit_cast<int32_t>(bit_cast<uint32_t>(acc) +
35 bit_cast<uint32_t>(SignedMulHigh32(lhs, rhs)));
36}
37
38
39int32_t SignedDiv32(int32_t lhs, int32_t rhs) {
40 if (rhs == 0) return 0;
41 if (rhs == -1) return -lhs;
42 return lhs / rhs;
43}
44
45
46int32_t SignedMod32(int32_t lhs, int32_t rhs) {
47 if (rhs == 0 || rhs == -1) return 0;
48 return lhs % rhs;
49}
50
Ben Murdochb8a8cc12014-11-26 15:28:44 +000051} // namespace bits
52} // namespace base
53} // namespace v8