编译器优化自动乱序引发 TrueStudio 代码执行错误.

/ 0评 / 0

使用TrueStudio开发STM32的时候,发现代码逻辑总是错,后来发现是自动重排,涉及重排的两个优化是.

-fschedule-insns
If supported for the target machine, attempt to reorder instructions to eliminate execution stalls due to required data being unavailable. This helps machines that have slow floating point or memory load instructions by allowing other instructions to be issued until the result of the load or floating-point instruction is required.
Enabled at levels -O2-O3.
-fschedule-insns2Similar to -fschedule-insns, but requests an additional pass of instruction scheduling after register allocation has been done. This is especially useful on machines with a relatively small number of registers and where memory load instructions take more than one cycle.
Enabled at levels -O2-O3-Os.

第一个是正常的重排,第二个是更节约资源的重排,目的就是减少CPU的空转,避免等待数据阻塞,然而,排得乱七八糟就是他的错了啊.使用-fno-schedule-insns -fno-schedule-insns2标志可以关,我测试一般用第二个就可以解决,没必要两个都要禁止.轻则SPI数据发送错乱,严重的时候时钟初始化顺序都错了.另外,通常STM32的库有些BUG,开-fno-strict-aliasing更能眼不见心不烦~

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注