clzll.h Source File

clzll.h Source File#

Composable Kernel: clzll.h Source File
clzll.h
Go to the documentation of this file.
1// Tencent is pleased to support the open source community by making RapidJSON available.
2//
3// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip.
4//
5// Licensed under the MIT License (the "License"); you may not use this file except
6// in compliance with the License. You may obtain a copy of the License at
7//
8// http://opensource.org/licenses/MIT
9//
10// Unless required by applicable law or agreed to in writing, software distributed
11// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
12// CONDITIONS OF ANY KIND, either express or implied. See the License for the
13// specific language governing permissions and limitations under the License.
14
15#ifndef RAPIDJSON_CLZLL_H_
16#define RAPIDJSON_CLZLL_H_
17
18#include "../rapidjson.h"
19
20#if defined(_MSC_VER) && !defined(UNDER_CE)
21#include <intrin.h>
22#if defined(_WIN64)
23#pragma intrinsic(_BitScanReverse64)
24#else
25#pragma intrinsic(_BitScanReverse)
26#endif
27#endif
28
30namespace internal {
31
33{
34 // Passing 0 to __builtin_clzll is UB in GCC and results in an
35 // infinite loop in the software implementation.
36 RAPIDJSON_ASSERT(x != 0);
37
38#if defined(_MSC_VER) && !defined(UNDER_CE)
39 unsigned long r = 0;
40#if defined(_WIN64)
41 _BitScanReverse64(&r, x);
42#else
43 // Scan the high 32 bits.
44 if(_BitScanReverse(&r, static_cast<uint32_t>(x >> 32)))
45 return 63 - (r + 32);
46
47 // Scan the low 32 bits.
48 _BitScanReverse(&r, static_cast<uint32_t>(x & 0xFFFFFFFF));
49#endif // _WIN64
50
51 return 63 - r;
52#elif(defined(__GNUC__) && __GNUC__ >= 4) || RAPIDJSON_HAS_BUILTIN(__builtin_clzll)
53 // __builtin_clzll wrapper
54 return static_cast<uint32_t>(__builtin_clzll(x));
55#else
56 // naive version
57 uint32_t r = 0;
58 while(!(x & (static_cast<uint64_t>(1) << 63)))
59 {
60 x <<= 1;
61 ++r;
62 }
63
64 return r;
65#endif // _MSC_VER
66}
67
68#define RAPIDJSON_CLZLL RAPIDJSON_NAMESPACE::internal::clzll
69
70} // namespace internal
72
73#endif // RAPIDJSON_CLZLL_H_
#define RAPIDJSON_ASSERT(x)
Assertion.
Definition rapidjson.h:451
#define RAPIDJSON_NAMESPACE_BEGIN
provide custom rapidjson namespace (opening expression)
Definition rapidjson.h:121
#define RAPIDJSON_NAMESPACE_END
provide custom rapidjson namespace (closing expression)
Definition rapidjson.h:124
Definition allocators.h:459
uint32_t clzll(uint64_t x)
Definition clzll.h:32
common definitions and configuration
unsigned int uint32_t
Definition stdint.h:126
unsigned __int64 uint64_t
Definition stdint.h:136