Historically, LLVM has not had very strong support for concurrency; some
minimal intrinsics were provided, and volatile
was used in some
cases to achieve rough semantics in the presence of concurrency. However, this
is changing; there are now new instructions which are well-defined in the
presence of threads and asynchronous signals, and the model for existing
instructions has been clarified in the IR.
The atomic instructions are designed specifically to provide readable IR and optimized code generation for the following:
<atomic>
header.
(C++0x draft available here.)
(C1x draft available here)volatile
and
regular shared variables.
(Java Specification)__sync_*
builtins.
(Description)static
variables with non-trivial constructors in C++.Atomic and volatile in the IR are orthogonal; "volatile" is the C/C++ volatile, which ensures that every volatile load and store happens and is performed in the stated order. A couple examples: if a SequentiallyConsistent store is immediately followed by another SequentiallyConsistent store to the same address, the first store can be erased. This transformation is not allowed for a pair of volatile stores. On the other hand, a non-volatile non-atomic load can be moved across a volatile load freely, but not an Acquire load.
This document is intended to provide a guide to anyone either writing a frontend for LLVM or working on optimization passes for LLVM with a guide for how to deal with instructions with special semantics in the presence of concurrency. This is not intended to be a precise guide to the semantics; the details can get extremely complicated and unreadable, and are not usually necessary.
The basic 'load'
and 'store'
allow a variety of
optimizations, but can lead to undefined results in a concurrent environment;
see NonAtomic. This section specifically goes
into the one optimizer restriction which applies in concurrent environments,
which gets a bit more of an extended description because any optimization
dealing with stores needs to be aware of it.
From the optimizer's point of view, the rule is that if there are not any instructions with atomic ordering involved, concurrency does not matter, with one exception: if a variable might be visible to another thread or signal handler, a store cannot be inserted along a path where it might not execute otherwise. Take the following example:
/* C code, for readability; run through clang -O2 -S -emit-llvm to get equivalent IR */ int x; void f(int* a) { for (int i = 0; i < 100; i++) { if (a[i]) x += 1; } }
The following is equivalent in non-concurrent situations:
int x; void f(int* a) { int xtemp = x; for (int i = 0; i < 100; i++) { if (a[i]) xtemp += 1; } x = xtemp; }
However, LLVM is not allowed to transform the former to the latter: it could indirectly introduce undefined behavior if another thread can access x at the same time. (This example is particularly of interest because before the concurrency model was implemented, LLVM would perform this transformation.)
Note that speculative loads are allowed; a load which
is part of a race returns undef
, but does not have undefined
behavior.
For cases where simple loads and stores are not sufficient, LLVM provides various atomic instructions. The exact guarantees provided depend on the ordering; see Atomic orderings
load atomic
and store atomic
provide the same
basic functionality as non-atomic loads and stores, but provide additional
guarantees in situations where threads and signals are involved.
cmpxchg
and atomicrmw
are essentially like an
atomic load followed by an atomic store (where the store is conditional for
cmpxchg
), but no other memory operation can happen on any thread
between the load and store. Note that LLVM's cmpxchg does not provide quite
as many options as the C++0x version.
A fence
provides Acquire and/or Release ordering which is not
part of another operation; it is normally used along with Monotonic memory
operations. A Monotonic load followed by an Acquire fence is roughly
equivalent to an Acquire load.
Frontends generating atomic instructions generally need to be aware of the target to some degree; atomic instructions are guaranteed to be lock-free, and therefore an instruction which is wider than the target natively supports can be impossible to generate.
In order to achieve a balance between performance and necessary guarantees, there are six levels of atomicity. They are listed in order of strength; each level includes all the guarantees of the previous level except for Acquire/Release. (See also LangRef.)
NotAtomic is the obvious, a load or store which is not atomic. (This isn't really a level of atomicity, but is listed here for comparison.) This is essentially a regular load or store. If there is a race on a given memory location, loads from that location return undef.
Unordered is the lowest level of atomicity. It essentially guarantees that races produce somewhat sane results instead of having undefined behavior. It also guarantees the operation to be lock-free, so it do not depend on the data being part of a special atomic structure or depend on a separate per-process global lock. Note that code generation will fail for unsupported atomic operations; if you need such an operation, use explicit locking.
LDRD
on ARM).Monotonic is the weakest level of atomicity that can be used in synchronization primitives, although it does not provide any general synchronization. It essentially guarantees that if you take all the operations affecting a specific address, a consistent ordering exists.
memory_order_relaxed
;
see those standards for the exact definition.
fence
.cmpxchg
and
atomicrmw
are required to appear as a single operation.Acquire provides a barrier of the sort necessary to acquire a lock to access other memory with normal loads and stores.
memory_order_acquire
. It
should also be used for C++0x/C1x memory_order_consume
.
dmb
on ARM,
sync
on PowerPC, etc.). Putting such a fence after the
equivalent Monotonic operation is sufficient to maintain Acquire
semantics for a memory operation.Release is similar to Acquire, but with a barrier of the sort necessary to release a lock.
memory_order_release
.AcquireRelease (acq_rel
in IR) provides both an Acquire and a
Release barrier (for fences and operations which both read and write memory).
memory_order_acq_rel
.
SequentiallyConsistent (seq_cst
in IR) provides
Acquire semantics for loads and Release semantics for
stores. Additionally, it guarantees that a total ordering exists
between all SequentiallyConsistent operations.
memory_order_seq_cst
,
Java volatile, and the gcc-compatible __sync_*
builtins
which do not specify otherwise.
Predicates for optimizer writers to query:
To support optimizing around atomic operations, make sure you are using the right predicates; everything should work if that is done. If your pass should optimize some atomic operations (Unordered operations in particular), make sure it doesn't replace an atomic load or store with a non-atomic operation.
Some examples of how optimizations interact with various kinds of atomic operations:
Atomic operations are represented in the SelectionDAG with
ATOMIC_*
opcodes. On architectures which use barrier
instructions for all atomic ordering (like ARM), appropriate fences are
split out as the DAG is built.
The MachineMemOperand for all atomic operations is currently marked as volatile; this is not correct in the IR sense of volatile, but CodeGen handles anything marked volatile very conservatively. This should get fixed at some point.
Common architectures have some way of representing at least a pointer-sized
lock-free cmpxchg
; such an operation can be used to implement
all the other atomic operations which can be represented in IR up to that
size. Backends are expected to implement all those operations, but not
operations which cannot be implemented in a lock-free manner. It is
expected that backends will give an error when given an operation which
cannot be implemented. (The LLVM code generator is not very helpful here
at the moment, but hopefully that will change.)
The implementation of atomics on LL/SC architectures (like ARM) is currently a bit of a mess; there is a lot of copy-pasted code across targets, and the representation is relatively unsuited to optimization (it would be nice to be able to optimize loops involving cmpxchg etc.).
On x86, all atomic loads generate a MOV
.
SequentiallyConsistent stores generate an XCHG
, other stores
generate a MOV
. SequentiallyConsistent fences generate an
MFENCE
, other fences do not cause any code to be generated.
cmpxchg uses the LOCK CMPXCHG
instruction.
atomicrmw xchg
uses XCHG
,
atomicrmw add
and atomicrmw sub
use
XADD
, and all other atomicrmw
operations generate
a loop with LOCK CMPXCHG
. Depending on the users of the
result, some atomicrmw
operations can be translated into
operations like LOCK AND
, but that does not work in
general.
On ARM, MIPS, and many other RISC architectures, Acquire, Release, and
SequentiallyConsistent semantics require barrier instructions
for every such operation. Loads and stores generate normal instructions.
cmpxchg
and atomicrmw
can be represented using
a loop with LL/SC-style instructions which take some sort of exclusive
lock on a cache line (LDREX
and STREX
on
ARM, etc.). At the moment, the IR does not provide any way to represent a
weak cmpxchg
which would not require a loop.