blob: ec9b3e91deb9573d410bbfeb945a8dc6ff1f7671 [file] [log] [blame]
Corentin Wallezf07e3bd2017-04-20 14:38:20 -04001// Copyright 2017 The NXT Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Corentin Wallezfffe6df2017-07-06 14:41:13 -040015#include "common/Math.h"
Corentin Wallezf07e3bd2017-04-20 14:38:20 -040016
Corentin Wallez40fb17d2017-05-30 18:02:38 -040017#if defined(_WIN32) || defined(_WIN64)
18 #include <intrin.h>
19#endif
Corentin Wallez944b60f2017-05-29 11:33:33 -070020
Corentin Wallezfffe6df2017-07-06 14:41:13 -040021#include <cassert>
22#define ASSERT assert
Corentin Wallezf07e3bd2017-04-20 14:38:20 -040023
24namespace backend {
25
Corentin Wallez944b60f2017-05-29 11:33:33 -070026 uint32_t ScanForward(uint32_t bits) {
Corentin Wallezf07e3bd2017-04-20 14:38:20 -040027 ASSERT(bits != 0);
Corentin Wallez944b60f2017-05-29 11:33:33 -070028 #if defined(_WIN32) || defined(_WIN64)
29 unsigned long firstBitIndex = 0ul;
30 unsigned char ret = _BitScanForward(&firstBitIndex, bits);
31 ASSERT(ret != 0);
32 return firstBitIndex;
33 #else
34 return static_cast<unsigned long>(__builtin_ctz(bits));
35 #endif
Corentin Wallezf07e3bd2017-04-20 14:38:20 -040036 }
37
38 uint32_t Log2(uint32_t value) {
39 ASSERT(value != 0);
Corentin Wallez944b60f2017-05-29 11:33:33 -070040 #if defined(_WIN32) || defined(_WIN64)
41 unsigned long firstBitIndex = 0ul;
42 unsigned char ret = _BitScanReverse(&firstBitIndex, value);
43 ASSERT(ret != 0);
44 return firstBitIndex;
45 #else
46 return 31 - __builtin_clz(value);
47 #endif
Corentin Wallezf07e3bd2017-04-20 14:38:20 -040048 }
49
50 bool IsPowerOfTwo(size_t n) {
51 ASSERT(n != 0);
52 return (n & (n - 1)) == 0;
53 }
54
55 bool IsAligned(const void* ptr, size_t alignment) {
56 ASSERT(IsPowerOfTwo(alignment));
57 ASSERT(alignment != 0);
58 return (reinterpret_cast<intptr_t>(ptr) & (alignment - 1)) == 0;
59 }
60
61 void* AlignVoidPtr(void* ptr, size_t alignment) {
62 ASSERT(alignment != 0);
63 return reinterpret_cast<void*>((reinterpret_cast<intptr_t>(ptr) + (alignment - 1)) & ~(alignment - 1));
64 }
65
66}