wasm-opt: optimizable loop is not optimized
The code example:
#include <stdint.h>
#include <stdio.h>
int32_t a;
int32_t b[1] = {0};
int8_t foo() {
for (; a < 8; a++)
for (b[0] = 0; b[0] < 3; b[0] += 1)
;
return b[0];
}
int main() {
printf("hello");
int b = foo();
printf("b: %d\n", b);
}
Version of wasm-opt:
wasm-opt version 109 (version_109-8-gbab21052c)
wasm-opt option:
wasm-opt --post-emscripten -O3 --low-memory-unused --zero-filled-memory --strip-producers -g --mvp-features --converge --inlining-optimizing --local-cse --code-folding --licm --rse --precompute-propagate --optimize-added-constants-propagate
Problem Description:
I try to compile the above code with emcc -O0 -g and then optimize the generated wasm code with wasm-opt, and I expect the nested loop in function foo will be optimized (as C compilers will do). wasm-opt seems to fail to optimize this nested loop.
What do you mean by "optimize the nested loop"? To turn it into b[0] = 3?
Binaryen doesn't perform optimizations like that atm. It would require understanding that a memory address (b[0]) is not written to by anything else. LLVM can do that because it models the stack explicitly (and has mem2reg), it has undefined behavior it can leverage (e.g. aliasing may be UB), and it has MemorySSA etc. optimizations. Binaryen operates on wasm which is an IR without that amount of information (though we could add MemorySSA eventually, perhaps).