================
@@ -0,0 +1,42 @@
+// RUN: %clang_cc1 -Wconversion -fsyntax-only -verify %s
+// RUN: %clang_cc1 -Wbitfield-conversion -fsyntax-only -verify %s
+// RUN: %clang_cc1 -triple armebv7-unknown-linux -Wbitfield-conversion \
+// RUN:     -fsyntax-only -verify %s
+// RUN: %clang_cc1 -triple arm64-unknown-linux  -Wbitfield-conversion \
+// RUN:     -fsyntax-only -verify %s
+// RUN: %clang_cc1 -triple arm-unknown-linux -Wbitfield-conversion \
+// RUN:     -fsyntax-only -verify %s
+// RUN: %clang_cc1 -triple aarch64-unknown-linux -Wbitfield-conversion \
+// RUN:     -fsyntax-only -verify %s
+// RUN: %clang_cc1 -triple mipsel-unknown-linux -Wbitfield-conversion \
+// RUN:     -fsyntax-only -verify %s
+// RUN: %clang_cc1 -triple mips64el-unknown-linux -Wbitfield-conversion \
+// RUN:     -fsyntax-only -verify %s
+
+typedef struct _xx {
+     int bf:9; // expected-note 3{{declared here}}
+ } xx, *pxx; 
+
+ xx vxx;
+
+ void foo1(int x) {     
+     vxx.bf = x; // expected-warning{{conversion from 'int' (32 bits) to 
bit-field 'bf' (9 bits) may change value}}
----------------
rnk wrote:

This will fire on the code pattern that I have been recommending in Clang to 
detect bitfield truncation:
```
  int value : 6;
  void setBitfield(int v) {
    value = v;
    assert(value == v && "truncation");
  }
```

Example: 
https://github.com/llvm/llvm-project/blob/c35939b22eba9440dff0509b1c2608de39478f14/clang/include/clang/AST/Decl.h#L1901-L1902

This isn't appropriate for all projects because not everyone uses assertions, 
but what's nice about it is that you don't have to do the truncation twice: the 
compiler figures out the bitwidth and truncates appropriately, so the developer 
doesn't have to duplicate information or create an extra enum to track the 
bitwidth to compute a mask. The assert can't really inform the warning because 
they are pre-processed away in release builds, but I wonder if we could detect 
equality comparisons between the assigned bitfield and the RHS of the 
assignment to suppress the warning. On second thought, that seems infeasible.

Without a better code pattern to recommend for developers, I'm worried that 
most of our users are going to turn this warning off. Can anyone more creative 
than me come up with a better recommended code pattern to suppress the warning?

https://github.com/llvm/llvm-project/pull/69049
_______________________________________________
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to