[clang] [clang] Add clang::preferred_type attribute for bitfields (PR #69104)

Vlad Serebrennikov via cfe-commits cfe-commits at lists.llvm.org
Thu Oct 19 08:18:24 PDT 2023


Endilll wrote:

Taking the example above, I think it would have to look the following way to fully complement a check for bit-field width in `preferred_type`:
```cpp
 enum StoredNameKind : unsigned _BitInt(3) { 
   StoredIdentifier = 0, 
   StoredObjCZeroArgSelector = Selector::ZeroArg, 
   StoredObjCOneArgSelector = Selector::OneArg, 
   StoredCXXConstructorName = 3, 
   StoredCXXDestructorName = 4, 
   StoredCXXConversionFunctionName = 5, 
   StoredCXXOperatorName = 6, 
   StoredDeclarationNameExtra = Selector::MultiArg, 
   PtrMask = 7, 
   [[clang::non_storable]] UncommonNameKindOffset = 8 
 };
 
class DeclarationName {
  [[clang::preferred_type(StoredNameKind)]] unsigned Kind : 3;
}; 
```
Breaking it down:
1) `3` in `unsigned _BitInt(3)` is checked against enumerator values to ensure it's sufficient
2) `UncommonNameKindOffset` does not trigger diagnostic above, because it's marked as (newly-invented) `non_storable`
3) `unsigned` and `3` in `unsigned Kind : 3` are checked against `unsigned _BitInt(3)` because of `preferred_type` 
4) (in other code) `Kind = UncommonNameKindOffset` will be catched, because of `non_storable`.

I think we can robustly diagnose new enumerators if the code is written this way. Implementation seem trivial to me.
Today `_BitInt(3)` in underlying type of an enum has poor support across compilers we support. It doesn't block implementation of this idea, but make it a bit less trivial to implement in performant manner, and makes enum declaration a bit less declarative.

https://github.com/llvm/llvm-project/pull/69104


More information about the cfe-commits mailing list