Subject: Re: Bitfields and kernel
To: NetBSD Kernel Technical Discussion List <tech-kern@netbsd.org>
From: Greg A. Woods <woods@most.weird.com>
List: tech-kern
Date: 09/29/1999 09:50:35
[ On Wednesday, September 29, 1999 at 06:48:57 (+0200), Matthias Buelow wrote: ]
> Subject: Re: Bitfields and kernel
>
> Yeah, I have the book open on my lap.  On page 183 it says,
> "Don't use C or C++ bitfields; they are highly nonportable and tend
> to generate voluminous and inefficient code".  This is under the chapter
> "Space Efficiency" however.
> They get even clearer on page 195 in the section on portability:
> "Bitfields.  Bitfields are so machine-dependent that no one should use
> them."

Oh, bugger.  I've confused my Kernighan texts!  They look so similar
lying open on the desk.  :-(  It is K&R (all editions) that suggest
using bit-fields for manipulation of related flags.

Anyway, I do take issue with the fact that C bit-fields are
non-portable.  They've worked exactly the same way, so far as I can tell
from real-world Unix compilers, ever since the original K&R.  In fact
except for Tiny C I don't think I've even used an MS-DOS compiler where
they caused any problems (Tiny C simply didn't implement bit-fields),
except perhaps for the early versions of Lattice C (and thus perhaps the
very first version of Microsoft C).

The implementation of C bit-fields is very machine dependent, naturally,
and of course they should never be used to try and map an external data
structure.  That doesn't mean they shouldn't be used where they make
sense to be used with internal data structures.

> The inefficiency mentioned might not be a big deal today but then again
> I also run NetBSD on a oldish VAXstation and it is so horribly slow,
> every instruction that gets spared counts, especially in often executed
> loops (polled-i/o devices for example; dunno if the VAX port does much bit-
> juggling in there, though but pio certainly eats a lot of cpu (I pray
> that the VAX gurus come up with dma support for the scsi controller fast :)).

VAX or no VAX, "Premature optimisation is the root of all evil in
programming."  :-)

In the end I would have to claim that if bit-field operations generate
worse code than the equivalent bit-fiddling idioms then the compiler is
at fault.  (Comparing with hand optimised machine code is obviously
apples to oranges.)

-- 
							Greg A. Woods

+1 416 218-0098      VE3TCP      <gwoods@acm.org>      <robohack!woods>
Planix, Inc. <woods@planix.com>; Secrets of the Weird <woods@weird.com>