P4C
The P4 Compiler
Loading...
Searching...
No Matches
bitops.h
1/*
2Copyright 2013-present Barefoot Networks, Inc.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17#ifndef LIB_BITOPS_H_
18#define LIB_BITOPS_H_
19
20#include <limits.h>
21
22#include "bitvec.h"
23
24namespace P4 {
25
26static inline unsigned bitcount(unsigned v) {
27#if defined(__GNUC__) || defined(__clang__)
28 unsigned rv = __builtin_popcount(v);
29#else
30 unsigned rv = 0;
31 while (v) {
32 v &= v - 1;
33 ++rv;
34 }
35#endif
36 return rv;
37}
38
39static inline int floor_log2(unsigned v) {
40 int rv = -1;
41#if defined(__GNUC__) || defined(__clang__)
42 if (v) rv = CHAR_BIT * sizeof(unsigned) - __builtin_clz(v) - 1;
43#else
44 while (v) {
45 rv++;
46 v >>= 1;
47 }
48#endif
49 return rv;
50}
51
52static inline int ceil_log2(unsigned v) { return v ? floor_log2(v - 1) + 1 : -1; }
53
54static inline unsigned bitmask2bytemask(const bitvec &a) {
55 int max = a.max().index();
56 if (max < 0) return 0;
57 unsigned rv = 0;
58 for (unsigned i = 0; i <= max / 8U; i++)
59 if (a.getrange(i * 8, 8)) rv |= 1 << i;
60 return rv;
61}
62
63} // namespace P4
64
65#endif /* LIB_BITOPS_H_ */
TODO: this is not really specific to BMV2, it should reside somewhere else.
Definition applyOptionsPragmas.cpp:24