Skip to main content

miri/intrinsics/
aarch64.rs

1use rustc_middle::mir::BinOp;
2use rustc_span::Symbol;
3
4use crate::intrinsics::math::{compute_crc32, sha256};
5use crate::*;
6
7impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
8pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
9    fn emulate_aarch64_intrinsic(
10        &mut self,
11        link_name: Symbol,
12        args: &[OpTy<'tcx>],
13        dest: &MPlaceTy<'tcx>,
14    ) -> InterpResult<'tcx, EmulateItemResult> {
15        let this = self.eval_context_mut();
16        // Prefix should have already been checked.
17        let unprefixed_name = link_name.as_str().strip_prefix("llvm.aarch64.").unwrap();
18        match unprefixed_name {
19            // Used to implement the vpmaxq_u8 function.
20            // Computes the maximum of adjacent pairs; the first half of the output is produced from the
21            // `left` input, the second half of the output from the `right` input.
22            // https://developer.arm.com/architectures/instruction-sets/intrinsics/vpmaxq_u8
23            "neon.umaxp.v16i8" => {
24                let [left, right] = this.check_shim_sig_unadjusted(link_name, args)?;
25
26                let (left, left_len) = this.project_to_simd(left)?;
27                let (right, right_len) = this.project_to_simd(right)?;
28                let (dest, lane_count) = this.project_to_simd(dest)?;
29                assert_eq!(left_len, right_len);
30                assert_eq!(lane_count, left_len);
31
32                for lane_idx in 0..lane_count {
33                    let src = if lane_idx < (lane_count / 2) { &left } else { &right };
34                    let src_idx = lane_idx.strict_rem(lane_count / 2);
35
36                    let lhs_lane =
37                        this.read_immediate(&this.project_index(src, src_idx.strict_mul(2))?)?;
38                    let rhs_lane = this.read_immediate(
39                        &this.project_index(src, src_idx.strict_mul(2).strict_add(1))?,
40                    )?;
41
42                    // Compute `if lhs > rhs { lhs } else { rhs }`, i.e., `max`.
43                    let res_lane = if this
44                        .binary_op(BinOp::Gt, &lhs_lane, &rhs_lane)?
45                        .to_scalar()
46                        .to_bool()?
47                    {
48                        lhs_lane
49                    } else {
50                        rhs_lane
51                    };
52
53                    let dest = this.project_index(&dest, lane_idx)?;
54                    this.write_immediate(*res_lane, &dest)?;
55                }
56            }
57
58            // Wrapping pairwise addition.
59            //
60            // Concatenates the two input vectors and adds adjacent elements. For input vectors `v`
61            // and `w` this computes `[v0 + v1, v2 + v3, ..., w0 + w1, w2 + w3, ...]`, using
62            // wrapping addition for `+`.
63            //
64            // Used by `vpadd_{s8, u8, s16, u16, s32, u32}`.
65            name if name.starts_with("neon.addp.") => {
66                let [left, right] = this.check_shim_sig_unadjusted(link_name, args)?;
67
68                let (left, left_len) = this.project_to_simd(left)?;
69                let (right, right_len) = this.project_to_simd(right)?;
70                let (dest, dest_len) = this.project_to_simd(dest)?;
71
72                assert_eq!(left_len, right_len);
73                assert_eq!(left_len, dest_len);
74
75                assert_eq!(left.layout, right.layout);
76                assert_eq!(left.layout, dest.layout);
77
78                assert!(dest_len.is_multiple_of(2));
79                let half_len = dest_len.strict_div(2);
80
81                for lane_idx in 0..dest_len {
82                    // The left and right vectors are concatenated.
83                    let (src, src_pair_idx) = if lane_idx < half_len {
84                        (&left, lane_idx)
85                    } else {
86                        (&right, lane_idx.strict_sub(half_len))
87                    };
88                    // Convert "pair index" into "index of first element of the pair".
89                    let i = src_pair_idx.strict_mul(2);
90
91                    let lhs = this.read_immediate(&this.project_index(src, i)?)?;
92                    let rhs = this.read_immediate(&this.project_index(src, i.strict_add(1))?)?;
93
94                    // Wrapping addition on the element type.
95                    let sum = this.binary_op(BinOp::Add, &lhs, &rhs)?;
96
97                    let dst_lane = this.project_index(&dest, lane_idx)?;
98                    this.write_immediate(*sum, &dst_lane)?;
99                }
100            }
101
102            // Widening pairwise addition.
103            //
104            // Takes a single input vector, and an output vector with half as many lanes and double
105            // the element width. Takes adjacent pairs of elements, widens both, and then adds them
106            // together.
107            //
108            // Used by `vpaddl_{u8, u16, u32}` and `vpaddlq_{u8, u16, u32}`.
109            name if name.starts_with("neon.uaddlp.") => {
110                let [src] = this.check_shim_sig_unadjusted(link_name, args)?;
111
112                let (src, src_len) = this.project_to_simd(src)?;
113                let (dest, dest_len) = this.project_to_simd(dest)?;
114
115                // Operates pairwise, so src has twice as many lanes.
116                assert_eq!(src_len, dest_len.strict_mul(2));
117
118                let src_elem_size = src.layout.field(this, 0).size;
119                let dest_elem_size = dest.layout.field(this, 0).size;
120
121                // Widens, so dest elements must be exactly twice as wide.
122                assert_eq!(dest_elem_size.bytes(), src_elem_size.bytes().strict_mul(2));
123
124                for dest_idx in 0..dest_len {
125                    let src_idx = dest_idx.strict_mul(2);
126
127                    let a_scalar = this.read_scalar(&this.project_index(&src, src_idx)?)?;
128                    let b_scalar =
129                        this.read_scalar(&this.project_index(&src, src_idx.strict_add(1))?)?;
130
131                    let a_val = a_scalar.to_uint(src_elem_size)?;
132                    let b_val = b_scalar.to_uint(src_elem_size)?;
133
134                    // Use addition on u128 to simulate widening addition for the destination type.
135                    // This cannot wrap since the element type is at most u64.
136                    let sum = a_val.strict_add(b_val);
137
138                    let dst_lane = this.project_index(&dest, dest_idx)?;
139                    this.write_scalar(Scalar::from_uint(sum, dest_elem_size), &dst_lane)?;
140                }
141            }
142
143            // Signed saturating doubling multiply returning the high half.
144            //
145            // Used by the `vqdmulh*` functions.
146            //
147            // This LLVM intrinsic multiplies the values of corresponding elements of the two source
148            // vector registers (which are signed integers), doubles the results, places the most significant half of the
149            // final results (using a saturating cast to fit the element type) into a vector, and writes the vector to the destination register.
150            //
151            // https://developer.arm.com/architectures/instruction-sets/intrinsics#f:@navigationhierarchiessimdisa=[Neon]&q=vqdmulh
152            name if name.starts_with("neon.sqdmulh.") => {
153                let [left, right] = this.check_shim_sig_unadjusted(link_name, args)?;
154
155                let (left, left_len) = this.project_to_simd(left)?;
156                let (right, right_len) = this.project_to_simd(right)?;
157                let (dest, dest_len) = this.project_to_simd(dest)?;
158                assert_eq!(left_len, right_len);
159                assert_eq!(left_len, dest_len);
160
161                let elem_size = dest.layout.field(this, 0).size;
162                let bits = elem_size.bits();
163                let min = elem_size.signed_int_min();
164                let max = elem_size.signed_int_max();
165
166                for i in 0..dest_len {
167                    let a = this.read_scalar(&this.project_index(&left, i)?)?.to_int(elem_size)?;
168                    let b = this.read_scalar(&this.project_index(&right, i)?)?.to_int(elem_size)?;
169
170                    // Uses i128 arithmetic, which cannot overflow because the intrinsic takes at most i32.
171                    let doubled = a.strict_mul(b).strict_mul(2);
172                    let res = (doubled >> bits).clamp(min, max);
173
174                    this.write_scalar(
175                        Scalar::from_int(res, elem_size),
176                        &this.project_index(&dest, i)?,
177                    )?;
178                }
179            }
180
181            // Vector table lookup: each index selects a byte from the table,
182            // out-of-range -> 0.
183            //
184            // Used to implement the vtblN, vqtblN and vqtblNq set of functions, e.g.:
185            //
186            // - https://developer.arm.com/architectures/instruction-sets/intrinsics/vtbl1_u8
187            // - https://developer.arm.com/architectures/instruction-sets/intrinsics/vqtbl1_u8
188            // - https://developer.arm.com/architectures/instruction-sets/intrinsics/vqtbl1q_s8
189            // - https://developer.arm.com/architectures/instruction-sets/intrinsics/vtbl2_u8
190            // - https://developer.arm.com/architectures/instruction-sets/intrinsics/vqtbl4q_s8
191            //
192            // LLVM does not have a portable shuffle that takes non-const indices
193            // so we need to implement this ourselves.
194            _ if unprefixed_name.starts_with("neon.tbl") => {
195                // The table segments always have 16 elements, the index vector and output vector
196                // have either 8 or 16 elements.
197                let (table_segments, indices) = match unprefixed_name {
198                    "neon.tbl1.v8i8" | "neon.tbl1.v16i8" => {
199                        let [table, indices] = this.check_shim_sig_unadjusted(link_name, args)?;
200                        let (table, len) = this.project_to_simd(table)?;
201                        assert_eq!(len, 16);
202                        (vec![table], indices)
203                    }
204                    "neon.tbl2.v8i8" | "neon.tbl2.v16i8" => {
205                        let [table0, table1, indices] =
206                            this.check_shim_sig_unadjusted(link_name, args)?;
207                        let (table0, len0) = this.project_to_simd(table0)?;
208                        let (table1, len1) = this.project_to_simd(table1)?;
209                        assert_eq!([len0, len1], [16; 2]);
210                        (vec![table0, table1], indices)
211                    }
212                    "neon.tbl3.v8i8" | "neon.tbl3.v16i8" => {
213                        let [table0, table1, table2, indices] =
214                            this.check_shim_sig_unadjusted(link_name, args)?;
215                        let (table0, len0) = this.project_to_simd(table0)?;
216                        let (table1, len1) = this.project_to_simd(table1)?;
217                        let (table2, len2) = this.project_to_simd(table2)?;
218                        assert_eq!([len0, len1, len2], [16; 3]);
219                        (vec![table0, table1, table2], indices)
220                    }
221                    "neon.tbl4.v8i8" | "neon.tbl4.v16i8" => {
222                        let [table0, table1, table2, table3, indices] =
223                            this.check_shim_sig_unadjusted(link_name, args)?;
224                        let (table0, len0) = this.project_to_simd(table0)?;
225                        let (table1, len1) = this.project_to_simd(table1)?;
226                        let (table2, len2) = this.project_to_simd(table2)?;
227                        let (table3, len3) = this.project_to_simd(table3)?;
228                        assert_eq!([len0, len1, len2, len3], [16; 4]);
229                        (vec![table0, table1, table2, table3], indices)
230                    }
231                    _ => unreachable!(),
232                };
233
234                let (indices, idx_len) = this.project_to_simd(indices)?;
235                let (dest, dest_len) = this.project_to_simd(dest)?;
236                assert_eq!(idx_len, dest_len);
237
238                for i in 0..dest_len {
239                    let idx = this.read_immediate(&this.project_index(&indices, i)?)?;
240                    let idx = idx.to_scalar().to_u8()?;
241
242                    // The LLVM intrinsic table segments always have 16 elements.
243                    let val = if usize::from(idx) < table_segments.len().strict_mul(16) {
244                        let table = &table_segments[usize::from(idx.strict_div(16))];
245                        let lane = u64::from(idx.strict_rem(16));
246                        let t = this.read_immediate(&this.project_index(table, lane)?)?;
247                        t.to_scalar()
248                    } else {
249                        Scalar::from_u8(0)
250                    };
251
252                    this.write_scalar(val, &this.project_index(&dest, i)?)?;
253                }
254            }
255            // Used to implement the __crc32{b,h,w,x} and __crc32c{b,h,w,x} functions.
256            // Polynomial 0x04C11DB7 (standard CRC-32):
257            // https://developer.arm.com/documentation/ddi0602/latest/Base-Instructions/CRC32B--CRC32H--CRC32W--CRC32X--CRC32-checksum-
258            // Polynomial 0x1EDC6F41 (CRC-32C / Castagnoli):
259            // https://developer.arm.com/documentation/ddi0602/latest/Base-Instructions/CRC32CB--CRC32CH--CRC32CW--CRC32CX--CRC32C-checksum-
260            "crc32b" | "crc32h" | "crc32w" | "crc32x" | "crc32cb" | "crc32ch" | "crc32cw"
261            | "crc32cx" => {
262                this.expect_target_feature_for_intrinsic(link_name, "crc")?;
263                // The polynomial constants below include the leading 1 bit
264                // (e.g. 0x104C11DB7 instead of 0x04C11DB7) which the ARM docs
265                // omit but the polynomial division algorithm requires.
266                let (bit_size, polynomial): (u32, u128) = match unprefixed_name {
267                    "crc32b" => (8, 0x104C11DB7),
268                    "crc32h" => (16, 0x104C11DB7),
269                    "crc32w" => (32, 0x104C11DB7),
270                    "crc32x" => (64, 0x104C11DB7),
271                    "crc32cb" => (8, 0x11EDC6F41),
272                    "crc32ch" => (16, 0x11EDC6F41),
273                    "crc32cw" => (32, 0x11EDC6F41),
274                    "crc32cx" => (64, 0x11EDC6F41),
275                    _ => unreachable!(),
276                };
277
278                let [crc, data] = this.check_shim_sig_unadjusted(link_name, args)?;
279                let crc = this.read_scalar(crc)?;
280                let data = this.read_scalar(data)?;
281
282                // The CRC accumulator is always u32. The data argument is u32 for
283                // b/h/w variants and u64 for the x variant, per the LLVM intrinsic
284                // definitions (all b/h/w take i32, only x takes i64).
285                // https://github.com/llvm/llvm-project/blob/main/llvm/include/llvm/IR/IntrinsicsAArch64.td
286                // If the higher bits are non-zero, `compute_crc32` will panic. We should probably
287                // raise a proper error instead, but outside stdarch nobody can trigger this anyway.
288                let crc = crc.to_u32()?;
289                let data = if bit_size == 64 { data.to_u64()? } else { u64::from(data.to_u32()?) };
290
291                let result = compute_crc32(crc, data, bit_size, polynomial);
292                this.write_scalar(Scalar::from_u32(result), dest)?;
293            }
294            // Polynomial multiply long (64-bit x 64-bit -> 128-bit).
295            //
296            // This is the same as "carryless" multiplication, see
297            // <https://en.wikipedia.org/wiki/Carry-less_product#Multiplication_of_polynomials>.
298            //
299            // Used to implement the vmull_p64 and vmull_high_p64 functions.
300            // https://developer.arm.com/architectures/instruction-sets/intrinsics/vmull_p64
301            "neon.pmull64" => {
302                // LLVM and GCC group pmull with the AES intrinsics.
303                // Also see <https://gcc.gnu.org/pipermail/gcc-patches/2023-February/612088.html>.
304                this.expect_target_feature_for_intrinsic(link_name, "aes")?;
305
306                let [left, right] = this.check_shim_sig_unadjusted(link_name, args)?;
307                let left = this.read_scalar(left)?.to_u64()?;
308                let right = this.read_scalar(right)?.to_u64()?;
309
310                let result = left.widening_carryless_mul(right);
311
312                // dest is int8x16_t, transmute to u128 for the write.
313                let dest = dest.transmute(this.machine.layouts.u128, this)?;
314                this.write_scalar(Scalar::from_u128(result), &dest)?;
315            }
316
317            // Used to implement the vsha256hq_u32 function.
318            // https://developer.arm.com/architectures/instruction-sets/intrinsics/vsha256hq_u32
319            "crypto.sha256h" => {
320                this.expect_target_feature_for_intrinsic(link_name, "sha2")?;
321
322                let [abcd, efgh, wk] = this.check_shim_sig_unadjusted(link_name, args)?;
323
324                let (abcd, abcd_len) = this.project_to_simd(abcd)?;
325                let (efgh, efgh_len) = this.project_to_simd(efgh)?;
326                let (wk, wk_len) = this.project_to_simd(wk)?;
327                let (dest, dest_len) = this.project_to_simd(dest)?;
328
329                assert_eq!(abcd_len, 4);
330                assert_eq!(efgh_len, 4);
331                assert_eq!(wk_len, 4);
332                assert_eq!(dest_len, 4);
333
334                let abcd: [u32; 4] = read_u32x4(this, &abcd)?;
335                let efgh: [u32; 4] = read_u32x4(this, &efgh)?;
336                let wk: [u32; 4] = read_u32x4(this, &wk)?;
337
338                let result = sha256h(abcd, efgh, wk);
339
340                write_u32x4(this, &dest, result)?;
341            }
342            // Used to implement the vsha256h2q_u32 function.
343            // https://developer.arm.com/architectures/instruction-sets/intrinsics/vsha256h2q_u32
344            "crypto.sha256h2" => {
345                this.expect_target_feature_for_intrinsic(link_name, "sha2")?;
346
347                let [efgh, abcd, wk] = this.check_shim_sig_unadjusted(link_name, args)?;
348
349                let (efgh, efgh_len) = this.project_to_simd(efgh)?;
350                let (abcd, abcd_len) = this.project_to_simd(abcd)?;
351                let (wk, wk_len) = this.project_to_simd(wk)?;
352                let (dest, dest_len) = this.project_to_simd(dest)?;
353
354                assert_eq!(efgh_len, 4);
355                assert_eq!(abcd_len, 4);
356                assert_eq!(wk_len, 4);
357                assert_eq!(dest_len, 4);
358
359                let efgh: [u32; 4] = read_u32x4(this, &efgh)?;
360                let abcd: [u32; 4] = read_u32x4(this, &abcd)?;
361                let wk: [u32; 4] = read_u32x4(this, &wk)?;
362
363                let result = sha256h2(efgh, abcd, wk);
364
365                write_u32x4(this, &dest, result)?;
366            }
367            // Used to implement the vsha256su0q_u32 function.
368            // https://developer.arm.com/architectures/instruction-sets/intrinsics/vsha256su0q_u32
369            "crypto.sha256su0" => {
370                this.expect_target_feature_for_intrinsic(link_name, "sha2")?;
371
372                let [a, b] = this.check_shim_sig_unadjusted(link_name, args)?;
373
374                let (a, a_len) = this.project_to_simd(a)?;
375                let (b, b_len) = this.project_to_simd(b)?;
376                let (dest, dest_len) = this.project_to_simd(dest)?;
377
378                assert_eq!(a_len, 4);
379                assert_eq!(b_len, 4);
380                assert_eq!(dest_len, 4);
381
382                let a: [u32; 4] = read_u32x4(this, &a)?;
383                let b: [u32; 4] = read_u32x4(this, &b)?;
384
385                let result = sha256su0(a, b);
386
387                write_u32x4(this, &dest, result)?;
388            }
389            // Used to implement the vsha256su1q_u32 function.
390            // https://developer.arm.com/architectures/instruction-sets/intrinsics/vsha256su1q_u32
391            "crypto.sha256su1" => {
392                this.expect_target_feature_for_intrinsic(link_name, "sha2")?;
393
394                let [a, b, c] = this.check_shim_sig_unadjusted(link_name, args)?;
395
396                let (a, a_len) = this.project_to_simd(a)?;
397                let (b, b_len) = this.project_to_simd(b)?;
398                let (c, c_len) = this.project_to_simd(c)?;
399                let (dest, dest_len) = this.project_to_simd(dest)?;
400
401                assert_eq!(a_len, 4);
402                assert_eq!(b_len, 4);
403                assert_eq!(c_len, 4);
404                assert_eq!(dest_len, 4);
405
406                let a: [u32; 4] = read_u32x4(this, &a)?;
407                let b: [u32; 4] = read_u32x4(this, &b)?;
408                let c: [u32; 4] = read_u32x4(this, &c)?;
409
410                let result = sha256su1(a, b, c);
411
412                write_u32x4(this, &dest, result)?;
413            }
414            _ => return interp_ok(EmulateItemResult::NotSupported),
415        }
416        interp_ok(EmulateItemResult::NeedsReturn)
417    }
418}
419
420/// Reads a `[u32; 4]` array.
421fn read_u32x4<'c>(ecx: &mut MiriInterpCx<'c>, vec: &OpTy<'c>) -> InterpResult<'c, [u32; 4]> {
422    let mut res = [0; 4];
423    for (i, dst) in res.iter_mut().enumerate() {
424        let projected = &ecx.project_index(vec, i.try_into().unwrap())?;
425        *dst = ecx.read_scalar(projected)?.to_u32()?;
426    }
427    interp_ok(res)
428}
429
430fn write_u32x4<'c>(
431    ecx: &mut MiriInterpCx<'c>,
432    dest: &MPlaceTy<'c>,
433    val: [u32; 4],
434) -> InterpResult<'c, ()> {
435    for (i, part) in val.into_iter().enumerate() {
436        let projected = &ecx.project_index(dest, i.to_u64())?;
437        ecx.write_scalar(Scalar::from_u32(part), projected)?;
438    }
439    interp_ok(())
440}
441
442fn sha256su0(v0: [u32; 4], v1: [u32; 4]) -> [u32; 4] {
443    [
444        v0[0].wrapping_add(sha256::sigma0(v0[1])),
445        v0[1].wrapping_add(sha256::sigma0(v0[2])),
446        v0[2].wrapping_add(sha256::sigma0(v0[3])),
447        v0[3].wrapping_add(sha256::sigma0(v1[0])),
448    ]
449}
450
451fn sha256su1(v0: [u32; 4], v1: [u32; 4], v2: [u32; 4]) -> [u32; 4] {
452    let r0 = v0[0].wrapping_add(v1[1]).wrapping_add(sha256::sigma1(v2[2]));
453    let r1 = v0[1].wrapping_add(v1[2]).wrapping_add(sha256::sigma1(v2[3]));
454    let r2 = v0[2].wrapping_add(v1[3]).wrapping_add(sha256::sigma1(r0));
455    let r3 = v0[3].wrapping_add(v2[0]).wrapping_add(sha256::sigma1(r1));
456    [r0, r1, r2, r3]
457}
458
459// SHA256H/SHA256H2 do four compression rounds on the abcd/efgh layout.
460// https://developer.arm.com/architectures/instruction-sets/intrinsics/#f:@navigationhierarchiesinstructiongroup=[Cryptography,SHA256]
461fn sha256hash(abcd: [u32; 4], efgh: [u32; 4], wk: [u32; 4]) -> ([u32; 4], [u32; 4]) {
462    let mut state = [abcd[0], abcd[1], abcd[2], abcd[3], efgh[0], efgh[1], efgh[2], efgh[3]];
463    for &wk_i in &wk {
464        state = sha256::round(state, wk_i);
465    }
466    ([state[0], state[1], state[2], state[3]], [state[4], state[5], state[6], state[7]])
467}
468
469fn sha256h(abcd: [u32; 4], efgh: [u32; 4], wk: [u32; 4]) -> [u32; 4] {
470    sha256hash(abcd, efgh, wk).0
471}
472
473// sha256h2 takes efgh as the first argument. abcd and efgh are swapped when calling sha256hash.
474fn sha256h2(efgh: [u32; 4], abcd: [u32; 4], wk: [u32; 4]) -> [u32; 4] {
475    sha256hash(abcd, efgh, wk).1
476}