<div dir="ltr"><div>Hello,</div><div><br></div><div>I'm really amazed to find out that 
under -O3, a simple piece of C code generated from a brainfxxk-to-C 
transpiler is miscompiled. <br></div><div>As one probably know, the C code transpiled from brainfxxk only contains 3 kind of statements: <br></div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex"><div>(1) ++(*ptr) / --(*ptr) <br></div><div>(2) ++ptr / --ptr <br></div><div>(3) while (*ptr) { ... }</div></blockquote><div> where ptr is a uint8_t*. <br></div><div>So
 it seems very clear to me that the code contains no undefined behavior 
(the pointer is uint8_t* and unsigned integer overflow is not UD). <br></div><div><br> </div><div>After further investigation, it seems like clang compiled this loop:</div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex"><div> <span style="font-family:monospace">while (*ptr) {<br>                         --(*ptr);<br>                    ++ptr;<br>                       ++(*ptr);<br>                    --ptr;<br>                     }</span></div></blockquote><div> to an unconditional infinite loop under -O3, resulting in the bug. The code snippet above seems completely benign to me. <br></div><div><br></div><div>I attached the offending program. With <br></div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex"><div>clang a.c -O0</div></blockquote><div>it
 worked fine (it should print out an ASCII-art picture of mandelbrot 
fracture). However, with -O1 or -O3, it goes into a dead loop (in the 
code snippet above) after printing out a few characters.</div><div><br></div><div>I also tried UndefinedBehaviorSanitizer. Strangely, when compiling using <br></div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex"><div>clang a.c -O3  -fsanitize=undefined</div></blockquote><div>the code worked again, with no infinite loop, and no undefined behavior reported.</div><div><br></div><div>So it seems to me a LLVM optimizer bug. I would greatly appreciate if any one is willing to investigate.</div><div><br></div><div>Best,</div><div>Haoran<div class="gmail-adL"><br><br></div></div></div>