aboutsummaryrefslogtreecommitdiff
path: root/lib/std/special/compiler_rt/multi3.zig
blob: d417c79ff212d41209f1ff09a54d55ea91fe8eba (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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// SPDX-License-Identifier: MIT
// Copyright (c) 2015-2021 Zig Contributors
// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
// The MIT license requires this copyright notice to be included in all copies
// and substantial portions of the software.
const builtin = @import("builtin");
const compiler_rt = @import("../compiler_rt.zig");

// Ported from git@github.com:llvm-project/llvm-project-20170507.git
// ae684fad6d34858c014c94da69c15e7774a633c3
// 2018-08-13

pub fn __multi3(a: i128, b: i128) callconv(.C) i128 {
    @setRuntimeSafety(builtin.is_test);
    const x = twords{ .all = a };
    const y = twords{ .all = b };
    var r = twords{ .all = __mulddi3(x.s.low, y.s.low) };
    r.s.high +%= x.s.high *% y.s.low +% x.s.low *% y.s.high;
    return r.all;
}

const v128 = @import("std").meta.Vector(2, u64);
pub fn __multi3_windows_x86_64(a: v128, b: v128) callconv(.C) v128 {
    return @bitCast(v128, @call(.{ .modifier = .always_inline }, __multi3, .{
        @bitCast(i128, a),
        @bitCast(i128, b),
    }));
}

fn __mulddi3(a: u64, b: u64) i128 {
    const bits_in_dword_2 = (@sizeOf(i64) * 8) / 2;
    const lower_mask = ~@as(u64, 0) >> bits_in_dword_2;
    var r: twords = undefined;
    r.s.low = (a & lower_mask) *% (b & lower_mask);
    var t: u64 = r.s.low >> bits_in_dword_2;
    r.s.low &= lower_mask;
    t +%= (a >> bits_in_dword_2) *% (b & lower_mask);
    r.s.low +%= (t & lower_mask) << bits_in_dword_2;
    r.s.high = t >> bits_in_dword_2;
    t = r.s.low >> bits_in_dword_2;
    r.s.low &= lower_mask;
    t +%= (b >> bits_in_dword_2) *% (a & lower_mask);
    r.s.low +%= (t & lower_mask) << bits_in_dword_2;
    r.s.high +%= t >> bits_in_dword_2;
    r.s.high +%= (a >> bits_in_dword_2) *% (b >> bits_in_dword_2);
    return r.all;
}

const twords = extern union {
    all: i128,
    s: S,

    const S = if (builtin.endian == .Little)
        struct {
            low: u64,
            high: u64,
        }
    else
        struct {
            high: u64,
            low: u64,
        };
};

test "import multi3" {
    _ = @import("multi3_test.zig");
}