ldc icon indicating copy to clipboard operation
ldc copied to clipboard

Incorrect code with a c union containing a struct with bitfields

Open drpriver opened this issue 3 years ago • 1 comments

ldc version:

LDC - the LLVM D compiler (1.30.0):
  based on DMD v2.100.1 and LLVM 14.0.3
  built with LDC - the LLVM D compiler (1.30.0)
  Default target: arm64-apple-darwin21.5.0
  Host CPU: cyclone
  http://dlang.org - http://wiki.dlang.org/LDC

If you have the following preprocessed C file:

// examp.i
struct Value {
  union {
    unsigned long data;
    struct {
        unsigned long kind:4;
        unsigned long count: 29;
        unsigned long capacity: 29;
        unsigned long allocated: 1;
    };
  };
};

and import it in your D code

import examp;

void main(){
    Value v;
    assert(v.kind == 0);
    assert(v.count == 0);
    assert(v.capacity == 0);
    assert(v.allocated == 0);

    v.kind = 4;
    assert(v.kind == 4);
    assert(v.count == 0); // assertion failure here
    assert(v.capacity == 0);
    assert(v.allocated == 0);

    v.count = 3;
    assert(v.kind == 4);
    assert(v.count == 3);
    assert(v.capacity == 0);
    assert(v.allocated == 0);

    v.capacity = 2;
    assert(v.kind == 4);
    assert(v.count == 3);
    assert(v.capacity == 2);
    assert(v.allocated == 0);

    v.allocated = 1;
    assert(v.kind == 4);
    assert(v.count == 3);
    assert(v.capacity == 2);
    assert(v.allocated == 1);
}

It compiles without error, but fails an assertion at runtime. DMD correctly compiles this code.

drpriver avatar Jul 31 '22 03:07 drpriver

Bitfields aren't supported at all yet (#3825), and apparently the according check (edit: emitting a compile error) isn't sufficient.

kinke avatar Jul 31 '22 09:07 kinke

This works now after #4015, verified manually.

kinke avatar Sep 10 '22 17:09 kinke