aboutsummaryrefslogtreecommitdiff
path: root/lib/compiler_rt/addo.zig
blob: 610d6206904b8fe5368d56330448df3a59e8a3e6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
const std = @import("std");
const common = @import("./common.zig");
pub const panic = @import("common.zig").panic;

comptime {
    @export(&__addosi4, .{ .name = "__addosi4", .linkage = common.linkage, .visibility = common.visibility });
    @export(&__addodi4, .{ .name = "__addodi4", .linkage = common.linkage, .visibility = common.visibility });
    @export(&__addoti4, .{ .name = "__addoti4", .linkage = common.linkage, .visibility = common.visibility });
}

// addo - add overflow
// * return a+%b.
// * return if a+b overflows => 1 else => 0
// - addoXi4_generic as default

inline fn addoXi4_generic(comptime ST: type, a: ST, b: ST, overflow: *c_int) ST {
    @setRuntimeSafety(common.test_safety);
    overflow.* = 0;
    const sum: ST = a +% b;
    // Hackers Delight: section Overflow Detection, subsection Signed Add/Subtract
    // Let sum = a +% b == a + b + carry == wraparound addition.
    // Overflow in a+b+carry occurs, iff a and b have opposite signs
    // and the sign of a+b+carry is the same as a (or equivalently b).
    // Slower routine: res = ~(a ^ b) & ((sum ^ a)
    // Faster routine: res = (sum ^ a) & (sum ^ b)
    // Overflow occurred, iff (res < 0)
    if (((sum ^ a) & (sum ^ b)) < 0)
        overflow.* = 1;
    return sum;
}

pub fn __addosi4(a: i32, b: i32, overflow: *c_int) callconv(.c) i32 {
    return addoXi4_generic(i32, a, b, overflow);
}
pub fn __addodi4(a: i64, b: i64, overflow: *c_int) callconv(.c) i64 {
    return addoXi4_generic(i64, a, b, overflow);
}
pub fn __addoti4(a: i128, b: i128, overflow: *c_int) callconv(.c) i128 {
    return addoXi4_generic(i128, a, b, overflow);
}

test {
    _ = @import("addosi4_test.zig");
    _ = @import("addodi4_test.zig");
    _ = @import("addoti4_test.zig");
}