Debian Codegraph @

libphobos/libdruntime/core/atomic.d

raw
1 /**
2 * The atomic module provides basic support for lock-free
3 * concurrent programming.
4 *
5 * $(NOTE Use the `-preview=nosharedaccess` compiler flag to detect
6 * unsafe individual read or write operations on shared data.)
7 *
8 * Copyright: Copyright Sean Kelly 2005 - 2016.
9 * License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
10 * Authors: Sean Kelly, Alex Rønne Petersen, Manu Evans
11 * Source: $(DRUNTIMESRC core/_atomic.d)
12 */
13
14 module core.atomic;
15
16 ///
17 @safe unittest
18 {
19 int y = 2;
20 shared int x = y; // OK
21
22 //x++; // read modify write error
23 x.atomicOp!"+="(1); // OK
24 //y = x; // read error with preview flag
25 y = x.atomicLoad(); // OK
26 assert(y == 3);
27 //x = 5; // write error with preview flag
28 x.atomicStore(5); // OK
29 assert(x.atomicLoad() == 5);
30 }
31
32 import core.internal.atomic;
33 import core.internal.attributes : betterC;
34 import core.internal.traits : hasUnsharedIndirections;
35
36 /**
37 * Specifies the memory ordering semantics of an atomic operation.
38 *
39 * See_Also:
40 * $(HTTP en.cppreference.com/w/cpp/atomic/memory_order)
41 */
42 enum MemoryOrder
43 {
44 /**
45 * Not sequenced.
46 * Corresponds to $(LINK2 https://llvm.org/docs/Atomics.html#monotonic, LLVM AtomicOrdering.Monotonic)
47 * and C++11/C11 `memory_order_relaxed`.
48 */
49 raw = 0,
50 /**
51 * Hoist-load + hoist-store barrier.
52 * Corresponds to $(LINK2 https://llvm.org/docs/Atomics.html#acquire, LLVM AtomicOrdering.Acquire)
53 * and C++11/C11 `memory_order_acquire`.
54 */
55 acq = 2,
56 /**
57 * Sink-load + sink-store barrier.
58 * Corresponds to $(LINK2 https://llvm.org/docs/Atomics.html#release, LLVM AtomicOrdering.Release)
59 * and C++11/C11 `memory_order_release`.
60 */
61 rel = 3,
62 /**
63 * Acquire + release barrier.
64 * Corresponds to $(LINK2 https://llvm.org/docs/Atomics.html#acquirerelease, LLVM AtomicOrdering.AcquireRelease)
65 * and C++11/C11 `memory_order_acq_rel`.
66 */
67 acq_rel = 4,
68 /**
69 * Fully sequenced (acquire + release). Corresponds to
70 * $(LINK2 https://llvm.org/docs/Atomics.html#sequentiallyconsistent, LLVM AtomicOrdering.SequentiallyConsistent)
71 * and C++11/C11 `memory_order_seq_cst`.
72 */
73 seq = 5,
74 }
75
76 /**
77 * Loads 'val' from memory and returns it. The memory barrier specified
78 * by 'ms' is applied to the operation, which is fully sequenced by
79 * default. Valid memory orders are MemoryOrder.raw, MemoryOrder.acq,
80 * and MemoryOrder.seq.
81 *
82 * Params:
83 * val = The target variable.
84 *
85 * Returns:
86 * The value of 'val'.
87 */
88 T atomicLoad(MemoryOrder ms = MemoryOrder.seq, T)(auto ref return scope const T val) pure nothrow @nogc @trusted
89 if (!is(T == shared U, U) && !is(T == shared inout U, U) && !is(T == shared const U, U))
90 {
91 return core.internal.atomic.atomicLoad!ms(cast(T*)&val);
92 }
93
94 /// Ditto
95 T atomicLoad(MemoryOrder ms = MemoryOrder.seq, T)(auto ref return scope shared const T val) pure nothrow @nogc @trusted
96 if (!hasUnsharedIndirections!T)
97 {
98 import core.internal.traits : hasUnsharedIndirections;
99 static assert(!hasUnsharedIndirections!T, "Copying `" ~ shared(const(T)).stringof ~ "` would violate shared.");
100
101 return atomicLoad!ms(*cast(T*)&val);
102 }
103
104 /// Ditto
105 TailShared!T atomicLoad(MemoryOrder ms = MemoryOrder.seq, T)(auto ref shared const T val) pure nothrow @nogc @trusted
106 if (hasUnsharedIndirections!T)
107 {
108 // HACK: DEPRECATE THIS FUNCTION, IT IS INVALID TO DO ATOMIC LOAD OF SHARED CLASS
109 // this is here because code exists in the wild that does this...
110
111 return core.internal.atomic.atomicLoad!ms(cast(TailShared!T*)&val);
112 }
113
114 /**
115 * Writes 'newval' into 'val'. The memory barrier specified by 'ms' is
116 * applied to the operation, which is fully sequenced by default.
117 * Valid memory orders are MemoryOrder.raw, MemoryOrder.rel, and
118 * MemoryOrder.seq.
119 *
120 * Params:
121 * val = The target variable.
122 * newval = The value to store.
123 */
124 void atomicStore(MemoryOrder ms = MemoryOrder.seq, T, V)(ref T val, V newval) pure nothrow @nogc @trusted
125 if (!is(T == shared) && !is(V == shared))
126 {
127 import core.internal.traits : hasElaborateCopyConstructor;
128 static assert (!hasElaborateCopyConstructor!T, "`T` may not have an elaborate copy: atomic operations override regular copying semantics.");
129
130 // resolve implicit conversions
131 T arg = newval;
132
133 core.internal.atomic.atomicStore!ms(&val, arg);
134 }
135
136 /// Ditto
137 void atomicStore(MemoryOrder ms = MemoryOrder.seq, T, V)(ref shared T val, V newval) pure nothrow @nogc @trusted
138 if (!is(T == class))
139 {
140 static if (is (V == shared U, U))
141 alias Thunk = U;
142 else
143 {
144 import core.internal.traits : hasUnsharedIndirections;
145 static assert(!hasUnsharedIndirections!V, "Copying argument `" ~ V.stringof ~ " newval` to `" ~ shared(T).stringof ~ " here` would violate shared.");
146 alias Thunk = V;
147 }
148 atomicStore!ms(*cast(T*)&val, *cast(Thunk*)&newval);
149 }
150
151 /// Ditto
152 void atomicStore(MemoryOrder ms = MemoryOrder.seq, T, V)(ref shared T val, auto ref shared V newval) pure nothrow @nogc @trusted
153 if (is(T == class))
154 {
155 static assert (is (V : T), "Can't assign `newval` of type `shared " ~ V.stringof ~ "` to `shared " ~ T.stringof ~ "`.");
156
157 core.internal.atomic.atomicStore!ms(cast(T*)&val, cast(V)newval);
158 }
159
160 /**
161 * Atomically adds `mod` to the value referenced by `val` and returns the value `val` held previously.
162 * This operation is both lock-free and atomic.
163 *
164 * Params:
165 * val = Reference to the value to modify.
166 * mod = The value to add.
167 *
168 * Returns:
169 * The value held previously by `val`.
170 */
171 T atomicFetchAdd(MemoryOrder ms = MemoryOrder.seq, T)(ref return scope T val, size_t mod) pure nothrow @nogc @trusted
172 if ((__traits(isIntegral, T) || is(T == U*, U)) && !is(T == shared))
173 in (atomicValueIsProperlyAligned(val))
174 {
175 static if (is(T == U*, U))
176 return cast(T)core.internal.atomic.atomicFetchAdd!ms(cast(size_t*)&val, mod * U.sizeof);
177 else
178 return core.internal.atomic.atomicFetchAdd!ms(&val, cast(T)mod);
179 }
180
181 /// Ditto
182 T atomicFetchAdd(MemoryOrder ms = MemoryOrder.seq, T)(ref return scope shared T val, size_t mod) pure nothrow @nogc @trusted
183 if (__traits(isIntegral, T) || is(T == U*, U))
184 in (atomicValueIsProperlyAligned(val))
185 {
186 return atomicFetchAdd!ms(*cast(T*)&val, mod);
187 }
188
189 /**
190 * Atomically subtracts `mod` from the value referenced by `val` and returns the value `val` held previously.
191 * This operation is both lock-free and atomic.
192 *
193 * Params:
194 * val = Reference to the value to modify.
195 * mod = The value to subtract.
196 *
197 * Returns:
198 * The value held previously by `val`.
199 */
200 T atomicFetchSub(MemoryOrder ms = MemoryOrder.seq, T)(ref return scope T val, size_t mod) pure nothrow @nogc @trusted
201 if ((__traits(isIntegral, T) || is(T == U*, U)) && !is(T == shared))
202 in (atomicValueIsProperlyAligned(val))
203 {
204 static if (is(T == U*, U))
205 return cast(T)core.internal.atomic.atomicFetchSub!ms(cast(size_t*)&val, mod * U.sizeof);
206 else
207 return core.internal.atomic.atomicFetchSub!ms(&val, cast(T)mod);
208 }
209
210 /// Ditto
211 T atomicFetchSub(MemoryOrder ms = MemoryOrder.seq, T)(ref return scope shared T val, size_t mod) pure nothrow @nogc @trusted
212 if (__traits(isIntegral, T) || is(T == U*, U))
213 in (atomicValueIsProperlyAligned(val))
214 {
215 return atomicFetchSub!ms(*cast(T*)&val, mod);
216 }
217
218 /**
219 * Exchange `exchangeWith` with the memory referenced by `here`.
220 * This operation is both lock-free and atomic.
221 *
222 * Params:
223 * here = The address of the destination variable.
224 * exchangeWith = The value to exchange.
225 *
226 * Returns:
227 * The value held previously by `here`.
228 */
229 T atomicExchange(MemoryOrder ms = MemoryOrder.seq,T,V)(T* here, V exchangeWith) pure nothrow @nogc @trusted
230 if (!is(T == shared) && !is(V == shared))
231 in (atomicPtrIsProperlyAligned(here), "Argument `here` is not properly aligned")
232 {
233 // resolve implicit conversions
234 T arg = exchangeWith;
235
236 return core.internal.atomic.atomicExchange!ms(here, arg);
237 }
238
239 /// Ditto
240 TailShared!T atomicExchange(MemoryOrder ms = MemoryOrder.seq,T,V)(shared(T)* here, V exchangeWith) pure nothrow @nogc @trusted
241 if (!is(T == class) && !is(T == interface))
242 in (atomicPtrIsProperlyAligned(here), "Argument `here` is not properly aligned")
243 {
244 static if (is (V == shared U, U))
245 alias Thunk = U;
246 else
247 {
248 import core.internal.traits : hasUnsharedIndirections;
249 static assert(!hasUnsharedIndirections!V, "Copying `exchangeWith` of type `" ~ V.stringof ~ "` to `" ~ shared(T).stringof ~ "` would violate shared.");
250 alias Thunk = V;
251 }
252 return atomicExchange!ms(cast(T*)here, *cast(Thunk*)&exchangeWith);
253 }
254
255 /// Ditto
256 shared(T) atomicExchange(MemoryOrder ms = MemoryOrder.seq,T,V)(shared(T)* here, shared(V) exchangeWith) pure nothrow @nogc @trusted
257 if (is(T == class) || is(T == interface))
258 in (atomicPtrIsProperlyAligned(here), "Argument `here` is not properly aligned")
259 {
260 static assert (is (V : T), "Can't assign `exchangeWith` of type `" ~ shared(V).stringof ~ "` to `" ~ shared(T).stringof ~ "`.");
261
262 return cast(shared)core.internal.atomic.atomicExchange!ms(cast(T*)here, cast(V)exchangeWith);
263 }
264
265 /**
266 * Performs either compare-and-set or compare-and-swap (or exchange).
267 *
268 * There are two categories of overloads in this template:
269 * The first category does a simple compare-and-set.
270 * The comparison value (`ifThis`) is treated as an rvalue.
271 *
272 * The second category does a compare-and-swap (a.k.a. compare-and-exchange),
273 * and expects `ifThis` to be a pointer type, where the previous value
274 * of `here` will be written.
275 *
276 * This operation is both lock-free and atomic.
277 *
278 * Params:
279 * here = The address of the destination variable.
280 * writeThis = The value to store.
281 * ifThis = The comparison value.
282 *
283 * Returns:
284 * true if the store occurred, false if not.
285 */
286 template cas(MemoryOrder succ = MemoryOrder.seq, MemoryOrder fail = MemoryOrder.seq)
287 {
288 /// Compare-and-set for non-shared values
289 bool cas(T, V1, V2)(T* here, V1 ifThis, V2 writeThis) pure nothrow @nogc @trusted
290 if (!is(T == shared) && is(T : V1))
291 in (atomicPtrIsProperlyAligned(here), "Argument `here` is not properly aligned")
292 {
293 // resolve implicit conversions
294 const T arg1 = ifThis;
295 T arg2 = writeThis;
296
297 return atomicCompareExchangeStrongNoResult!(succ, fail)(here, arg1, arg2);
298 }
299
300 /// Compare-and-set for shared value type
301 bool cas(T, V1, V2)(shared(T)* here, V1 ifThis, V2 writeThis) pure nothrow @nogc @trusted
302 if (!is(T == class) && (is(T : V1) || is(shared T : V1)))
303 in (atomicPtrIsProperlyAligned(here), "Argument `here` is not properly aligned")
304 {
305 static if (is (V1 == shared U1, U1))
306 alias Thunk1 = U1;
307 else
308 alias Thunk1 = V1;
309 static if (is (V2 == shared U2, U2))
310 alias Thunk2 = U2;
311 else
312 {
313 import core.internal.traits : hasUnsharedIndirections;
314 static assert(!hasUnsharedIndirections!V2,
315 "Copying `" ~ V2.stringof ~ "* writeThis` to `" ~
316 shared(T).stringof ~ "* here` would violate shared.");
317 alias Thunk2 = V2;
318 }
319 return cas(cast(T*)here, *cast(Thunk1*)&ifThis, *cast(Thunk2*)&writeThis);
320 }
321
322 /// Compare-and-set for `shared` reference type (`class`)
323 bool cas(T, V1, V2)(shared(T)* here, shared(V1) ifThis, shared(V2) writeThis)
324 pure nothrow @nogc @trusted
325 if (is(T == class))
326 in (atomicPtrIsProperlyAligned(here), "Argument `here` is not properly aligned")
327 {
328 return atomicCompareExchangeStrongNoResult!(succ, fail)(
329 cast(T*)here, cast(V1)ifThis, cast(V2)writeThis);
330 }
331
332 /// Compare-and-exchange for non-`shared` types
333 bool cas(T, V)(T* here, T* ifThis, V writeThis) pure nothrow @nogc @trusted
334 if (!is(T == shared) && !is(V == shared))
335 in (atomicPtrIsProperlyAligned(here), "Argument `here` is not properly aligned")
336 {
337 // resolve implicit conversions
338 T arg1 = writeThis;
339
340 return atomicCompareExchangeStrong!(succ, fail)(here, ifThis, writeThis);
341 }
342
343 /// Compare and exchange for mixed-`shared`ness types
344 bool cas(T, V1, V2)(shared(T)* here, V1* ifThis, V2 writeThis) pure nothrow @nogc @trusted
345 if (!is(T == class) && (is(T : V1) || is(shared T : V1)))
346 in (atomicPtrIsProperlyAligned(here), "Argument `here` is not properly aligned")
347 {
348 static if (is (V1 == shared U1, U1))
349 alias Thunk1 = U1;
350 else
351 {
352 import core.internal.traits : hasUnsharedIndirections;
353 static assert(!hasUnsharedIndirections!V1,
354 "Copying `" ~ shared(T).stringof ~ "* here` to `" ~
355 V1.stringof ~ "* ifThis` would violate shared.");
356 alias Thunk1 = V1;
357 }
358 static if (is (V2 == shared U2, U2))
359 alias Thunk2 = U2;
360 else
361 {
362 import core.internal.traits : hasUnsharedIndirections;
363 static assert(!hasUnsharedIndirections!V2,
364 "Copying `" ~ V2.stringof ~ "* writeThis` to `" ~
365 shared(T).stringof ~ "* here` would violate shared.");
366 alias Thunk2 = V2;
367 }
368 static assert (is(T : Thunk1),
369 "Mismatching types for `here` and `ifThis`: `" ~
370 shared(T).stringof ~ "` and `" ~ V1.stringof ~ "`.");
371 return cas(cast(T*)here, cast(Thunk1*)ifThis, *cast(Thunk2*)&writeThis);
372 }
373
374 /// Compare-and-exchange for `class`
375 bool cas(T, V)(shared(T)* here, shared(T)* ifThis, shared(V) writeThis)
376 pure nothrow @nogc @trusted
377 if (is(T == class))
378 in (atomicPtrIsProperlyAligned(here), "Argument `here` is not properly aligned")
379 {
380 return atomicCompareExchangeStrong!(succ, fail)(
381 cast(T*)here, cast(T*)ifThis, cast(V)writeThis);
382 }
383 }
384
385 /**
386 * Stores 'writeThis' to the memory referenced by 'here' if the value
387 * referenced by 'here' is equal to 'ifThis'.
388 * The 'weak' version of cas may spuriously fail. It is recommended to
389 * use `casWeak` only when `cas` would be used in a loop.
390 * This operation is both
391 * lock-free and atomic.
392 *
393 * Params:
394 * here = The address of the destination variable.
395 * writeThis = The value to store.
396 * ifThis = The comparison value.
397 *
398 * Returns:
399 * true if the store occurred, false if not.
400 */
401 bool casWeak(MemoryOrder succ = MemoryOrder.seq,MemoryOrder fail = MemoryOrder.seq,T,V1,V2)(T* here, V1 ifThis, V2 writeThis) pure nothrow @nogc @trusted
402 if (!is(T == shared) && is(T : V1))
403 in (atomicPtrIsProperlyAligned(here), "Argument `here` is not properly aligned")
404 {
405 // resolve implicit conversions
406 T arg1 = ifThis;
407 T arg2 = writeThis;
408
409 static if (__traits(isFloating, T))
410 {
411 alias IntTy = IntForFloat!T;
412 return atomicCompareExchangeWeakNoResult!(succ, fail)(cast(IntTy*)here, *cast(IntTy*)&arg1, *cast(IntTy*)&arg2);
413 }
414 else
415 return atomicCompareExchangeWeakNoResult!(succ, fail)(here, arg1, arg2);
416 }
417
418 /// Ditto
419 bool casWeak(MemoryOrder succ = MemoryOrder.seq,MemoryOrder fail = MemoryOrder.seq,T,V1,V2)(shared(T)* here, V1 ifThis, V2 writeThis) pure nothrow @nogc @trusted
420 if (!is(T == class) && (is(T : V1) || is(shared T : V1)))
421 in (atomicPtrIsProperlyAligned(here), "Argument `here` is not properly aligned")
422 {
423 static if (is (V1 == shared U1, U1))
424 alias Thunk1 = U1;
425 else
426 alias Thunk1 = V1;
427 static if (is (V2 == shared U2, U2))
428 alias Thunk2 = U2;
429 else
430 {
431 import core.internal.traits : hasUnsharedIndirections;
432 static assert(!hasUnsharedIndirections!V2, "Copying `" ~ V2.stringof ~ "* writeThis` to `" ~ shared(T).stringof ~ "* here` would violate shared.");
433 alias Thunk2 = V2;
434 }
435 return casWeak!(succ, fail)(cast(T*)here, *cast(Thunk1*)&ifThis, *cast(Thunk2*)&writeThis);
436 }
437
438 /// Ditto
439 bool casWeak(MemoryOrder succ = MemoryOrder.seq,MemoryOrder fail = MemoryOrder.seq,T,V1,V2)(shared(T)* here, shared(V1) ifThis, shared(V2) writeThis) pure nothrow @nogc @trusted
440 if (is(T == class))
441 in (atomicPtrIsProperlyAligned(here), "Argument `here` is not properly aligned")
442 {
443 return atomicCompareExchangeWeakNoResult!(succ, fail)(cast(T*)here, cast(V1)ifThis, cast(V2)writeThis);
444 }
445
446 /**
447 * Stores 'writeThis' to the memory referenced by 'here' if the value
448 * referenced by 'here' is equal to the value referenced by 'ifThis'.
449 * The prior value referenced by 'here' is written to `ifThis` and
450 * returned to the user.
451 * The 'weak' version of cas may spuriously fail. It is recommended to
452 * use `casWeak` only when `cas` would be used in a loop.
453 * This operation is both lock-free and atomic.
454 *
455 * Params:
456 * here = The address of the destination variable.
457 * writeThis = The value to store.
458 * ifThis = The address of the value to compare, and receives the prior value of `here` as output.
459 *
460 * Returns:
461 * true if the store occurred, false if not.
462 */
463 bool casWeak(MemoryOrder succ = MemoryOrder.seq,MemoryOrder fail = MemoryOrder.seq,T,V)(T* here, T* ifThis, V writeThis) pure nothrow @nogc @trusted
464 if (!is(T == shared S, S) && !is(V == shared U, U))
465 in (atomicPtrIsProperlyAligned(here), "Argument `here` is not properly aligned")
466 {
467 // resolve implicit conversions
468 T arg1 = writeThis;
469
470 static if (__traits(isFloating, T))
471 {
472 alias IntTy = IntForFloat!T;
473 return atomicCompareExchangeWeak!(succ, fail)(cast(IntTy*)here, cast(IntTy*)ifThis, *cast(IntTy*)&writeThis);
474 }
475 else
476 return atomicCompareExchangeWeak!(succ, fail)(here, ifThis, writeThis);
477 }
478
479 /// Ditto
480 bool casWeak(MemoryOrder succ = MemoryOrder.seq,MemoryOrder fail = MemoryOrder.seq,T,V1,V2)(shared(T)* here, V1* ifThis, V2 writeThis) pure nothrow @nogc @trusted
481 if (!is(T == class) && (is(T : V1) || is(shared T : V1)))
482 in (atomicPtrIsProperlyAligned(here), "Argument `here` is not properly aligned")
483 {
484 static if (is (V1 == shared U1, U1))
485 alias Thunk1 = U1;
486 else
487 {
488 import core.internal.traits : hasUnsharedIndirections;
489 static assert(!hasUnsharedIndirections!V1, "Copying `" ~ shared(T).stringof ~ "* here` to `" ~ V1.stringof ~ "* ifThis` would violate shared.");
490 alias Thunk1 = V1;
491 }
492 static if (is (V2 == shared U2, U2))
493 alias Thunk2 = U2;
494 else
495 {
496 import core.internal.traits : hasUnsharedIndirections;
497 static assert(!hasUnsharedIndirections!V2, "Copying `" ~ V2.stringof ~ "* writeThis` to `" ~ shared(T).stringof ~ "* here` would violate shared.");
498 alias Thunk2 = V2;
499 }
500 static assert (is(T : Thunk1), "Mismatching types for `here` and `ifThis`: `" ~ shared(T).stringof ~ "` and `" ~ V1.stringof ~ "`.");
501 return casWeak!(succ, fail)(cast(T*)here, cast(Thunk1*)ifThis, *cast(Thunk2*)&writeThis);
502 }
503
504 /// Ditto
505 bool casWeak(MemoryOrder succ = MemoryOrder.seq,MemoryOrder fail = MemoryOrder.seq,T,V)(shared(T)* here, shared(T)* ifThis, shared(V) writeThis) pure nothrow @nogc @trusted
506 if (is(T == class))
507 in (atomicPtrIsProperlyAligned(here), "Argument `here` is not properly aligned")
508 {
509 return atomicCompareExchangeWeak!(succ, fail)(cast(T*)here, cast(T*)ifThis, cast(V)writeThis);
510 }
511
512 /**
513 * Inserts a full load/store memory fence (on platforms that need it). This ensures
514 * that all loads and stores before a call to this function are executed before any
515 * loads and stores after the call.
516 */
517 void atomicFence(MemoryOrder order = MemoryOrder.seq)() pure nothrow @nogc @safe
518 {
519 core.internal.atomic.atomicFence!order();
520 }
521
522 /**
523 * Gives a hint to the processor that the calling thread is in a 'spin-wait' loop,
524 * allowing to more efficiently allocate resources.
525 */
526 void pause() pure nothrow @nogc @safe
527 {
528 core.internal.atomic.pause();
529 }
530
531 /**
532 * Performs the binary operation 'op' on val using 'mod' as the modifier.
533 *
534 * Params:
535 * val = The target variable.
536 * mod = The modifier to apply.
537 *
538 * Returns:
539 * The result of the operation.
540 */
541 TailShared!T atomicOp(string op, T, V1)(ref shared T val, V1 mod) pure nothrow @nogc @safe
542 if (__traits(compiles, mixin("*cast(T*)&val" ~ op ~ "mod")))
543 in (atomicValueIsProperlyAligned(val))
544 {
545 // binary operators
546 //
547 // + - * / % ^^ &
548 // | ^ << >> >>> ~ in
549 // == != < <= > >=
550 static if (op == "+" || op == "-" || op == "*" || op == "/" ||
551 op == "%" || op == "^^" || op == "&" || op == "|" ||
552 op == "^" || op == "<<" || op == ">>" || op == ">>>" ||
553 op == "~" || // skip "in"
554 op == "==" || op == "!=" || op == "<" || op == "<=" ||
555 op == ">" || op == ">=")
556 {
557 T get = atomicLoad!(MemoryOrder.raw, T)(val);
558 mixin("return get " ~ op ~ " mod;");
559 }
560 else
561 // assignment operators
562 //
563 // += -= *= /= %= ^^= &=
564 // |= ^= <<= >>= >>>= ~=
565 static if (op == "+=" && __traits(isIntegral, T) && __traits(isIntegral, V1) && T.sizeof <= size_t.sizeof && V1.sizeof <= size_t.sizeof)
566 {
567 return cast(T)(atomicFetchAdd(val, mod) + mod);
568 }
569 else static if (op == "-=" && __traits(isIntegral, T) && __traits(isIntegral, V1) && T.sizeof <= size_t.sizeof && V1.sizeof <= size_t.sizeof)
570 {
571 return cast(T)(atomicFetchSub(val, mod) - mod);
572 }
573 else static if (op == "+=" || op == "-=" || op == "*=" || op == "/=" ||
574 op == "%=" || op == "^^=" || op == "&=" || op == "|=" ||
575 op == "^=" || op == "<<=" || op == ">>=" || op == ">>>=") // skip "~="
576 {
577 T set, get = atomicLoad!(MemoryOrder.raw, T)(val);
578 do
579 {
580 set = get;
581 mixin("set " ~ op ~ " mod;");
582 } while (!casWeakByRef(val, get, set));
583 return set;
584 }
585 else
586 {
587 static assert(false, "Operation not supported.");
588 }
589 }
590
591
592 version (D_InlineAsm_X86)
593 {
594 enum has64BitXCHG = false;
595 enum has64BitCAS = true;
596 enum has128BitCAS = false;
597 }
598 else version (D_InlineAsm_X86_64)
599 {
600 enum has64BitXCHG = true;
601 enum has64BitCAS = true;
602 enum has128BitCAS = true;
603 }
604 else version (GNU)
605 {
606 import gcc.config;
607 enum has64BitCAS = GNU_Have_64Bit_Atomics;
608 enum has64BitXCHG = GNU_Have_64Bit_Atomics;
609 enum has128BitCAS = GNU_Have_LibAtomic;
610 }
611 else
612 {
613 enum has64BitXCHG = false;
614 enum has64BitCAS = false;
615 enum has128BitCAS = false;
616 }
617
618 private
619 {
620 bool atomicValueIsProperlyAligned(T)(ref T val) pure nothrow @nogc @trusted
621 {
622 return atomicPtrIsProperlyAligned(&val);
623 }
624
625 bool atomicPtrIsProperlyAligned(T)(T* ptr) pure nothrow @nogc @safe
626 {
627 // NOTE: Strictly speaking, the x86 supports atomic operations on
628 // unaligned values. However, this is far slower than the
629 // common case, so such behavior should be prohibited.
630 static if (T.sizeof > size_t.sizeof)
631 {
632 version (X86)
633 {
634 // cmpxchg8b only requires 4-bytes alignment
635 return cast(size_t)ptr % size_t.sizeof == 0;
636 }
637 else
638 {
639 // e.g., x86_64 cmpxchg16b requires 16-bytes alignment
640 return cast(size_t)ptr % T.sizeof == 0;
641 }
642 }
643 else
644 {
645 return cast(size_t)ptr % T.sizeof == 0;
646 }
647 }
648
649 template IntForFloat(F)
650 if (__traits(isFloating, F))
651 {
652 static if (F.sizeof == 4)
653 alias IntForFloat = uint;
654 else static if (F.sizeof == 8)
655 alias IntForFloat = ulong;
656 else
657 static assert (false, "Invalid floating point type: " ~ F.stringof ~ ", only support `float` and `double`.");
658 }
659
660 template IntForStruct(S)
661 if (is(S == struct))
662 {
663 static if (S.sizeof == 1)
664 alias IntForFloat = ubyte;
665 else static if (F.sizeof == 2)
666 alias IntForFloat = ushort;
667 else static if (F.sizeof == 4)
668 alias IntForFloat = uint;
669 else static if (F.sizeof == 8)
670 alias IntForFloat = ulong;
671 else static if (F.sizeof == 16)
672 alias IntForFloat = ulong[2]; // TODO: what's the best type here? slice/delegates pass in registers...
673 else
674 static assert (ValidateStruct!S);
675 }
676
677 template ValidateStruct(S)
678 if (is(S == struct))
679 {
680 import core.internal.traits : hasElaborateAssign;
681
682 // `(x & (x-1)) == 0` checks that x is a power of 2.
683 static assert (S.sizeof <= size_t.sizeof * 2
684 && (S.sizeof & (S.sizeof - 1)) == 0,
685 S.stringof ~ " has invalid size for atomic operations.");
686 static assert (!hasElaborateAssign!S, S.stringof ~ " may not have an elaborate assignment when used with atomic operations.");
687
688 enum ValidateStruct = true;
689 }
690
691 // TODO: it'd be nice if we had @trusted scopes; we could remove this...
692 bool casWeakByRef(T,V1,V2)(ref T value, ref V1 ifThis, V2 writeThis) pure nothrow @nogc @trusted
693 {
694 return casWeak(&value, &ifThis, writeThis);
695 }
696
697 /* Construct a type with a shared tail, and if possible with an unshared
698 head. */
699 template TailShared(U) if (!is(U == shared))
700 {
701 alias TailShared = .TailShared!(shared U);
702 }
703 template TailShared(S) if (is(S == shared))
704 {
705 // Get the unshared variant of S.
706 static if (is(S U == shared U)) {}
707 else static assert(false, "Should never be triggered. The `static " ~
708 "if` declares `U` as the unshared version of the shared type " ~
709 "`S`. `S` is explicitly declared as shared, so getting `U` " ~
710 "should always work.");
711
712 static if (is(S : U))
713 alias TailShared = U;
714 else static if (is(S == struct))
715 {
716 enum implName = () {
717 /* Start with "_impl". If S has a field with that name, append
718 underscores until the clash is resolved. */
719 string name = "_impl";
720 string[] fieldNames;
721 static foreach (alias field; S.tupleof)
722 {
723 fieldNames ~= __traits(identifier, field);
724 }
725 static bool canFind(string[] haystack, string needle)
726 {
727 foreach (candidate; haystack)
728 {
729 if (candidate == needle) return true;
730 }
731 return false;
732 }
733 while (canFind(fieldNames, name)) name ~= "_";
734 return name;
735 } ();
736 struct TailShared
737 {
738 static foreach (i, alias field; S.tupleof)
739 {
740 /* On @trusted: This is casting the field from shared(Foo)
741 to TailShared!Foo. The cast is safe because the field has
742 been loaded and is not shared anymore. */
743 mixin("
744 @trusted @property
745 ref " ~ __traits(identifier, field) ~ "()
746 {
747 alias R = TailShared!(typeof(field));
748 return * cast(R*) &" ~ implName ~ ".tupleof[i];
749 }
750 ");
751 }
752 mixin("
753 S " ~ implName ~ ";
754 alias " ~ implName ~ " this;
755 ");
756 }
757 }
758 else
759 alias TailShared = S;
760 }
761 @safe unittest
762 {
763 // No tail (no indirections) -> fully unshared.
764
765 static assert(is(TailShared!int == int));
766 static assert(is(TailShared!(shared int) == int));
767
768 static struct NoIndir { int i; }
769 static assert(is(TailShared!NoIndir == NoIndir));
770 static assert(is(TailShared!(shared NoIndir) == NoIndir));
771
772 // Tail can be independently shared or is already -> tail-shared.
773
774 static assert(is(TailShared!(int*) == shared(int)*));
775 static assert(is(TailShared!(shared int*) == shared(int)*));
776 static assert(is(TailShared!(shared(int)*) == shared(int)*));
777
778 static assert(is(TailShared!(int[]) == shared(int)[]));
779 static assert(is(TailShared!(shared int[]) == shared(int)[]));
780 static assert(is(TailShared!(shared(int)[]) == shared(int)[]));
781
782 static struct S1 { shared int* p; }
783 static assert(is(TailShared!S1 == S1));
784 static assert(is(TailShared!(shared S1) == S1));
785
786 static struct S2 { shared(int)* p; }
787 static assert(is(TailShared!S2 == S2));
788 static assert(is(TailShared!(shared S2) == S2));
789
790 // Tail follows shared-ness of head -> fully shared.
791
792 static class C { int i; }
793 static assert(is(TailShared!C == shared C));
794 static assert(is(TailShared!(shared C) == shared C));
795
796 /* However, structs get a wrapper that has getters which cast to
797 TailShared. */
798
799 static struct S3 { int* p; int _impl; int _impl_; int _impl__; }
800 static assert(!is(TailShared!S3 : S3));
801 static assert(is(TailShared!S3 : shared S3));
802 static assert(is(TailShared!(shared S3) == TailShared!S3));
803
804 static struct S4 { shared(int)** p; }
805 static assert(!is(TailShared!S4 : S4));
806 static assert(is(TailShared!S4 : shared S4));
807 static assert(is(TailShared!(shared S4) == TailShared!S4));
808 }
809 }
810
811
812 ////////////////////////////////////////////////////////////////////////////////
813 // Unit Tests
814 ////////////////////////////////////////////////////////////////////////////////
815
816
817 version (CoreUnittest)
818 {
819 version (D_LP64)
820 {
821 enum hasDWCAS = has128BitCAS;
822 }
823 else
824 {
825 enum hasDWCAS = has64BitCAS;
826 }
827
828 void testXCHG(T)(T val) pure nothrow @nogc @trusted
829 in
830 {
831 assert(val !is T.init);
832 }
833 do
834 {
835 T base = cast(T)null;
836 shared(T) atom = cast(shared(T))null;
837
838 assert(base !is val, T.stringof);
839 assert(atom is base, T.stringof);
840
841 assert(atomicExchange(&atom, val) is base, T.stringof);
842 assert(atom is val, T.stringof);
843 }
844
845 void testCAS(T)(T val) pure nothrow @nogc @trusted
846 in
847 {
848 assert(val !is T.init);
849 }
850 do
851 {
852 T base = cast(T)null;
853 shared(T) atom = cast(shared(T))null;
854
855 assert(base !is val, T.stringof);
856 assert(atom is base, T.stringof);
857
858 assert(cas(&atom, base, val), T.stringof);
859 assert(atom is val, T.stringof);
860 assert(!cas(&atom, base, base), T.stringof);
861 assert(atom is val, T.stringof);
862
863 atom = cast(shared(T))null;
864
865 shared(T) arg = base;
866 assert(cas(&atom, &arg, val), T.stringof);
867 assert(arg is base, T.stringof);
868 assert(atom is val, T.stringof);
869
870 arg = base;
871 assert(!cas(&atom, &arg, base), T.stringof);
872 assert(arg is val, T.stringof);
873 assert(atom is val, T.stringof);
874 }
875
876 void testLoadStore(MemoryOrder ms = MemoryOrder.seq, T)(T val = T.init + 1) pure nothrow @nogc @trusted
877 {
878 T base = cast(T) 0;
879 shared(T) atom = cast(T) 0;
880
881 assert(base !is val);
882 assert(atom is base);
883 atomicStore!(ms)(atom, val);
884 base = atomicLoad!(ms)(atom);
885
886 assert(base is val, T.stringof);
887 assert(atom is val);
888 }
889
890
891 void testType(T)(T val = T.init + 1) pure nothrow @nogc @safe
892 {
893 static if (T.sizeof < 8 || has64BitXCHG)
894 testXCHG!(T)(val);
895 testCAS!(T)(val);
896 testLoadStore!(MemoryOrder.seq, T)(val);
897 testLoadStore!(MemoryOrder.raw, T)(val);
898 }
899
900 @betterC @safe pure nothrow unittest
901 {
902 testType!(bool)();
903
904 testType!(byte)();
905 testType!(ubyte)();
906
907 testType!(short)();
908 testType!(ushort)();
909
910 testType!(int)();
911 testType!(uint)();
912 }
913
914 @safe pure nothrow unittest
915 {
916
917 testType!(shared int*)();
918
919 static interface Inter {}
920 static class KlassImpl : Inter {}
921 testXCHG!(shared Inter)(new shared(KlassImpl));
922 testCAS!(shared Inter)(new shared(KlassImpl));
923
924 static class Klass {}
925 testXCHG!(shared Klass)(new shared(Klass));
926 testCAS!(shared Klass)(new shared(Klass));
927
928 testXCHG!(shared int)(42);
929
930 testType!(float)(0.1f);
931
932 static if (has64BitCAS)
933 {
934 testType!(double)(0.1);
935 testType!(long)();
936 testType!(ulong)();
937 }
938 static if (has128BitCAS)
939 {
940 () @trusted
941 {
942 align(16) struct Big { long a, b; }
943
944 shared(Big) atom;
945 shared(Big) base;
946 shared(Big) arg;
947 shared(Big) val = Big(1, 2);
948
949 assert(cas(&atom, arg, val), Big.stringof);
950 assert(atom is val, Big.stringof);
951 assert(!cas(&atom, arg, val), Big.stringof);
952 assert(atom is val, Big.stringof);
953
954 atom = Big();
955 assert(cas(&atom, &arg, val), Big.stringof);
956 assert(arg is base, Big.stringof);
957 assert(atom is val, Big.stringof);
958
959 arg = Big();
960 assert(!cas(&atom, &arg, base), Big.stringof);
961 assert(arg is val, Big.stringof);
962 assert(atom is val, Big.stringof);
963 }();
964 }
965
966 shared(size_t) i;
967
968 atomicOp!"+="(i, cast(size_t) 1);
969 assert(i == 1);
970
971 atomicOp!"-="(i, cast(size_t) 1);
972 assert(i == 0);
973
974 shared float f = 0.1f;
975 atomicOp!"+="(f, 0.1f);
976 assert(f > 0.1999f && f < 0.2001f);
977
978 static if (has64BitCAS)
979 {
980 shared double d = 0.1;
981 atomicOp!"+="(d, 0.1);
982 assert(d > 0.1999 && d < 0.2001);
983 }
984 }
985
986 @betterC pure nothrow unittest
987 {
988 static if (has128BitCAS)
989 {
990 struct DoubleValue
991 {
992 long value1;
993 long value2;
994 }
995
996 align(16) shared DoubleValue a;
997 atomicStore(a, DoubleValue(1,2));
998 assert(a.value1 == 1 && a.value2 ==2);
999
1000 while (!cas(&a, DoubleValue(1,2), DoubleValue(3,4))){}
1001 assert(a.value1 == 3 && a.value2 ==4);
1002
1003 align(16) DoubleValue b = atomicLoad(a);
1004 assert(b.value1 == 3 && b.value2 ==4);
1005 }
1006
1007 static if (hasDWCAS)
1008 {
1009 static struct List { size_t gen; List* next; }
1010 shared(List) head;
1011 assert(cas(&head, shared(List)(0, null), shared(List)(1, cast(List*)1)));
1012 assert(head.gen == 1);
1013 assert(cast(size_t)head.next == 1);
1014 }
1015
1016 // https://issues.dlang.org/show_bug.cgi?id=20629
1017 static struct Struct
1018 {
1019 uint a, b;
1020 }
1021 shared Struct s1 = Struct(1, 2);
1022 atomicStore(s1, Struct(3, 4));
1023 assert(cast(uint) s1.a == 3);
1024 assert(cast(uint) s1.b == 4);
1025 }
1026
1027 // https://issues.dlang.org/show_bug.cgi?id=20844
1028 static if (hasDWCAS)
1029 {
1030 debug: // tests CAS in-contract
1031
1032 pure nothrow unittest
1033 {
1034 import core.exception : AssertError;
1035
1036 align(16) shared ubyte[2 * size_t.sizeof + 1] data;
1037 auto misalignedPointer = cast(size_t[2]*) &data[1];
1038 size_t[2] x;
1039
1040 try
1041 cas(misalignedPointer, x, x);
1042 catch (AssertError)
1043 return;
1044
1045 assert(0, "should have failed");
1046 }
1047 }
1048
1049 @betterC pure nothrow @nogc @safe unittest
1050 {
1051 int a;
1052 if (casWeak!(MemoryOrder.acq_rel, MemoryOrder.raw)(&a, 0, 4))
1053 assert(a == 4);
1054 }
1055
1056 @betterC pure nothrow unittest
1057 {
1058 static struct S { int val; }
1059 auto s = shared(S)(1);
1060
1061 shared(S*) ptr;
1062
1063 // head unshared
1064 shared(S)* ifThis = null;
1065 shared(S)* writeThis = &s;
1066 assert(ptr is null);
1067 assert(cas(&ptr, ifThis, writeThis));
1068 assert(ptr is writeThis);
1069
1070 // head shared
1071 shared(S*) ifThis2 = writeThis;
1072 shared(S*) writeThis2 = null;
1073 assert(cas(&ptr, ifThis2, writeThis2));
1074 assert(ptr is null);
1075 }
1076
1077 // === atomicFetchAdd and atomicFetchSub operations ====
1078 @betterC pure nothrow @nogc @safe unittest
1079 {
1080 shared ubyte u8 = 1;
1081 shared ushort u16 = 2;
1082 shared uint u32 = 3;
1083 shared byte i8 = 5;
1084 shared short i16 = 6;
1085 shared int i32 = 7;
1086
1087 assert(atomicOp!"+="(u8, 8) == 9);
1088 assert(atomicOp!"+="(u16, 8) == 10);
1089 assert(atomicOp!"+="(u32, 8) == 11);
1090 assert(atomicOp!"+="(i8, 8) == 13);
1091 assert(atomicOp!"+="(i16, 8) == 14);
1092 assert(atomicOp!"+="(i32, 8) == 15);
1093 version (D_LP64)
1094 {
1095 shared ulong u64 = 4;
1096 shared long i64 = 8;
1097 assert(atomicOp!"+="(u64, 8) == 12);
1098 assert(atomicOp!"+="(i64, 8) == 16);
1099 }
1100 }
1101
1102 @betterC pure nothrow @nogc unittest
1103 {
1104 byte[10] byteArray = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19];
1105 ulong[10] ulongArray = [2, 4, 6, 8, 10, 12, 14, 16, 19, 20];
1106
1107 {
1108 auto array = byteArray;
1109 byte* ptr = &array[0];
1110 byte* prevPtr = atomicFetchAdd(ptr, 3);
1111 assert(prevPtr == &array[0]);
1112 assert(*prevPtr == 1);
1113 assert(*ptr == 7);
1114 }
1115 {
1116 auto array = ulongArray;
1117 ulong* ptr = &array[0];
1118 ulong* prevPtr = atomicFetchAdd(ptr, 3);
1119 assert(prevPtr == &array[0]);
1120 assert(*prevPtr == 2);
1121 assert(*ptr == 8);
1122 }
1123 }
1124
1125 @betterC pure nothrow @nogc @safe unittest
1126 {
1127 shared ubyte u8 = 1;
1128 shared ushort u16 = 2;
1129 shared uint u32 = 3;
1130 shared byte i8 = 5;
1131 shared short i16 = 6;
1132 shared int i32 = 7;
1133
1134 assert(atomicOp!"-="(u8, 1) == 0);
1135 assert(atomicOp!"-="(u16, 1) == 1);
1136 assert(atomicOp!"-="(u32, 1) == 2);
1137 assert(atomicOp!"-="(i8, 1) == 4);
1138 assert(atomicOp!"-="(i16, 1) == 5);
1139 assert(atomicOp!"-="(i32, 1) == 6);
1140 version (D_LP64)
1141 {
1142 shared ulong u64 = 4;
1143 shared long i64 = 8;
1144 assert(atomicOp!"-="(u64, 1) == 3);
1145 assert(atomicOp!"-="(i64, 1) == 7);
1146 }
1147 }
1148
1149 @betterC pure nothrow @nogc unittest
1150 {
1151 byte[10] byteArray = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19];
1152 ulong[10] ulongArray = [2, 4, 6, 8, 10, 12, 14, 16, 19, 20];
1153
1154 {
1155 auto array = byteArray;
1156 byte* ptr = &array[5];
1157 byte* prevPtr = atomicFetchSub(ptr, 4);
1158 assert(prevPtr == &array[5]);
1159 assert(*prevPtr == 11);
1160 assert(*ptr == 3); // https://issues.dlang.org/show_bug.cgi?id=21578
1161 }
1162 {
1163 auto array = ulongArray;
1164 ulong* ptr = &array[5];
1165 ulong* prevPtr = atomicFetchSub(ptr, 4);
1166 assert(prevPtr == &array[5]);
1167 assert(*prevPtr == 12);
1168 assert(*ptr == 4); // https://issues.dlang.org/show_bug.cgi?id=21578
1169 }
1170 }
1171
1172 @betterC pure nothrow @nogc @safe unittest // https://issues.dlang.org/show_bug.cgi?id=16651
1173 {
1174 shared ulong a = 2;
1175 uint b = 1;
1176 atomicOp!"-="(a, b);
1177 assert(a == 1);
1178
1179 shared uint c = 2;
1180 ubyte d = 1;
1181 atomicOp!"-="(c, d);
1182 assert(c == 1);
1183 }
1184
1185 pure nothrow @safe unittest // https://issues.dlang.org/show_bug.cgi?id=16230
1186 {
1187 shared int i;
1188 static assert(is(typeof(atomicLoad(i)) == int));
1189
1190 shared int* p;
1191 static assert(is(typeof(atomicLoad(p)) == shared(int)*));
1192
1193 shared int[] a;
1194 static if (__traits(compiles, atomicLoad(a)))
1195 {
1196 static assert(is(typeof(atomicLoad(a)) == shared(int)[]));
1197 }
1198
1199 static struct S { int* _impl; }
1200 shared S s;
1201 static assert(is(typeof(atomicLoad(s)) : shared S));
1202 static assert(is(typeof(atomicLoad(s)._impl) == shared(int)*));
1203 auto u = atomicLoad(s);
1204 assert(u._impl is null);
1205 u._impl = new shared int(42);
1206 assert(atomicLoad(*u._impl) == 42);
1207
1208 static struct S2 { S s; }
1209 shared S2 s2;
1210 static assert(is(typeof(atomicLoad(s2).s) == TailShared!S));
1211
1212 static struct S3 { size_t head; int* tail; }
1213 shared S3 s3;
1214 static if (__traits(compiles, atomicLoad(s3)))
1215 {
1216 static assert(is(typeof(atomicLoad(s3).head) == size_t));
1217 static assert(is(typeof(atomicLoad(s3).tail) == shared(int)*));
1218 }
1219
1220 static class C { int i; }
1221 shared C c;
1222 static assert(is(typeof(atomicLoad(c)) == shared C));
1223
1224 static struct NoIndirections { int i; }
1225 shared NoIndirections n;
1226 static assert(is(typeof(atomicLoad(n)) == NoIndirections));
1227 }
1228
1229 unittest // Issue 21631
1230 {
1231 shared uint si1 = 45;
1232 shared uint si2 = 38;
1233 shared uint* psi = &si1;
1234
1235 assert((&psi).cas(cast(const) psi, &si2));
1236 }
1237 }