llvm / llvm-project

The LLVM Project is a collection of modular and reusable compiler and toolchain technologies.
http://llvm.org
Other
27.82k stars 11.46k forks source link

optimizer malloc #49826

Open 68b1592b-506f-4f32-b7cc-f7acec066692 opened 3 years ago

68b1592b-506f-4f32-b7cc-f7acec066692 commented 3 years ago
Bugzilla Link 50482
Version trunk
OS Linux
CC @DougGregor,@fhahn,@ojeda,@Kojoley,@RalfJung,@zygoloid,@wjristow

Extended Description

#include <stdlib.h>
int is_any_memory_available(int n){
    char *x = malloc(n);
    int y = (x != NULL);
    free(x);
    return y;
}

Works with -O0 With -O3 is optmized to

is_any_memory_available:                # @is_any_memory_available
        mov     eax, 1
        ret

https://godbolt.org/z/4fr7Wz7n7

RalfJung commented 3 years ago

Related example:

#include <stdlib.h>
int test() {
  char *x = malloc(-1);
  char *y = malloc(2);
  int ret = (x != NULL) && (y != NULL);
  free(x); free(y);
  return ret;
}

Arguably, this function must return "0" since it is impossible that both of these 'malloc's succeed. However, clang optimizes this function to return "1". (gcc will not do that.)

68b1592b-506f-4f32-b7cc-f7acec066692 commented 3 years ago

I saw the C++ bug report but (a) it was withdrawn, and (b) the response cited a C++ rule for why it was allowed. This is a C bug report.

68b1592b-506f-4f32-b7cc-f7acec066692 commented 3 years ago

So are you saying that C++ rules apply in this case? The cited provision is not in C11.

Kojoley commented 3 years ago

This bug has been marked as a duplicate of bug llvm/llvm-project#28790