Skip to content

Commit 9a4ca42

Browse files
Replace "unchecked" arithmetic with "wrapping" in optimization guide. (swiftlang#31463)
* Replace "unchecked" arithmetic with "wrapping" in optimization guide. Previously, this section talked about "unchecked" arithmetic operations; that's not what &+ and friends are. They are wrapping operations with fully-defined behavior (unlike nsw llvm ops, which are actually "unchecked"). * Update docs/OptimizationTips.rst
1 parent 1a35681 commit 9a4ca42

File tree

1 file changed

+14
-7
lines changed

1 file changed

+14
-7
lines changed

docs/OptimizationTips.rst

+14-7
Original file line numberDiff line numberDiff line change
@@ -283,30 +283,37 @@ through the usage of ``inout`` parameters:
283283
var a = [1, 2, 3]
284284
append_one_in_place(&a)
285285

286-
Unchecked operations
286+
Wrapping operations
287287
====================
288288

289289
Swift eliminates integer overflow bugs by checking for overflow when performing
290-
normal arithmetic. These checks are not appropriate in high performance code
291-
where one knows that no memory safety issues can result.
290+
normal arithmetic. These checks may not be appropriate in high performance code
291+
if one either knows that overflow cannot occur, or that the result of
292+
allowing the operation to wrap around is correct.
292293

293-
Advice: Use unchecked integer arithmetic when you can prove that overflow cannot occur
294+
Advice: Use wrapping integer arithmetic when you can prove that overflow cannot occur
294295
---------------------------------------------------------------------------------------
295296

296-
In performance-critical code you can elide overflow checks if you know it is
297-
safe.
297+
In performance-critical code you can use wrapping arithmetic to avoid overflow
298+
checks if you know it is safe.
298299

299300
::
300301

301302
a: [Int]
302303
b: [Int]
303304
c: [Int]
304305

305-
// Precondition: for all a[i], b[i]: a[i] + b[i] does not overflow!
306+
// Precondition: for all a[i], b[i]: a[i] + b[i] either does not overflow,
307+
// or the result of wrapping is desired.
306308
for i in 0 ... n {
307309
c[i] = a[i] &+ b[i]
308310
}
309311

312+
It's important to note that the behavior of the ``&+``, ``&-``, and ``&*``
313+
operators is fully-defined; the result simply wraps around if it would overflow.
314+
Thus, ``Int.max &+ 1`` is guaranteed to be ``Int.min`` (unlike in C, where
315+
``INT_MAX + 1`` is undefined behavior).
316+
310317
Generics
311318
========
312319

0 commit comments

Comments
 (0)