P4C
The P4 Compiler
Loading...
Searching...
No Matches
bitops.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_BITOPS_H_
9#define LIB_BITOPS_H_
10
11#include <limits.h>
12
13#include "bitvec.h"
14
15namespace P4 {
16
17static inline unsigned bitcount(unsigned v) {
18#if defined(__GNUC__) || defined(__clang__)
19 unsigned rv = __builtin_popcount(v);
20#else
21 unsigned rv = 0;
22 while (v) {
23 v &= v - 1;
24 ++rv;
25 }
26#endif
27 return rv;
28}
29
30static inline int floor_log2(unsigned v) {
31 int rv = -1;
32#if defined(__GNUC__) || defined(__clang__)
33 if (v) rv = CHAR_BIT * sizeof(unsigned) - __builtin_clz(v) - 1;
34#else
35 while (v) {
36 rv++;
37 v >>= 1;
38 }
39#endif
40 return rv;
41}
42
43static inline int ceil_log2(unsigned v) { return v ? floor_log2(v - 1) + 1 : -1; }
44
45static inline unsigned bitmask2bytemask(const bitvec &a) {
46 int max = a.max().index();
47 if (max < 0) return 0;
48 unsigned rv = 0;
49 for (unsigned i = 0; i <= max / 8U; i++)
50 if (a.getrange(i * 8, 8)) rv |= 1 << i;
51 return rv;
52}
53
54} // namespace P4
55
56#endif /* LIB_BITOPS_H_ */
Definition bitvec.h:111
TODO: this is not really specific to BMV2, it should reside somewhere else.
Definition applyOptionsPragmas.cpp:13