blob: 41af98f100a5d0daca01901c580200281a7359f8 [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 Wallez944b60f2017-05-29 11:33:33 -070017#include <intrin.h>
18
Corentin Wallezf07e3bd2017-04-20 14:38:20 -040019#include "Forward.h"
20
21namespace backend {
22
Corentin Wallez944b60f2017-05-29 11:33:33 -070023 uint32_t ScanForward(uint32_t bits) {
Corentin Wallezf07e3bd2017-04-20 14:38:20 -040024 ASSERT(bits != 0);
Corentin Wallez944b60f2017-05-29 11:33:33 -070025 #if defined(_WIN32) || defined(_WIN64)
26 unsigned long firstBitIndex = 0ul;
27 unsigned char ret = _BitScanForward(&firstBitIndex, bits);
28 ASSERT(ret != 0);
29 return firstBitIndex;
30 #else
31 return static_cast<unsigned long>(__builtin_ctz(bits));
32 #endif
Corentin Wallezf07e3bd2017-04-20 14:38:20 -040033 }
34
35 uint32_t Log2(uint32_t value) {
36 ASSERT(value != 0);
Corentin Wallez944b60f2017-05-29 11:33:33 -070037 #if defined(_WIN32) || defined(_WIN64)
38 unsigned long firstBitIndex = 0ul;
39 unsigned char ret = _BitScanReverse(&firstBitIndex, value);
40 ASSERT(ret != 0);
41 return firstBitIndex;
42 #else
43 return 31 - __builtin_clz(value);
44 #endif
Corentin Wallezf07e3bd2017-04-20 14:38:20 -040045 }
46
47 bool IsPowerOfTwo(size_t n) {
48 ASSERT(n != 0);
49 return (n & (n - 1)) == 0;
50 }
51
52 bool IsAligned(const void* ptr, size_t alignment) {
53 ASSERT(IsPowerOfTwo(alignment));
54 ASSERT(alignment != 0);
55 return (reinterpret_cast<intptr_t>(ptr) & (alignment - 1)) == 0;
56 }
57
58 void* AlignVoidPtr(void* ptr, size_t alignment) {
59 ASSERT(alignment != 0);
60 return reinterpret_cast<void*>((reinterpret_cast<intptr_t>(ptr) + (alignment - 1)) & ~(alignment - 1));
61 }
62
63}