天天看点

keil、MDK、armcc 内存屏障语句

CMSIS 中定义为 __memory_changed

/* cmsis_armcc.h */

#ifndef   __COMPILER_BARRIER
  #define __COMPILER_BARRIER()                   __memory_changed()
#endif      

内存屏障语句:

__schedule_barrier();      

或者:

__memory_changed();      

等同于GCC的:

__asm__ __volatile__("": : :"memory")      

编译器在优化时,生成的汇编代码可能与C语言的书写次序不一致,这个叫编译乱序。一般情况下,编译乱序是无害的,会让程序执行更快,但是有些情况下,特别是与中断处理例程有交互的代码,希望执行的次序完全按照C语言的书写次序来完成,这个时候就需要加入适当的内存屏障指令,避免编译乱序。

参考 MDK 帮助文件:

3.6 Compiler intrinsics for inserting optimization barriers

The optimization barrier intrinsics __schedule_barrier, __force_stores, __force_loads, and __memory_changed let you override compiler optimizations by disabling instruction re-ordering and forcing memory updates.

The compiler can perform a range of optimizations, including re-ordering instructions and merging some operations. In some cases, such as system level programming where memory is being accessed concurrently by multiple processes, it might be necessary to disable instruction re-ordering and force memory to be updated.

The optimization barrier intrinsics __schedule_barrier, __force_stores, __force_loads and __memory_changed do not generate code, but they can result in slightly increased code size and extra memory accesses.

参考 MDK 帮助文件:

B4.10 __schedule_barrier intrinsic

This intrinsic creates a special sequence point that prevents operations with side effects from moving past it under all circumstances. Normal sequence points allow operations with side effects past if they do not affect program behavior. Operations without side effects are not restricted by the intrinsic, and the compiler can move them past the sequence point.

有道翻译:

This intrinsic creates a special sequence point that prevents operations with side effects from moving past it under all circumstances.

这种内在的特性创建了一个特殊的序列点,在任何情况下都可以防止带有副作用的操作越过它。

Normal sequence points allow operations with side effects past if they do not affect program behavior.

正常的序列点允许带有副作用的操作,如果它们不影响程序行为的话。