All the optimization passes I can find in the documentation, deal with register, stack or global values; I cannot find any mention of anything trying to optimize values on the heap. But this:
#include <stdlib.h>
int main(int argc, char **argv) {
int *a = malloc(10 * sizeof(int));
for (int i = 0; i < 10; i++)
a[i] = i;
return a[5];
}
compiles to ‘ret 5’ (as it should). Which pass does that?
The optimization should be done at InstructionCombine pass. See: Compiler Explorer. Previous cleaning passes are necessary.
But I feel this optimization is a little bit aggresive. Since it changes the behavior of the program. The program above might hit a memory leak while the optimized one would not.
As a reference, GCC wouldn’t do this under O2: Compiler Explorer. It would only do this under O3.