rui314 / chibicc

A small C compiler
MIT License
9.57k stars 871 forks source link

Compile warnings on GCC/Clang #11

Closed edubart closed 3 years ago

edubart commented 3 years ago

When I compile with O2 I have this warning on GCC 10.2.0:

In function ‘rehash’,
    inlined from ‘get_or_insert_entry’ at hashmap.c:82:5:
hashmap.c:41:18: warning: argument 1 range [18446744071562067968, 18446744073709551615] exceeds maximum object size 9223372036854775807 [-Walloc-size-larger-than=]
   41 |   map2.buckets = calloc(cap, sizeof(HashEntry));
      |                  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from chibicc.h:10,
                 from hashmap.c:3:
hashmap.c: In function ‘get_or_insert_entry’:
/usr/include/stdlib.h:542:14: note: in a call to allocation function ‘calloc’ declared here
  542 | extern void *calloc (size_t __nmemb, size_t __size)

And with Clang many warnings about switches, like:

codegen.c:81:11: warning: 42 enumeration values not handled in switch: 'ND_NULL_EXPR', 'ND_ADD', 'ND_SUB'... [-Wswitch]
  switch (node->kind) {
codegen.c:179:11: warning: 8 enumeration values not handled in switch: 'TY_VOID', 'TY_BOOL', 'TY_CHAR'... [-Wswitch]
  switch (ty->kind) {
...
rui314 commented 3 years ago

Thank you for the bug report. I noticed the first one, but that error looks weird. I believe gcc infers the range of possible values cap can take and conclude that the range is [18446744071562067968, 18446744073709551615], but that inference is simply wrong. cap is much smaller value. Is this a gcc bug, or did I miss something?

For the second switch, I should add -Wno-switch to Makefile. I'll do that.

rui314 commented 3 years ago

Turned out that I already added -Wno-switch in 4a9378dc78645a397ff2cab68fc4e72666c6c64a.

edubart commented 3 years ago

Changing cap to unsigned int makes the first warning go away.

rui314 commented 3 years ago

But do you know why that fixes the problem? That variable shouldn't indeed have a negative value, but the value can't be negative anyway, so the inference of gcc looks weird.

rui314 commented 3 years ago

I investigated this problem a little bit more, and now I believe that, if gcc doesn't have enough information on the exact value range, gcc makes a pessimistic assumption on what value a variable can take and issue a warning based on an incorrect assumption. I'll fix that by adding an assert() to constrain the value range.