Sebastian Redl
2009-Jun-25 14:10 UTC
[LLVMdev] [cfe-dev] LLVM frontend supporting arbitrary bit-width integral datatypes
Duncan Sands wrote:> Hi Adam, > > >> One problem, I was trying to solve was, that I need to declare variables of let's say 5-bit width like 'i5 var', >> the maximal bit-width may be limited to 64 bits. I need such variables to represent instruction's operands, >> example is at the end this message. >> > > any standard compliant C compiler supports i5, believe it or not. > > Try this: > > #include <stdio.h> > > struct i3 { int i:3; }; > > int main(void) { > struct i3 A, B, C; > > A.i = 2; > B.i = 3; > C.i = A.i + B.i; > printf("%d + %d = %d\n", A.i, B.i, C.i); > return 0; > } > > I get: > 2 + 3 = -3 > which is correct for i3 arithmetic! > There might be some problems with signed vs unsigned bitfields, > depending on the compiler. >You're producing a signed overflow, which is simply undefined behavior. Unsigned overflow is well-defined, even for bitfields, but signed is not. Sebastian
Duncan Sands
2009-Jun-25 14:16 UTC
[LLVMdev] [cfe-dev] LLVM frontend supporting arbitrary bit-width integral datatypes
Hi Sebastian,> You're producing a signed overflow, which is simply undefined behavior. > Unsigned overflow is well-defined, even for bitfields, but signed is not.that's true, here's an unsigned version (outputs 5 + 5 = 2): #include <stdio.h> struct i3 { unsigned i:3; }; int main(void) { struct i3 A, B, C; A.i = 5; B.i = 5; C.i = A.i + B.i; printf("%d + %d = %d\n", A.i, B.i, C.i); return 0; } Ciao, Duncan.
Eli Friedman
2009-Jun-26 22:23 UTC
[LLVMdev] [cfe-dev] LLVM frontend supporting arbitrary bit-width integral datatypes
On Thu, Jun 25, 2009 at 7:16 AM, Duncan Sands<baldrick at free.fr> wrote:> Hi Sebastian, > >> You're producing a signed overflow, which is simply undefined behavior. >> Unsigned overflow is well-defined, even for bitfields, but signed is not. > > that's true, here's an unsigned version (outputs 5 + 5 = 2): > > #include <stdio.h> > > struct i3 { unsigned i:3; }; > > int main(void) { > struct i3 A, B, C; > > A.i = 5; > B.i = 5; > C.i = A.i + B.i; > printf("%d + %d = %d\n", A.i, B.i, C.i); > return 0; > }Note that you're actually doing signed arithmetic here; it just doesn't happen to matter because "int" is much larger than the bitfield. -Eli
Seemingly Similar Threads
- [LLVMdev] [cfe-dev] LLVM frontend supporting arbitrary bit-width integral datatypes
- [LLVMdev] LLVM frontend supporting arbitrary bit-width integral datatypes
- [LLVMdev] LLVM frontend supporting arbitrary bit-width integral datatypes
- [LLVMdev] LLVM frontend supporting arbitrary bit-width integral datatypes
- [LLVMdev] LLVM frontend supporting arbitrary bit-width integral datatypes