blob: 874aee0ba68fe74aaaaafe9005c93ffeeabd1cea [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
15#include "Math.h"
16
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 Wallezf07e3bd2017-04-20 14:38:20 -040021#include "Forward.h"
22
23namespace backend {
24
Corentin Wallez944b60f2017-05-29 11:33:33 -070025 uint32_t ScanForward(uint32_t bits) {
Corentin Wallezf07e3bd2017-04-20 14:38:20 -040026 ASSERT(bits != 0);
Corentin Wallez944b60f2017-05-29 11:33:33 -070027 #if defined(_WIN32) || defined(_WIN64)
28 unsigned long firstBitIndex = 0ul;
29 unsigned char ret = _BitScanForward(&firstBitIndex, bits);
30 ASSERT(ret != 0);
31 return firstBitIndex;
32 #else
33 return static_cast<unsigned long>(__builtin_ctz(bits));
34 #endif
Corentin Wallezf07e3bd2017-04-20 14:38:20 -040035 }
36
37 uint32_t Log2(uint32_t value) {
38 ASSERT(value != 0);
Corentin Wallez944b60f2017-05-29 11:33:33 -070039 #if defined(_WIN32) || defined(_WIN64)
40 unsigned long firstBitIndex = 0ul;
41 unsigned char ret = _BitScanReverse(&firstBitIndex, value);
42 ASSERT(ret != 0);
43 return firstBitIndex;
44 #else
45 return 31 - __builtin_clz(value);
46 #endif
Corentin Wallezf07e3bd2017-04-20 14:38:20 -040047 }
48
49 bool IsPowerOfTwo(size_t n) {
50 ASSERT(n != 0);
51 return (n & (n - 1)) == 0;
52 }
53
54 bool IsAligned(const void* ptr, size_t alignment) {
55 ASSERT(IsPowerOfTwo(alignment));
56 ASSERT(alignment != 0);
57 return (reinterpret_cast<intptr_t>(ptr) & (alignment - 1)) == 0;
58 }
59
60 void* AlignVoidPtr(void* ptr, size_t alignment) {
61 ASSERT(alignment != 0);
62 return reinterpret_cast<void*>((reinterpret_cast<intptr_t>(ptr) + (alignment - 1)) & ~(alignment - 1));
63 }
64
65}