P4C
The P4 Compiler
Loading...
Searching...
No Matches
big_int_util.h
1/*
2 * SPDX-FileCopyrightText: 2013 Barefoot Networks, Inc.
3 * Copyright 2013-present Barefoot Networks, Inc.
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 */
7
8#ifndef LIB_BIG_INT_UTIL_H_
9#define LIB_BIG_INT_UTIL_H_
10
11#include "big_int.h"
12#include "hash.h"
13
14namespace P4::Util {
15
16// Useful functions for manipulating GMP values
17// (arbitrary-precision values)
18
19big_int ripBits(big_int &value, int bits);
20
21struct BitRange {
22 unsigned lowIndex;
23 unsigned highIndex;
24 big_int value;
25};
26
27// Find a consecutive scan of 1 bits at the "bottom"
28BitRange findOnes(const big_int &value);
29
30big_int cvtInt(const char *s, unsigned base);
31big_int shift_left(const big_int &v, unsigned bits);
32big_int shift_right(const big_int &v, unsigned bits);
33// Convert a slice [m:l] into a mask
34big_int maskFromSlice(unsigned m, unsigned l);
35big_int mask(unsigned bits);
36
37inline unsigned scan0_positive(const boost::multiprecision::cpp_int &val, unsigned pos) {
38 while (boost::multiprecision::bit_test(val, pos)) ++pos;
39 return pos;
40}
41inline unsigned scan1_positive(const boost::multiprecision::cpp_int &val, unsigned pos) {
42 if (val == 0 || pos > boost::multiprecision::msb(val)) return ~0U;
43 unsigned lsb = boost::multiprecision::lsb(val);
44 if (lsb >= pos) return lsb;
45 while (!boost::multiprecision::bit_test(val, pos)) ++pos;
46 return pos;
47}
48inline unsigned scan0(const boost::multiprecision::cpp_int &val, unsigned pos) {
49 if (val < 0) return scan1_positive(-val - 1, pos);
50 return scan0_positive(val, pos);
51}
52inline unsigned scan1(const boost::multiprecision::cpp_int &val, unsigned pos) {
53 if (val < 0) return scan0_positive(-val - 1, pos);
54 return scan1_positive(val, pos);
55}
56
57} // namespace P4::Util
58
59namespace P4 {
60
61static inline unsigned bitcount(big_int v) {
62 if (v < 0) return ~0U;
63 unsigned rv = 0;
64 while (v != 0) {
65 v &= v - 1;
66 ++rv;
67 }
68 return rv;
69}
70
71static inline int ffs(big_int v) {
72 if (v <= 0) return -1;
73 return boost::multiprecision::lsb(v);
74}
75
76static inline int floor_log2(big_int v) {
77 int rv = -1;
78 while (v > 0) {
79 rv++;
80 v /= 2;
81 }
82 return rv;
83}
84
85static inline int ceil_log2(big_int v) { return v ? floor_log2(v - 1) + 1 : -1; }
86
87template <>
88struct Util::Hasher<big_int> : Detail::StdHasher {};
89
90} // namespace P4
91
92#endif /* LIB_BIG_INT_UTIL_H_ */
Definition hash.h:90
TODO: this is not really specific to BMV2, it should reside somewhere else.
Definition applyOptionsPragmas.cpp:13
Definition big_int_util.h:21
Definition hash.h:123