bitunion.hh revision 10289
1/*
2 * Copyright (c) 2007-2008 The Regents of The University of Michigan
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 * Authors: Gabe Black
29 */
30
31#ifndef __BASE_BITUNION_HH__
32#define __BASE_BITUNION_HH__
33
34#include "base/bitfield.hh"
35#include "base/types.hh"
36
37//      The following implements the BitUnion system of defining bitfields
38//on top of an underlying class. This is done through the pervasive use of
39//both named and unnamed unions which all contain the same actual storage.
40//Since they're unioned with each other, all of these storage locations
41//overlap. This allows all of the bitfields to manipulate the same data
42//without having to have access to each other. More details are provided with
43//the individual components.
44
45//This namespace is for classes which implement the backend of the BitUnion
46//stuff. Don't use any of these directly, except for the Bitfield classes in
47//the *BitfieldTypes class(es).
48namespace BitfieldBackend
49{
50    //A base class for all bitfields. It instantiates the actual storage,
51    //and provides getBits and setBits functions for manipulating it. The
52    //Data template parameter is type of the underlying storage.
53    template<class Data>
54    class BitfieldBase
55    {
56      protected:
57        Data __data;
58
59        //This function returns a range of bits from the underlying storage.
60        //It relies on the "bits" function above. It's the user's
61        //responsibility to make sure that there is a properly overloaded
62        //version of this function for whatever type they want to overlay.
63        inline uint64_t
64        getBits(int first, int last) const
65        {
66            return bits(__data, first, last);
67        }
68
69        //Similar to the above, but for settings bits with replaceBits.
70        inline void
71        setBits(int first, int last, uint64_t val)
72        {
73            replaceBits(__data, first, last, val);
74        }
75    };
76
77    //This class contains all the "regular" bitfield classes. It is inherited
78    //by all BitUnions which give them access to those types.
79    template<class Type>
80    class RegularBitfieldTypes
81    {
82      protected:
83        //This class implements ordinary bitfields, that is a span of bits
84        //who's msb is "first", and who's lsb is "last".
85        template<int first, int last=first>
86        class Bitfield : public BitfieldBase<Type>
87        {
88            static_assert(first >= last,
89                          "Bitfield ranges must be specified as <msb, lsb>");
90
91          public:
92            operator const uint64_t () const
93            {
94                return this->getBits(first, last);
95            }
96
97            uint64_t
98            operator=(const uint64_t _data)
99            {
100                this->setBits(first, last, _data);
101                return _data;
102            }
103        };
104
105        //A class which specializes the above so that it can only be read
106        //from. This is accomplished explicitly making sure the assignment
107        //operator is blocked. The conversion operator is carried through
108        //inheritance. This will unfortunately need to be copied into each
109        //bitfield type due to limitations with how templates work
110        template<int first, int last=first>
111        class BitfieldRO : public Bitfield<first, last>
112        {
113          private:
114            uint64_t
115            operator=(const uint64_t _data);
116        };
117
118        //Similar to the above, but only allows writing.
119        template<int first, int last=first>
120        class BitfieldWO : public Bitfield<first, last>
121        {
122          private:
123            operator const uint64_t () const;
124
125          public:
126            using Bitfield<first, last>::operator=;
127        };
128    };
129
130    //This class contains all the "regular" bitfield classes. It is inherited
131    //by all BitUnions which give them access to those types.
132    template<class Type>
133    class SignedBitfieldTypes
134    {
135      protected:
136        //This class implements ordinary bitfields, that is a span of bits
137        //who's msb is "first", and who's lsb is "last".
138        template<int first, int last=first>
139        class SignedBitfield : public BitfieldBase<Type>
140        {
141          public:
142            operator const int64_t () const
143            {
144                return sext<first - last + 1>(this->getBits(first, last));
145            }
146
147            int64_t
148            operator=(const int64_t _data)
149            {
150                this->setBits(first, last, _data);
151                return _data;
152            }
153        };
154
155        //A class which specializes the above so that it can only be read
156        //from. This is accomplished explicitly making sure the assignment
157        //operator is blocked. The conversion operator is carried through
158        //inheritance. This will unfortunately need to be copied into each
159        //bitfield type due to limitations with how templates work
160        template<int first, int last=first>
161        class SignedBitfieldRO : public SignedBitfield<first, last>
162        {
163          private:
164            int64_t
165            operator=(const int64_t _data);
166        };
167
168        //Similar to the above, but only allows writing.
169        template<int first, int last=first>
170        class SignedBitfieldWO : public SignedBitfield<first, last>
171        {
172          private:
173            operator const int64_t () const;
174
175          public:
176            int64_t operator=(const int64_t _data)
177            {
178                *((SignedBitfield<first, last> *)this) = _data;
179                return _data;
180            }
181        };
182    };
183
184    template<class Type>
185    class BitfieldTypes : public RegularBitfieldTypes<Type>,
186                          public SignedBitfieldTypes<Type>
187    {};
188
189    //When a BitUnion is set up, an underlying class is created which holds
190    //the actual union. This class then inherits from it, and provids the
191    //implementations for various operators. Setting things up this way
192    //prevents having to redefine these functions in every different BitUnion
193    //type. More operators could be implemented in the future, as the need
194    //arises.
195    template <class Type, class Base>
196    class BitUnionOperators : public Base
197    {
198      public:
199        BitUnionOperators(Type const & _data)
200        {
201            Base::__data = _data;
202        }
203
204        BitUnionOperators() {}
205
206        operator const Type () const
207        {
208            return Base::__data;
209        }
210
211        Type
212        operator=(Type const & _data)
213        {
214            Base::__data = _data;
215            return _data;
216        }
217
218        bool
219        operator<(Base const & base) const
220        {
221            return Base::__data < base.__data;
222        }
223
224        bool
225        operator==(Base const & base) const
226        {
227            return Base::__data == base.__data;
228        }
229    };
230}
231
232//This macro is a backend for other macros that specialize it slightly.
233//First, it creates/extends a namespace "BitfieldUnderlyingClasses" and
234//sticks the class which has the actual union in it, which
235//BitfieldOperators above inherits from. Putting these classes in a special
236//namespace ensures that there will be no collisions with other names as long
237//as the BitUnion names themselves are all distinct and nothing else uses
238//the BitfieldUnderlyingClasses namespace, which is unlikely. The class itself
239//creates a typedef of the "type" parameter called __DataType. This allows
240//the type to propagate outside of the macro itself in a controlled way.
241//Finally, the base storage is defined which BitfieldOperators will refer to
242//in the operators it defines. This macro is intended to be followed by
243//bitfield definitions which will end up inside it's union. As explained
244//above, these is overlayed the __data member in its entirety by each of the
245//bitfields which are defined in the union, creating shared storage with no
246//overhead.
247#define __BitUnion(type, name) \
248    class BitfieldUnderlyingClasses##name : \
249        public BitfieldBackend::BitfieldTypes<type> \
250    { \
251      public: \
252        typedef type __DataType; \
253        union { \
254            type __data;\
255
256//This closes off the class and union started by the above macro. It is
257//followed by a typedef which makes "name" refer to a BitfieldOperator
258//class inheriting from the class and union just defined, which completes
259//building up the type for the user.
260#define EndBitUnion(name) \
261        }; \
262    }; \
263    typedef BitfieldBackend::BitUnionOperators< \
264        BitfieldUnderlyingClasses##name::__DataType, \
265        BitfieldUnderlyingClasses##name> name;
266
267//This sets up a bitfield which has other bitfields nested inside of it. The
268//__data member functions like the "underlying storage" of the top level
269//BitUnion. Like everything else, it overlays with the top level storage, so
270//making it a regular bitfield type makes the entire thing function as a
271//regular bitfield when referred to by itself.
272#define __SubBitUnion(fieldType, first, last, name) \
273    class : public BitfieldBackend::BitfieldTypes<__DataType> \
274    { \
275      public: \
276        union { \
277            fieldType<first, last> __data;
278
279//This closes off the union created above and gives it a name. Unlike the top
280//level BitUnion, we're interested in creating an object instead of a type.
281//The operators are defined in the macro itself instead of a class for
282//technical reasons. If someone determines a way to move them to one, please
283//do so.
284#define EndSubBitUnion(name) \
285        }; \
286        inline operator const __DataType () const \
287        { return __data; } \
288        \
289        inline const __DataType operator = (const __DataType & _data) \
290        { return __data = _data;} \
291    } name;
292
293//Regular bitfields
294//These define macros for read/write regular bitfield based subbitfields.
295#define SubBitUnion(name, first, last) \
296    __SubBitUnion(Bitfield, first, last, name)
297
298//Regular bitfields
299//These define macros for read/write regular bitfield based subbitfields.
300#define SignedSubBitUnion(name, first, last) \
301    __SubBitUnion(SignedBitfield, first, last, name)
302
303//Use this to define an arbitrary type overlayed with bitfields.
304#define BitUnion(type, name) __BitUnion(type, name)
305
306//Use this to define conveniently sized values overlayed with bitfields.
307#define BitUnion64(name) __BitUnion(uint64_t, name)
308#define BitUnion32(name) __BitUnion(uint32_t, name)
309#define BitUnion16(name) __BitUnion(uint16_t, name)
310#define BitUnion8(name) __BitUnion(uint8_t, name)
311
312#endif // __BASE_BITUNION_HH__
313