This is an archive of the discontinued LLVM Phabricator instance.

[clang][objc] Add a warning when declaring BOOL bitfields with width 1
Needs ReviewPublic

Authored by teemperor on Dec 18 2020, 4:34 AM.

Details

Summary

In Objective-C, BOOL is either signed char or _Bool depending on the platform and the well defined values for it are YES(1) and NO(0).

For BOOL being signed char this brings up the confusing situation below:

struct X {
  BOOL b : 1;
};
int main() {
  X x;
  x.b = YES;
  if (x.b == YES) {
    // This will never be executed as `x.b` is actually`-1`.
  }
}

We already added support for detecting this situation to ubsan (see https://reviews.llvm.org/D30423?id=89914#inline-266079),
but I think this should also be a compiler warning and that tells people to use unsigned as the bitfield type. This way users
that don't run the affected code with ubsan also know that it probably won't work (and won't file radars against LLDB such as
rdar://71815375 ).

This patch adds a -Wobjc-bool-bitfield that suggests using unsigned for BOOL bitfields of width 1. I enabled it by default
but restricted it to configurations where BOOL is actually signed char as this is where the issue actually arises. For BOOL = bool
configurations this would only limit portability and I guess we don't know if users care about this (and if they do, they'll see
the warning when they compile for a platform where this is an issue).

A related follow-up warning I want to add: We should probably also warn if BOOL bitfields have a width > 1 as that only
works when BOOL = signed char (but stops compiling once the platform changes to BOOL = bool). It's also
kind of nonsensical to use a width greater than 1 for BOOL.

Diff Detail

Event Timeline

teemperor requested review of this revision.Dec 18 2020, 4:34 AM
teemperor created this revision.