d5bf9fa5c0f4b3a85f3f8235324ceb3c2e838110
[oota-llvm.git] / docs / Atomics.html
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
2                       "http://www.w3.org/TR/html4/strict.dtd">
3 <html>
4 <head>
5   <title>LLVM Atomic Instructions and Concurrency Guide</title>
6   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
7   <link rel="stylesheet" href="llvm.css" type="text/css">
8 </head>
9 <body>
10
11 <h1>
12   LLVM Atomic Instructions and Concurrency Guide
13 </h1>
14
15 <ol>
16   <li><a href="#introduction">Introduction</a></li>
17   <li><a href="#loadstore">Load and store</a></li>
18   <li><a href="#otherinst">Other atomic instructions</a></li>
19   <li><a href="#ordering">Atomic orderings</a></li>
20   <li><a href="#iropt">Atomics and IR optimization</a></li>
21   <li><a href="#codegen">Atomics and Codegen</a></li>
22 </ol>
23
24 <div class="doc_author">
25   <p>Written by Eli Friedman</p>
26 </div>
27
28 <!-- *********************************************************************** -->
29 <h2>
30   <a name="introduction">Introduction</a>
31 </h2>
32 <!-- *********************************************************************** -->
33
34 <div>
35
36 <p>Historically, LLVM has not had very strong support for concurrency; some
37 minimal intrinsics were provided, and <code>volatile</code> was used in some
38 cases to achieve rough semantics in the presence of concurrency.  However, this
39 is changing; there are now new instructions which are well-defined in the
40 presence of threads and asynchronous signals, and the model for existing
41 instructions has been clarified in the IR.</p>
42
43 <p>The atomic instructions are designed specifically to provide readable IR and
44    optimized code generation for the following:</p>
45 <ul>
46   <li>The new C++0x <code>&lt;atomic&gt;</code> header.
47       (<a href="http://www.open-std.org/jtc1/sc22/wg21/">C++0x draft available here</a>.)
48       (<a href="http://www.open-std.org/jtc1/sc22/wg14/">C1x draft available here</a>)</li>
49   <li>Proper semantics for Java-style memory, for both <code>volatile</code> and
50       regular shared variables.
51       (<a href="http://java.sun.com/docs/books/jls/third_edition/html/memory.html">Java Specification</a>)</li>
52   <li>gcc-compatible <code>__sync_*</code> builtins.
53       (<a href="http://gcc.gnu.org/onlinedocs/gcc/Atomic-Builtins.html">Description</a>)</li>
54   <li>Other scenarios with atomic semantics, including <code>static</code>
55       variables with non-trivial constructors in C++.</li>
56 </ul>
57
58 <p>Atomic and volatile in the IR are orthogonal; "volatile" is the C/C++
59    volatile, which ensures that every volatile load and store happens and is
60    performed in the stated order.  A couple examples: if a
61    SequentiallyConsistent store is immediately followed by another
62    SequentiallyConsistent store to the same address, the first store can
63    be erased. This transformation is not allowed for a pair of volatile
64    stores. On the other hand, a non-volatile non-atomic load can be moved
65    across a volatile load freely, but not an Acquire load.</p>
66
67 <p>This document is intended to provide a guide to anyone either writing a
68    frontend for LLVM or working on optimization passes for LLVM with a guide
69    for how to deal with instructions with special semantics in the presence of
70    concurrency.  This is not intended to be a precise guide to the semantics;
71    the details can get extremely complicated and unreadable, and are not
72    usually necessary.</p>
73
74 </div>
75
76 <!-- *********************************************************************** -->
77 <h2>
78   <a name="loadstore">Load and store</a>
79 </h2>
80 <!-- *********************************************************************** -->
81
82 <div>
83
84 <p>The basic <code>'load'</code> and <code>'store'</code> allow a variety of 
85    optimizations, but can have unintuitive results in a concurrent environment.
86    For a frontend writer, the rule is essentially that all memory accessed 
87    with basic loads and stores by multiple threads should be protected by a
88    lock or other synchronization; otherwise, you are likely to run into
89    undefined behavior. (Do not use volatile as a substitute for atomics; it
90    might work on some platforms, but does not provide the necessary guarantees
91    in general.)</p>
92
93 <p>From the optimizer's point of view, the rule is that if there
94    are not any instructions with atomic ordering involved, concurrency does
95    not matter, with one exception: if a variable might be visible to another
96    thread or signal handler, a store cannot be inserted along a path where it
97    might not execute otherwise. For example, suppose LICM wants to take all the
98    loads and stores in a loop to and from a particular address and promote them
99    to registers. LICM is not allowed to insert an unconditional store after
100    the loop with the computed value unless a store unconditionally executes
101    within the loop. Note that speculative loads are allowed; a load which
102    is part of a race returns <code>undef</code>, but does not have undefined
103    behavior.</p>
104
105 <p>For cases where simple loads and stores are not sufficient, LLVM provides
106    atomic loads and stores with varying levels of guarantees.</p>
107
108 </div>
109
110 <!-- *********************************************************************** -->
111 <h2>
112   <a name="otherinst">Other atomic instructions</a>
113 </h2>
114 <!-- *********************************************************************** -->
115
116 <div>
117
118 <p><code>cmpxchg</code> and <code>atomicrmw</code> are essentially like an
119    atomic load followed by an atomic store (where the store is conditional for
120    <code>cmpxchg</code>), but no other memory operation can happen between
121    the load and store.  Note that our cmpxchg does not have quite as many
122    options for making cmpxchg weaker as the C++0x version.</p>
123
124 <p>A <code>fence</code> provides Acquire and/or Release ordering which is not
125    part of another operation; it is normally used along with Monotonic memory
126    operations.  A Monotonic load followed by an Acquire fence is roughly
127    equivalent to an Acquire load.</p>
128
129 <p>Frontends generating atomic instructions generally need to be aware of the
130    target to some degree; atomic instructions are guaranteed to be lock-free,
131    and therefore an instruction which is wider than the target natively supports
132    can be impossible to generate.</p>
133
134 </div>
135
136 <!-- *********************************************************************** -->
137 <h2>
138   <a name="ordering">Atomic orderings</a>
139 </h2>
140 <!-- *********************************************************************** -->
141
142 <div>
143
144 <p>In order to achieve a balance between performance and necessary guarantees,
145    there are six levels of atomicity. They are listed in order of strength;
146    each level includes all the guarantees of the previous level except for
147    Acquire/Release.</p>
148
149 <!-- ======================================================================= -->
150 <h3>
151      <a name="o_unordered">Unordered</a>
152 </h3>
153
154 <div>
155
156 <p>Unordered is the lowest level of atomicity. It essentially guarantees that
157    races produce somewhat sane results instead of having undefined behavior.
158    It also guarantees the operation to be lock-free, so it do not depend on
159    the data being part of a special atomic structure or depend on a separate
160    per-process global lock.  Note that code generation will fail for
161    unsupported atomic operations; if you need such an operation, use explicit
162    locking.</p>
163
164 <dl>
165   <dt>Relevant standard</dt>
166   <dd>This is intended to match the Java memory model for shared
167       variables.</dd>
168   <dt>Notes for frontends</dt>
169   <dd>This cannot be used for synchronization, but is useful for Java and
170       other "safe" languages which need to guarantee that the generated
171       code never exhibits undefined behavior. Note that this guarantee
172       is cheap on common platforms for loads of a native width, but can
173       be expensive or unavailable for wider loads, like a 64-bit store
174       on ARM. (A frontend for Java or other "safe" languages would normally
175       split a 64-bit store on ARM into two 32-bit unordered stores.)
176   <dt>Notes for optimizers</dt>
177   <dd>In terms of the optimizer, this prohibits any transformation that
178       transforms a single load into multiple loads, transforms a store
179       into multiple stores, narrows a store, or stores a value which
180       would not be stored otherwise.  Some examples of unsafe optimizations
181       are narrowing an assignment into a bitfield, rematerializing
182       a load, and turning loads and stores into a memcpy call. Reordering
183       unordered operations is safe, though, and optimizers should take 
184       advantage of that because unordered operations are common in
185       languages that need them.</dd>
186   <dt>Notes for code generation</dt>
187   <dd>These operations are required to be atomic in the sense that if you
188       use unordered loads and unordered stores, a load cannot see a value
189       which was never stored.  A normal load or store instruction is usually
190       sufficient, but note that an unordered load or store cannot
191       be split into multiple instructions (or an instruction which
192       does multiple memory operations, like <code>LDRD</code> on ARM).</dd>
193 </dl>
194
195 </div>
196
197 <!-- ======================================================================= -->
198 <h3>
199      <a name="o_monotonic">Monotonic</a>
200 </h3>
201
202 <div>
203
204 <p>Monotonic is the weakest level of atomicity that can be used in
205    synchronization primitives, although it does not provide any general
206    synchronization. It essentially guarantees that if you take all the
207    operations affecting a specific address, a consistent ordering exists.
208
209 <dl>
210   <dt>Relevant standard</dt>
211   <dd>This corresponds to the C++0x/C1x <code>memory_order_relaxed</code>;
212      see those standards for the exact definition.
213   <dt>Notes for frontends</dt>
214   <dd>If you are writing a frontend which uses this directly, use with caution.
215       The guarantees in terms of synchronization are very weak, so make
216       sure these are only used in a pattern which you know is correct.
217       Generally, these would either be used for atomic operations which
218       do not protect other memory (like an atomic counter), or along with
219       a <code>fence</code>.</dd>
220   <dt>Notes for optimizers</dt>
221   <dd>In terms of the optimizer, this can be treated as a read+write on the
222       relevant memory location (and alias analysis will take advantage of
223       that). In addition, it is legal to reorder non-atomic and Unordered
224       loads around Monotonic loads. CSE/DSE and a few other optimizations
225       are allowed, but Monotonic operations are unlikely to be used in ways
226       which would make those optimizations useful.</dd>
227   <dt>Notes for code generation</dt>
228   <dd>Code generation is essentially the same as that for unordered for loads
229      and stores.  No fences is required.  <code>cmpxchg</code> and 
230      <code>atomicrmw</code> are required to appear as a single operation.</dd>
231 </dl>
232
233 </div>
234
235 <!-- ======================================================================= -->
236 <h3>
237      <a name="o_acquire">Acquire</a>
238 </h3>
239
240 <div>
241
242 <p>Acquire provides a barrier of the sort necessary to acquire a lock to access
243    other memory with normal loads and stores.
244
245 <dl>
246   <dt>Relevant standard</dt>
247   <dd>This corresponds to the C++0x/C1x <code>memory_order_acquire</code>. It
248       should also be used for C++0x/C1x <code>memory_order_consume</code>.
249   <dt>Notes for frontends</dt>
250   <dd>If you are writing a frontend which uses this directly, use with caution.
251       Acquire only provides a semantic guarantee when paired with a Release
252       operation.</dd>
253   <dt>Notes for optimizers</dt>
254   <dd>In general, optimizers should treat this like a nothrow call; the
255       the possible optimizations are usually not interesting.</dd>
256   <dt>Notes for code generation</dt>
257   <dd>Architectures with weak memory ordering (essentially everything relevant
258       today except x86 and SPARC) require some sort of fence to maintain
259       the Acquire semantics.  The precise fences required varies widely by
260       architecture, but for a simple implementation, most architectures provide
261       a barrier which is strong enough for everything (<code>dmb</code> on ARM,
262       <code>sync</code> on PowerPC, etc.).  Putting such a fence after the
263       equivalent Monotonic operation is sufficient to maintain Acquire
264       semantics for a memory operation.</dd>
265 </dl>
266
267 </div>
268
269 <!-- ======================================================================= -->
270 <h3>
271      <a name="o_acquire">Release</a>
272 </h3>
273
274 <div>
275
276 <p>Release is similar to Acquire, but with a barrier of the sort necessary to
277    release a lock.
278
279 <dl>
280   <dt>Relevant standard</dt>
281   <dd>This corresponds to the C++0x/C1x <code>memory_order_release</code>.</dd>
282   <dt>Notes for frontends</dt>
283   <dd>If you are writing a frontend which uses this directly, use with caution.
284       Release only provides a semantic guarantee when paired with a Acquire
285       operation.</dd>
286   <dt>Notes for optimizers</dt>
287   <dd>In general, optimizers should treat this like a nothrow call; the
288       the possible optimizations are usually not interesting.</dd>
289   <dt>Notes for code generation</dt>
290   <dd>Similarly to Acquire, a fence after the relevant operation is usually
291       sufficient; see the section on Acquire.  Note that a store-store fence
292       is not sufficient to implement Release semantics; store-store fences
293       are generally not exposed to IR because they are extremely difficult to
294       use correctly.</dd>
295 </dl>
296
297 </div>
298
299 <!-- ======================================================================= -->
300 <h3>
301      <a name="o_acqrel">AcquireRelease</a>
302 </h3>
303
304 <div>
305
306 <p>AcquireRelease (<code>acq_rel</code> in IR) provides both an Acquire and a
307    Release barrier (for fences and operations which both read and write memory).
308
309 <dl>
310   <dt>Relevant standard</dt>
311   <dd>This corresponds to the C++0x/C1x <code>memory_order_acq_rel</code>.
312   <dt>Notes for frontends</dt>
313   <dd>If you are writing a frontend which uses this directly, use with caution.
314       Acquire only provides a semantic guarantee when paired with a Release
315       operation, and vice versa.</dd>
316   <dt>Notes for optimizers</dt>
317   <dd>In general, optimizers should treat this like a nothrow call; the
318       the possible optimizations are usually not interesting.</dd>
319   <dt>Notes for code generation</dt>
320   <dd>This operation has Acquire and Release semantics; see the sections on
321       Acquire and Release.</dd>
322 </dl>
323
324 </div>
325
326 <!-- ======================================================================= -->
327 <h3>
328      <a name="o_seqcst">SequentiallyConsistent</a>
329 </h3>
330
331 <div>
332
333 <p>SequentiallyConsistent (<code>seq_cst</code> in IR) provides
334    Acquire semantics for loads and Release semantics for
335    stores. Additionally, it guarantees that a total ordering exists
336    between all SequentiallyConsistent operations.
337
338 <dl>
339   <dt>Relevant standard</dt>
340   <dd>This corresponds to the C++0x/C1x <code>memory_order_seq_cst</code>,
341       Java volatile, and the gcc-compatible <code>__sync_*</code> builtins
342       which do not specify otherwise.
343   <dt>Notes for frontends</dt>
344   <dd>If a frontend is exposing atomic operations, these are much easier to
345       reason about for the programmer than other kinds of operations, and using
346       them is generally a practical performance tradeoff.</dd>
347   <dt>Notes for optimizers</dt>
348   <dd>In general, optimizers should treat this like a nothrow call.
349       However, optimizers may improve performance by reordering a
350       store followed by a load unless both operations are sequentially
351       consistent.</dd>
352   <dt>Notes for code generation</dt>
353   <dd>SequentiallyConsistent loads minimally require the same barriers
354     as Acquire operations and SequeuentiallyConsistent stores require
355     Release barriers. Additionally, the code generator must enforce
356     ordering between SequeuentiallyConsistent stores followed by
357     SequeuentiallyConsistent loads. On common architectures, this
358     requires emitting a full fence after SequeuentiallyConsistent stores.</dd>
359 </dl>
360
361 </div>
362
363 </div>
364
365 <!-- *********************************************************************** -->
366 <h2>
367   <a name="iropt">Atomics and IR optimization</a>
368 </h2>
369 <!-- *********************************************************************** -->
370
371 <div>
372
373 <p>Predicates for optimizer writers to query:
374 <ul>
375   <li>isSimple(): A load or store which is not volatile or atomic.  This is
376       what, for example, memcpyopt would check for operations it might
377       transform.
378   <li>isUnordered(): A load or store which is not volatile and at most
379       Unordered. This would be checked, for example, by LICM before hoisting
380       an operation.
381   <li>mayReadFromMemory()/mayWriteToMemory(): Existing predicate, but note
382       that they return true for any operation which is volatile or at least
383       Monotonic.
384   <li>Alias analysis: Note that AA will return ModRef for anything Acquire or
385       Release, and for the address accessed by any Monotonic operation.
386 </ul>
387
388 <p>There are essentially two components to supporting atomic operations. The
389    first is making sure to query isSimple() or isUnordered() instead
390    of isVolatile() before transforming an operation.  The other piece is
391    making sure that a transform does not end up replacing, for example, an 
392    Unordered operation with a non-atomic operation.  Most of the other 
393    necessary checks automatically fall out from existing predicates and
394    alias analysis queries.</p>
395
396 <p>Some examples of how optimizations interact with various kinds of atomic
397    operations:
398 <ul>
399   <li>memcpyopt: An atomic operation cannot be optimized into part of a
400       memcpy/memset, including unordered loads/stores.  It can pull operations
401       across some atomic operations.
402   <li>LICM: Unordered loads/stores can be moved out of a loop.  It just treats
403       monotonic operations like a read+write to a memory location, and anything
404       stricter than that like a nothrow call.
405   <li>DSE: Unordered stores can be DSE'ed like normal stores.  Monotonic stores
406       can be DSE'ed in some cases, but it's tricky to reason about, and not
407       especially important.
408   <li>Folding a load: Any atomic load from a constant global can be
409       constant-folded, because it cannot be observed.  Similar reasoning allows
410       scalarrepl with atomic loads and stores.
411 </ul>
412
413 </div>
414
415 <!-- *********************************************************************** -->
416 <h2>
417   <a name="codegen">Atomics and Codegen</a>
418 </h2>
419 <!-- *********************************************************************** -->
420
421 <div>
422
423 <p>Atomic operations are represented in the SelectionDAG with
424    <code>ATOMIC_*</code> opcodes.  On architectures which use barrier
425    instructions for all atomic ordering (like ARM), appropriate fences are
426    split out as the DAG is built.</p>
427
428 <p>The MachineMemOperand for all atomic operations is currently marked as
429    volatile; this is not correct in the IR sense of volatile, but CodeGen
430    handles anything marked volatile very conservatively.  This should get
431    fixed at some point.</p>
432
433 <p>Common architectures have some way of representing at least a pointer-sized
434    lock-free <code>cmpxchg</code>; such an operation can be used to implement
435    all the other atomic operations which can be represented in IR up to that
436    size.  Backends are expected to implement all those operations, but not
437    operations which cannot be implemented in a lock-free manner.  It is
438    expected that backends will give an error when given an operation which
439    cannot be implemented.  (The LLVM code generator is not very helpful here
440    at the moment, but hopefully that will change.)</p>
441
442 <p>The implementation of atomics on LL/SC architectures (like ARM) is currently
443    a bit of a mess; there is a lot of copy-pasted code across targets, and
444    the representation is relatively unsuited to optimization (it would be nice
445    to be able to optimize loops involving cmpxchg etc.).</p>
446
447 <p>On x86, all atomic loads generate a <code>MOV</code>.
448    SequentiallyConsistent stores generate an <code>XCHG</code>, other stores
449    generate a <code>MOV</code>. SequentiallyConsistent fences generate an
450    <code>MFENCE</code>, other fences do not cause any code to be generated.
451    cmpxchg uses the <code>LOCK CMPXCHG</code> instruction.
452    <code>atomicrmw xchg</code> uses <code>XCHG</code>,
453    <code>atomicrmw add</code> and <code>atomicrmw sub</code> use
454    <code>XADD</code>, and all other <code>atomicrmw</code> operations generate
455    a loop with <code>LOCK CMPXCHG</code>.  Depending on the users of the
456    result, some <code>atomicrmw</code> operations can be translated into
457    operations like <code>LOCK AND</code>, but that does not work in
458    general.</p>
459
460 <p>On ARM, MIPS, and many other RISC architectures, Acquire, Release, and
461    SequentiallyConsistent semantics require barrier instructions
462    for every such operation. Loads and stores generate normal instructions.
463    <code>cmpxchg</code> and <code>atomicrmw</code> can be represented using
464    a loop with LL/SC-style instructions which take some sort of exclusive
465    lock on a cache line  (<code>LDREX</code> and <code>STREX</code> on
466    ARM, etc.). At the moment, the IR does not provide any way to represent a
467    weak <code>cmpxchg</code> which would not require a loop.</p>
468 </div>
469
470 <!-- *********************************************************************** -->
471
472 <hr>
473 <address>
474   <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
475   src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS"></a>
476   <a href="http://validator.w3.org/check/referer"><img
477   src="http://www.w3.org/Icons/valid-html401-blue" alt="Valid HTML 4.01"></a>
478
479   <a href="http://llvm.org/">LLVM Compiler Infrastructure</a><br>
480   Last modified: $Date: 2011-08-09 02:07:00 -0700 (Tue, 09 Aug 2011) $
481 </address>
482
483 </body>
484 </html>