Bug 102556 - equality comparison of a [static N] parameter to null not folded
Summary: equality comparison of a [static N] parameter to null not folded
Status: UNCONFIRMED
Alias: None
Product: gcc
Classification: Unclassified
Component: tree-optimization (show other bugs)
Version: 12.0
: P3 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords: diagnostic, missed-optimization
Depends on:
Blocks:
 
Reported: 2021-10-01 16:38 UTC by Martin Sebor
Modified: 2023-08-03 21:04 UTC (History)
2 users (show)

See Also:
Host:
Target:
Build:
Known to work:
Known to fail:
Last reconfirmed:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Martin Sebor 2021-10-01 16:38:04 UTC
The C99 [static N] array notation in a function parameter indicates that the caller must provide as an argument an array with at least N element.  Therefore, in the body of the function, the parameter may be assumed to be nonnull, the same way as if it had been declared with attribute nonnull.

The test case below shows that GCC fails to take advantage of this to fold pointless comparisons of such parameters to null, even though it does make use of the equivalent guarantee provided by the attribute.

In contrast, Clang folds the expression in both functions to false.

$ cat z.c && gcc -O2 -S -Wall -fdump-tree-optimized=/dev/stdout z.c
__attribute__ ((nonnull)) int f (int *a)
{
  return a == 0;   // folded to false with a warning (good)
}

int g (int a[static 1])
{
  return a == 0;   // not folded, missing warning
}
z.c: In function ‘f’:
z.c:3:12: warning: ‘nonnull’ argument ‘a’ compared to NULL [-Wnonnull-compare]
    3 |   return a == 0;   // folded to false with a warning (good)
      |          ~~^~~~

;; Function f (f, funcdef_no=0, decl_uid=1978, cgraph_uid=1, symbol_order=0)

__attribute__((nonnull))
int f (int * a)
{
  <bb 2> [local count: 1073741824]:
  return 0;

}



;; Function g (g, funcdef_no=1, decl_uid=1981, cgraph_uid=2, symbol_order=1)

__attribute__((access ("^0[s1]", )))
int g (int * a)
{
  _Bool _1;
  int _3;

  <bb 2> [local count: 1073741824]:
  _1 = a_2(D) == 0B;
  _3 = (int) _1;
  return _3;

}
Comment 1 Roman Žilka 2022-12-17 12:55:46 UTC
This'd be helpful.