Jlm
Loading...
Searching...
No Matches
Math.hpp
Go to the documentation of this file.
1/*
2 * Copyright 2023 HÃ¥vard Krogstie <krogstie.havard@gmail.com>
3 * See COPYING for terms of redistribution.
4 */
5
6#ifndef JLM_UTIL_MATH_HPP
7#define JLM_UTIL_MATH_HPP
8
9#include <jlm/util/common.hpp>
10
11#include <cstdint>
12#include <type_traits>
13
14namespace jlm::util
15{
16
26template<class T>
27static constexpr int
28log2Floor(T value)
29{
30 static_assert(std::is_integral_v<T>, "T must be integral type");
31 if (value < 1)
32 return -1;
33
34 return 1 + log2Floor(value >> 1);
35}
36
49template<class T>
50static constexpr T
52{
53 // 2^0 == 1 is the lowest possible power of two
54 if (value <= 1)
55 return 1;
56
57 return T(1) << (log2Floor(value - 1) + 1);
58}
59
73template<class T>
74static constexpr T
75RoundUpToMultipleOf(T value, T multiple)
76{
77 const auto miss = value % multiple;
78 if (miss < 0)
79 return value - miss;
80 if (miss == 0)
81 return value;
82 return value + multiple - miss;
83}
84
95template<class T>
96static constexpr int
98{
99 using UnsignedT = std::make_unsigned_t<T>;
100 return log2Floor(static_cast<UnsignedT>(value)) + 1;
101}
102
108template<class T>
109static constexpr int
110BitWidthOfEnum(T endValue)
111{
112 static_assert(std::is_enum_v<T>, "BitWidthOfEnum only takes enums");
113
114 using UnderlyingT = std::underlying_type_t<T>;
115
116 // To appease gcc warnings, the returned bit width is large enough to hold the endValue as well,
117 // even if it is just a sentinel COUNT value
118 return BitsRequiredToRepresent(static_cast<UnderlyingT>(endValue));
119}
120
133inline int64_t
134truncateAndSignExtend(int64_t value, uint64_t keepBits)
135{
136 JLM_ASSERT(keepBits <= 64);
137 const auto extendBits = 64 - keepBits;
138
139 // Shift signed value left and right again to sign extend
140 return (value << extendBits) >> extendBits;
141}
142
155inline int64_t
156truncateAndZeroExtend(int64_t value, uint64_t keepBits)
157{
158 JLM_ASSERT(keepBits <= 64);
159 const auto extendBits = 64 - keepBits;
160
161 // Shift unsigned value left and right again to zero extend
162 return (static_cast<uint64_t>(value) << extendBits) >> extendBits;
163}
164
165}
166
167#endif // JLM_UTIL_MATH_HPP
#define JLM_ASSERT(x)
Definition common.hpp:16
static constexpr T RoundUpToMultipleOf(T value, T multiple)
Definition Math.hpp:75
static constexpr T RoundUpToPowerOf2(T value)
Definition Math.hpp:51
static constexpr int BitsRequiredToRepresent(T value)
Definition Math.hpp:97
int64_t truncateAndZeroExtend(int64_t value, uint64_t keepBits)
Definition Math.hpp:156
static constexpr int BitWidthOfEnum(T endValue)
Definition Math.hpp:110
int64_t truncateAndSignExtend(int64_t value, uint64_t keepBits)
Definition Math.hpp:134
static constexpr int log2Floor(T value)
Definition Math.hpp:28