1
//! Ratio arithmetic and comparison that never wraps (ISS-086). Operands are
2
//! cross-reduced by their GCDs before any product, so a result that fits in
3
//! 64 bits is computed exactly even when the naive cross products would not;
4
//! every remaining product, sum and difference goes through a checked helper
5
//! that throws `ARITHMETIC-OVERFLOW` instead of wrapping.
6

            
7
use super::CompileContext;
8
use super::exception::ConditionTrap;
9
use wasm_encoder::{BlockType, Function, Instruction, ValType};
10

            
11
const NUM: u32 = 0;
12
const DEN: u32 = 1;
13

            
14
/// The checked i64 operations, in their registration order.
15
pub(super) const CHECKED_OPS: [&str; 3] = ["i64_mul_checked", "i64_add_checked", "i64_sub_checked"];
16

            
17
impl CompileContext {
18
    /// `i64_mul_checked` / `i64_add_checked` / `i64_sub_checked(a, b) -> i64`.
19
2352712
    pub(super) fn build_checked_i64_bodies(&mut self, overflow: &ConditionTrap) {
20
2352712
        self.pending_helpers.push(checked_mul_body(overflow));
21
2352712
        self.pending_helpers
22
2352712
            .push(checked_sum_body(overflow, &Instruction::I64Add, (1, 2)));
23
2352712
        self.pending_helpers
24
2352712
            .push(checked_sum_body(overflow, &Instruction::I64Sub, (0, 1)));
25
2352712
    }
26

            
27
    /// `ratio_add` / `ratio_sub` / `ratio_mul` / `ratio_div(a, b) -> ratio`.
28
2352712
    pub(super) fn build_ratio_binop_bodies(&mut self, div_trap: &ConditionTrap) {
29
2352712
        let ops = self.ratio_ops();
30
2352712
        self.pending_helpers.push(ops.sum_body(ops.add_checked));
31
2352712
        self.pending_helpers.push(ops.sum_body(ops.sub_checked));
32
2352712
        self.pending_helpers.push(ops.mul_body());
33
2352712
        self.pending_helpers.push(ops.div_body(div_trap));
34
2352712
    }
35

            
36
    /// `ratio_eq` / `ratio_lt(a, b) -> i32`.
37
2352712
    pub(super) fn build_ratio_cmp_bodies(&mut self) {
38
2352712
        let ops = self.ratio_ops();
39
2352712
        self.pending_helpers.push(ops.eq_body());
40
2352712
        self.pending_helpers.push(ops.lt_body());
41
2352712
    }
42

            
43
4705424
    fn ratio_ops(&self) -> RatioOps {
44
4705424
        RatioOps {
45
4705424
            ratio: self.ids.ty_ratio,
46
4705424
            gcd: self.ids.gcd,
47
4705424
            ratio_new: self.ids.ratio_new,
48
4705424
            mul_checked: self.ids.i64_mul_checked,
49
4705424
            add_checked: self.ids.i64_add_checked,
50
4705424
            sub_checked: self.ids.i64_sub_checked,
51
4705424
        }
52
4705424
    }
53
}
54

            
55
/// The function indices the ratio bodies call.
56
struct RatioOps {
57
    ratio: u32,
58
    gcd: u32,
59
    ratio_new: u32,
60
    mul_checked: u32,
61
    add_checked: u32,
62
    sub_checked: u32,
63
}
64

            
65
impl RatioOps {
66
110577464
    fn field(&self, f: &mut Function, local: u32, field: u32) {
67
110577464
        f.instruction(&Instruction::LocalGet(local));
68
110577464
        f.instruction(&Instruction::StructGet {
69
110577464
            struct_type_index: self.ratio,
70
110577464
            field_index: field,
71
110577464
        });
72
110577464
    }
73

            
74
    /// Pushes `field(local) / g`, `g` held in local `g`.
75
47054240
    fn reduced(&self, f: &mut Function, local: u32, field: u32, g: u32) {
76
47054240
        self.field(f, local, field);
77
47054240
        f.instruction(&Instruction::LocalGet(g));
78
47054240
        f.instruction(&Instruction::I64DivS);
79
47054240
    }
80

            
81
    /// Sets local `into` to `gcd(field_a(a), field_b(b))`.
82
21174408
    fn gcd_into(&self, f: &mut Function, field_a: (u32, u32), field_b: (u32, u32), into: u32) {
83
21174408
        self.field(f, field_a.0, field_a.1);
84
21174408
        self.field(f, field_b.0, field_b.1);
85
21174408
        f.instruction(&Instruction::Call(self.gcd));
86
21174408
        f.instruction(&Instruction::LocalSet(into));
87
21174408
    }
88

            
89
    /// `a ± b` over the least common denominator `a.den * (b.den / g)`.
90
4705424
    fn sum_body(&self, combine: u32) -> Function {
91
4705424
        let mut f = Function::new([(1, ValType::I64)]);
92
4705424
        let g = 2;
93
4705424
        self.gcd_into(&mut f, (0, DEN), (1, DEN), g);
94
4705424
        self.field(&mut f, 0, NUM);
95
4705424
        self.reduced(&mut f, 1, DEN, g);
96
4705424
        f.instruction(&Instruction::Call(self.mul_checked));
97
4705424
        self.field(&mut f, 1, NUM);
98
4705424
        self.reduced(&mut f, 0, DEN, g);
99
4705424
        f.instruction(&Instruction::Call(self.mul_checked));
100
4705424
        f.instruction(&Instruction::Call(combine));
101
4705424
        self.field(&mut f, 0, DEN);
102
4705424
        self.reduced(&mut f, 1, DEN, g);
103
4705424
        f.instruction(&Instruction::Call(self.mul_checked));
104
4705424
        f.instruction(&Instruction::Call(self.ratio_new));
105
4705424
        f.instruction(&Instruction::End);
106
4705424
        f
107
4705424
    }
108

            
109
    /// `a * b`, each numerator first cancelled against the other denominator.
110
2352712
    fn mul_body(&self) -> Function {
111
2352712
        let mut f = Function::new([(2, ValType::I64)]);
112
2352712
        let (g1, g2) = (2, 3);
113
2352712
        self.gcd_into(&mut f, (0, NUM), (1, DEN), g1);
114
2352712
        self.gcd_into(&mut f, (1, NUM), (0, DEN), g2);
115
2352712
        self.product(&mut f, (0, NUM, g1), (1, NUM, g2));
116
2352712
        self.product(&mut f, (0, DEN, g2), (1, DEN, g1));
117
2352712
        f.instruction(&Instruction::Call(self.ratio_new));
118
2352712
        f.instruction(&Instruction::End);
119
2352712
        f
120
2352712
    }
121

            
122
    /// `a / b = a * (b.den / b.num)`; a zero divisor throws before any gcd.
123
2352712
    fn div_body(&self, div_trap: &ConditionTrap) -> Function {
124
2352712
        let mut f = Function::new([(2, ValType::I64)]);
125
2352712
        let (g1, g2) = (2, 3);
126
2352712
        self.field(&mut f, 1, NUM);
127
2352712
        f.instruction(&Instruction::I64Eqz);
128
2352712
        f.instruction(&Instruction::If(BlockType::Empty));
129
2352712
        div_trap.emit_throw(&mut f);
130
2352712
        f.instruction(&Instruction::End);
131
2352712
        self.gcd_into(&mut f, (0, NUM), (1, NUM), g1);
132
2352712
        self.gcd_into(&mut f, (0, DEN), (1, DEN), g2);
133
2352712
        self.product(&mut f, (0, NUM, g1), (1, DEN, g2));
134
2352712
        self.product(&mut f, (0, DEN, g2), (1, NUM, g1));
135
2352712
        f.instruction(&Instruction::Call(self.ratio_new));
136
2352712
        f.instruction(&Instruction::End);
137
2352712
        f
138
2352712
    }
139

            
140
    /// Pushes the checked product of two reduced fields.
141
9410848
    fn product(&self, f: &mut Function, left: (u32, u32, u32), right: (u32, u32, u32)) {
142
9410848
        self.reduced(f, left.0, left.1, left.2);
143
9410848
        self.reduced(f, right.0, right.1, right.2);
144
9410848
        f.instruction(&Instruction::Call(self.mul_checked));
145
9410848
    }
146

            
147
    /// Equal in lowest terms: exact, with no product to overflow.
148
2352712
    fn eq_body(&self) -> Function {
149
2352712
        let mut f = Function::new([(2, ValType::I64)]);
150
2352712
        let (ga, gb) = (2, 3);
151
2352712
        self.gcd_into(&mut f, (0, NUM), (0, DEN), ga);
152
2352712
        self.gcd_into(&mut f, (1, NUM), (1, DEN), gb);
153
2352712
        for field in [NUM, DEN] {
154
4705424
            self.reduced(&mut f, 0, field, ga);
155
4705424
            self.reduced(&mut f, 1, field, gb);
156
4705424
            f.instruction(&Instruction::I64Eq);
157
        }
158
2352712
        f.instruction(&Instruction::I32And);
159
2352712
        f.instruction(&Instruction::End);
160
2352712
        f
161
2352712
    }
162

            
163
    /// `a.num * (b.den / g) < b.num * (a.den / g)`, `g` the denominators' GCD.
164
2352712
    fn lt_body(&self) -> Function {
165
2352712
        let mut f = Function::new([(1, ValType::I64)]);
166
2352712
        let g = 2;
167
2352712
        self.gcd_into(&mut f, (0, DEN), (1, DEN), g);
168
2352712
        self.field(&mut f, 0, NUM);
169
2352712
        self.reduced(&mut f, 1, DEN, g);
170
2352712
        f.instruction(&Instruction::Call(self.mul_checked));
171
2352712
        self.field(&mut f, 1, NUM);
172
2352712
        self.reduced(&mut f, 0, DEN, g);
173
2352712
        f.instruction(&Instruction::Call(self.mul_checked));
174
2352712
        f.instruction(&Instruction::I64LtS);
175
2352712
        f.instruction(&Instruction::End);
176
2352712
        f
177
2352712
    }
178
}
179

            
180
/// `a * b`, throwing when the product leaves i64: it overflowed exactly when
181
/// dividing it back by `a` does not give `b`, or for `i64::MIN * -1`, whose
182
/// division would itself trap.
183
2352712
fn checked_mul_body(overflow: &ConditionTrap) -> Function {
184
2352712
    let mut f = Function::new([(1, ValType::I64)]);
185
2352712
    for (minus_one, min) in [(0, 1), (1, 0)] {
186
4705424
        f.instruction(&Instruction::LocalGet(minus_one));
187
4705424
        f.instruction(&Instruction::I64Const(-1));
188
4705424
        f.instruction(&Instruction::I64Eq);
189
4705424
        f.instruction(&Instruction::LocalGet(min));
190
4705424
        f.instruction(&Instruction::I64Const(i64::MIN));
191
4705424
        f.instruction(&Instruction::I64Eq);
192
4705424
        f.instruction(&Instruction::I32And);
193
4705424
        throw_if(&mut f, overflow);
194
    }
195
2352712
    f.instruction(&Instruction::LocalGet(0));
196
2352712
    f.instruction(&Instruction::I64Eqz);
197
2352712
    f.instruction(&Instruction::If(BlockType::Result(ValType::I64)));
198
2352712
    f.instruction(&Instruction::I64Const(0));
199
2352712
    f.instruction(&Instruction::Else);
200
2352712
    f.instruction(&Instruction::LocalGet(0));
201
2352712
    f.instruction(&Instruction::LocalGet(1));
202
2352712
    f.instruction(&Instruction::I64Mul);
203
2352712
    f.instruction(&Instruction::LocalTee(2));
204
2352712
    f.instruction(&Instruction::LocalGet(0));
205
2352712
    f.instruction(&Instruction::I64DivS);
206
2352712
    f.instruction(&Instruction::LocalGet(1));
207
2352712
    f.instruction(&Instruction::I64Ne);
208
2352712
    throw_if(&mut f, overflow);
209
2352712
    f.instruction(&Instruction::LocalGet(2));
210
2352712
    f.instruction(&Instruction::End);
211
2352712
    f.instruction(&Instruction::End);
212
2352712
    f
213
2352712
}
214

            
215
/// `r = a + b` or `r = a - b`, throwing on signed overflow, which is when
216
/// `(a ^ r) & (x ^ y)` is negative: `(x, y)` is `(b, r)` for a sum (r's sign
217
/// differs from both operands') and `(a, b)` for a difference (the operands'
218
/// signs differ and r's differs from a's).
219
4705424
fn checked_sum_body(
220
4705424
    overflow: &ConditionTrap,
221
4705424
    op: &Instruction<'_>,
222
4705424
    (x, y): (u32, u32),
223
4705424
) -> Function {
224
4705424
    let mut f = Function::new([(1, ValType::I64)]);
225
4705424
    f.instruction(&Instruction::LocalGet(0));
226
4705424
    f.instruction(&Instruction::LocalGet(1));
227
4705424
    f.instruction(op);
228
4705424
    f.instruction(&Instruction::LocalSet(2));
229
4705424
    f.instruction(&Instruction::LocalGet(0));
230
4705424
    f.instruction(&Instruction::LocalGet(2));
231
4705424
    f.instruction(&Instruction::I64Xor);
232
4705424
    f.instruction(&Instruction::LocalGet(x));
233
4705424
    f.instruction(&Instruction::LocalGet(y));
234
4705424
    f.instruction(&Instruction::I64Xor);
235
4705424
    f.instruction(&Instruction::I64And);
236
4705424
    f.instruction(&Instruction::I64Const(0));
237
4705424
    f.instruction(&Instruction::I64LtS);
238
4705424
    throw_if(&mut f, overflow);
239
4705424
    f.instruction(&Instruction::LocalGet(2));
240
4705424
    f.instruction(&Instruction::End);
241
4705424
    f
242
4705424
}
243

            
244
11763560
fn throw_if(f: &mut Function, trap: &ConditionTrap) {
245
11763560
    f.instruction(&Instruction::If(BlockType::Empty));
246
11763560
    trap.emit_throw(f);
247
11763560
    f.instruction(&Instruction::End);
248
11763560
}