Friday, 15 February 2013

cpu - about memory barriers (why the following example is error) -



cpu - about memory barriers (why the following example is error) -

i read 1 article, https://www.kernel.org/doc/documentation/memory-barriers.txt

in doc, next illustration shown don't leave out access_once().

it tempting seek enforce ordering on identical stores on both branches of "if" statement follows:

q = access_once(a); if (q) { barrier(); access_once(b) = p; do_something(); } else { barrier(); access_once(b) = p; do_something_else(); }

unfortunately, current compilers transform follows @ high optimization levels:

q = access_once(a); barrier(); access_once(b) = p; /* bug: no ordering vs. load a!!! */ if (q) { /* access_once(b) = p; -- moved up, bug!!! */ do_something(); } else { /* access_once(b) = p; -- moved up, bug!!! */ do_something_else(); }

i don't know, why "moveed up" bug ? if write code, move "access_one(b) because both if/else branch execute same code.

it isn't much moving bug, it's exposes bug in code.

the intention utilize conditional on q (from a), ensure write b done after read a; because both stores "protected" conditional , "stores not speculated", cpu shouldn't making store until knows outcome of condition, requires read have been done first.

the compiler defeats intention seeing both branches of conditional start same thing, in formal sense statements not conditioned. problem explained in next paragraph:

now there no conditional between load 'a' , store 'b', means cpu within rights reorder them: conditional absolutely required, , must nowadays in assembly code after compiler optimizations have been applied.

i'm not experienced plenty know meant barrier(), apparently not powerful plenty enforce ordering between 2 independent memory operations.

cpu compiler-optimization cpu-cache memory-barriers

No comments:

Post a Comment