rustc_codegen_llvm/
intrinsic.rs

1use std::assert_matches::assert_matches;
2use std::cmp::Ordering;
3
4use rustc_abi::{Align, BackendRepr, ExternAbi, Float, HasDataLayout, Primitive, Size};
5use rustc_codegen_ssa::base::{compare_simd_types, wants_msvc_seh, wants_wasm_eh};
6use rustc_codegen_ssa::codegen_attrs::autodiff_attrs;
7use rustc_codegen_ssa::common::{IntPredicate, TypeKind};
8use rustc_codegen_ssa::errors::{ExpectedPointerMutability, InvalidMonomorphization};
9use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
10use rustc_codegen_ssa::mir::place::{PlaceRef, PlaceValue};
11use rustc_codegen_ssa::traits::*;
12use rustc_hir::def_id::LOCAL_CRATE;
13use rustc_hir::{self as hir};
14use rustc_middle::mir::BinOp;
15use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt, HasTypingEnv, LayoutOf};
16use rustc_middle::ty::{self, GenericArgsRef, Instance, Ty, TyCtxt, TypingEnv};
17use rustc_middle::{bug, span_bug};
18use rustc_span::{Span, Symbol, sym};
19use rustc_symbol_mangling::{mangle_internal_symbol, symbol_name_for_instance_in_crate};
20use rustc_target::callconv::PassMode;
21use rustc_target::spec::PanicStrategy;
22use tracing::debug;
23
24use crate::abi::FnAbiLlvmExt;
25use crate::builder::Builder;
26use crate::builder::autodiff::{adjust_activity_to_abi, generate_enzyme_call};
27use crate::context::CodegenCx;
28use crate::errors::AutoDiffWithoutEnable;
29use crate::llvm::{self, Metadata};
30use crate::type_::Type;
31use crate::type_of::LayoutLlvmExt;
32use crate::va_arg::emit_va_arg;
33use crate::value::Value;
34
35fn call_simple_intrinsic<'ll, 'tcx>(
36    bx: &mut Builder<'_, 'll, 'tcx>,
37    name: Symbol,
38    args: &[OperandRef<'tcx, &'ll Value>],
39) -> Option<&'ll Value> {
40    let (base_name, type_params): (&'static str, &[&'ll Type]) = match name {
41        sym::sqrtf16 => ("llvm.sqrt", &[bx.type_f16()]),
42        sym::sqrtf32 => ("llvm.sqrt", &[bx.type_f32()]),
43        sym::sqrtf64 => ("llvm.sqrt", &[bx.type_f64()]),
44        sym::sqrtf128 => ("llvm.sqrt", &[bx.type_f128()]),
45
46        sym::powif16 => ("llvm.powi", &[bx.type_f16(), bx.type_i32()]),
47        sym::powif32 => ("llvm.powi", &[bx.type_f32(), bx.type_i32()]),
48        sym::powif64 => ("llvm.powi", &[bx.type_f64(), bx.type_i32()]),
49        sym::powif128 => ("llvm.powi", &[bx.type_f128(), bx.type_i32()]),
50
51        sym::sinf16 => ("llvm.sin", &[bx.type_f16()]),
52        sym::sinf32 => ("llvm.sin", &[bx.type_f32()]),
53        sym::sinf64 => ("llvm.sin", &[bx.type_f64()]),
54        sym::sinf128 => ("llvm.sin", &[bx.type_f128()]),
55
56        sym::cosf16 => ("llvm.cos", &[bx.type_f16()]),
57        sym::cosf32 => ("llvm.cos", &[bx.type_f32()]),
58        sym::cosf64 => ("llvm.cos", &[bx.type_f64()]),
59        sym::cosf128 => ("llvm.cos", &[bx.type_f128()]),
60
61        sym::powf16 => ("llvm.pow", &[bx.type_f16()]),
62        sym::powf32 => ("llvm.pow", &[bx.type_f32()]),
63        sym::powf64 => ("llvm.pow", &[bx.type_f64()]),
64        sym::powf128 => ("llvm.pow", &[bx.type_f128()]),
65
66        sym::expf16 => ("llvm.exp", &[bx.type_f16()]),
67        sym::expf32 => ("llvm.exp", &[bx.type_f32()]),
68        sym::expf64 => ("llvm.exp", &[bx.type_f64()]),
69        sym::expf128 => ("llvm.exp", &[bx.type_f128()]),
70
71        sym::exp2f16 => ("llvm.exp2", &[bx.type_f16()]),
72        sym::exp2f32 => ("llvm.exp2", &[bx.type_f32()]),
73        sym::exp2f64 => ("llvm.exp2", &[bx.type_f64()]),
74        sym::exp2f128 => ("llvm.exp2", &[bx.type_f128()]),
75
76        sym::logf16 => ("llvm.log", &[bx.type_f16()]),
77        sym::logf32 => ("llvm.log", &[bx.type_f32()]),
78        sym::logf64 => ("llvm.log", &[bx.type_f64()]),
79        sym::logf128 => ("llvm.log", &[bx.type_f128()]),
80
81        sym::log10f16 => ("llvm.log10", &[bx.type_f16()]),
82        sym::log10f32 => ("llvm.log10", &[bx.type_f32()]),
83        sym::log10f64 => ("llvm.log10", &[bx.type_f64()]),
84        sym::log10f128 => ("llvm.log10", &[bx.type_f128()]),
85
86        sym::log2f16 => ("llvm.log2", &[bx.type_f16()]),
87        sym::log2f32 => ("llvm.log2", &[bx.type_f32()]),
88        sym::log2f64 => ("llvm.log2", &[bx.type_f64()]),
89        sym::log2f128 => ("llvm.log2", &[bx.type_f128()]),
90
91        sym::fmaf16 => ("llvm.fma", &[bx.type_f16()]),
92        sym::fmaf32 => ("llvm.fma", &[bx.type_f32()]),
93        sym::fmaf64 => ("llvm.fma", &[bx.type_f64()]),
94        sym::fmaf128 => ("llvm.fma", &[bx.type_f128()]),
95
96        sym::fmuladdf16 => ("llvm.fmuladd", &[bx.type_f16()]),
97        sym::fmuladdf32 => ("llvm.fmuladd", &[bx.type_f32()]),
98        sym::fmuladdf64 => ("llvm.fmuladd", &[bx.type_f64()]),
99        sym::fmuladdf128 => ("llvm.fmuladd", &[bx.type_f128()]),
100
101        sym::fabsf16 => ("llvm.fabs", &[bx.type_f16()]),
102        sym::fabsf32 => ("llvm.fabs", &[bx.type_f32()]),
103        sym::fabsf64 => ("llvm.fabs", &[bx.type_f64()]),
104        sym::fabsf128 => ("llvm.fabs", &[bx.type_f128()]),
105
106        sym::minnumf16 => ("llvm.minnum", &[bx.type_f16()]),
107        sym::minnumf32 => ("llvm.minnum", &[bx.type_f32()]),
108        sym::minnumf64 => ("llvm.minnum", &[bx.type_f64()]),
109        sym::minnumf128 => ("llvm.minnum", &[bx.type_f128()]),
110
111        // FIXME: LLVM currently mis-compile those intrinsics, re-enable them
112        // when llvm/llvm-project#{139380,139381,140445} are fixed.
113        //sym::minimumf16 => ("llvm.minimum", &[bx.type_f16()]),
114        //sym::minimumf32 => ("llvm.minimum", &[bx.type_f32()]),
115        //sym::minimumf64 => ("llvm.minimum", &[bx.type_f64()]),
116        //sym::minimumf128 => ("llvm.minimum", &[cx.type_f128()]),
117        //
118        sym::maxnumf16 => ("llvm.maxnum", &[bx.type_f16()]),
119        sym::maxnumf32 => ("llvm.maxnum", &[bx.type_f32()]),
120        sym::maxnumf64 => ("llvm.maxnum", &[bx.type_f64()]),
121        sym::maxnumf128 => ("llvm.maxnum", &[bx.type_f128()]),
122
123        // FIXME: LLVM currently mis-compile those intrinsics, re-enable them
124        // when llvm/llvm-project#{139380,139381,140445} are fixed.
125        //sym::maximumf16 => ("llvm.maximum", &[bx.type_f16()]),
126        //sym::maximumf32 => ("llvm.maximum", &[bx.type_f32()]),
127        //sym::maximumf64 => ("llvm.maximum", &[bx.type_f64()]),
128        //sym::maximumf128 => ("llvm.maximum", &[cx.type_f128()]),
129        //
130        sym::copysignf16 => ("llvm.copysign", &[bx.type_f16()]),
131        sym::copysignf32 => ("llvm.copysign", &[bx.type_f32()]),
132        sym::copysignf64 => ("llvm.copysign", &[bx.type_f64()]),
133        sym::copysignf128 => ("llvm.copysign", &[bx.type_f128()]),
134
135        sym::floorf16 => ("llvm.floor", &[bx.type_f16()]),
136        sym::floorf32 => ("llvm.floor", &[bx.type_f32()]),
137        sym::floorf64 => ("llvm.floor", &[bx.type_f64()]),
138        sym::floorf128 => ("llvm.floor", &[bx.type_f128()]),
139
140        sym::ceilf16 => ("llvm.ceil", &[bx.type_f16()]),
141        sym::ceilf32 => ("llvm.ceil", &[bx.type_f32()]),
142        sym::ceilf64 => ("llvm.ceil", &[bx.type_f64()]),
143        sym::ceilf128 => ("llvm.ceil", &[bx.type_f128()]),
144
145        sym::truncf16 => ("llvm.trunc", &[bx.type_f16()]),
146        sym::truncf32 => ("llvm.trunc", &[bx.type_f32()]),
147        sym::truncf64 => ("llvm.trunc", &[bx.type_f64()]),
148        sym::truncf128 => ("llvm.trunc", &[bx.type_f128()]),
149
150        // We could use any of `rint`, `nearbyint`, or `roundeven`
151        // for this -- they are all identical in semantics when
152        // assuming the default FP environment.
153        // `rint` is what we used for $forever.
154        sym::round_ties_even_f16 => ("llvm.rint", &[bx.type_f16()]),
155        sym::round_ties_even_f32 => ("llvm.rint", &[bx.type_f32()]),
156        sym::round_ties_even_f64 => ("llvm.rint", &[bx.type_f64()]),
157        sym::round_ties_even_f128 => ("llvm.rint", &[bx.type_f128()]),
158
159        sym::roundf16 => ("llvm.round", &[bx.type_f16()]),
160        sym::roundf32 => ("llvm.round", &[bx.type_f32()]),
161        sym::roundf64 => ("llvm.round", &[bx.type_f64()]),
162        sym::roundf128 => ("llvm.round", &[bx.type_f128()]),
163
164        _ => return None,
165    };
166    Some(bx.call_intrinsic(
167        base_name,
168        type_params,
169        &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
170    ))
171}
172
173impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
174    fn codegen_intrinsic_call(
175        &mut self,
176        instance: ty::Instance<'tcx>,
177        args: &[OperandRef<'tcx, &'ll Value>],
178        result: PlaceRef<'tcx, &'ll Value>,
179        span: Span,
180    ) -> Result<(), ty::Instance<'tcx>> {
181        let tcx = self.tcx;
182
183        let name = tcx.item_name(instance.def_id());
184        let fn_args = instance.args;
185
186        let simple = call_simple_intrinsic(self, name, args);
187        let llval = match name {
188            _ if simple.is_some() => simple.unwrap(),
189            sym::ptr_mask => {
190                let ptr = args[0].immediate();
191                self.call_intrinsic(
192                    "llvm.ptrmask",
193                    &[self.val_ty(ptr), self.type_isize()],
194                    &[ptr, args[1].immediate()],
195                )
196            }
197            sym::autodiff => {
198                codegen_autodiff(self, tcx, instance, args, result);
199                return Ok(());
200            }
201            sym::is_val_statically_known => {
202                if let OperandValue::Immediate(imm) = args[0].val {
203                    self.call_intrinsic(
204                        "llvm.is.constant",
205                        &[args[0].layout.immediate_llvm_type(self.cx)],
206                        &[imm],
207                    )
208                } else {
209                    self.const_bool(false)
210                }
211            }
212            sym::select_unpredictable => {
213                let cond = args[0].immediate();
214                assert_eq!(args[1].layout, args[2].layout);
215                let select = |bx: &mut Self, true_val, false_val| {
216                    let result = bx.select(cond, true_val, false_val);
217                    bx.set_unpredictable(&result);
218                    result
219                };
220                match (args[1].val, args[2].val) {
221                    (OperandValue::Ref(true_val), OperandValue::Ref(false_val)) => {
222                        assert!(true_val.llextra.is_none());
223                        assert!(false_val.llextra.is_none());
224                        assert_eq!(true_val.align, false_val.align);
225                        let ptr = select(self, true_val.llval, false_val.llval);
226                        let selected =
227                            OperandValue::Ref(PlaceValue::new_sized(ptr, true_val.align));
228                        selected.store(self, result);
229                        return Ok(());
230                    }
231                    (OperandValue::Immediate(_), OperandValue::Immediate(_))
232                    | (OperandValue::Pair(_, _), OperandValue::Pair(_, _)) => {
233                        let true_val = args[1].immediate_or_packed_pair(self);
234                        let false_val = args[2].immediate_or_packed_pair(self);
235                        select(self, true_val, false_val)
236                    }
237                    (OperandValue::ZeroSized, OperandValue::ZeroSized) => return Ok(()),
238                    _ => span_bug!(span, "Incompatible OperandValue for select_unpredictable"),
239                }
240            }
241            sym::catch_unwind => {
242                catch_unwind_intrinsic(
243                    self,
244                    args[0].immediate(),
245                    args[1].immediate(),
246                    args[2].immediate(),
247                    result,
248                );
249                return Ok(());
250            }
251            sym::breakpoint => self.call_intrinsic("llvm.debugtrap", &[], &[]),
252            sym::va_copy => {
253                let dest = args[0].immediate();
254                self.call_intrinsic(
255                    "llvm.va_copy",
256                    &[self.val_ty(dest)],
257                    &[dest, args[1].immediate()],
258                )
259            }
260            sym::va_arg => {
261                match result.layout.backend_repr {
262                    BackendRepr::Scalar(scalar) => {
263                        match scalar.primitive() {
264                            Primitive::Int(..) => {
265                                if self.cx().size_of(result.layout.ty).bytes() < 4 {
266                                    // `va_arg` should not be called on an integer type
267                                    // less than 4 bytes in length. If it is, promote
268                                    // the integer to an `i32` and truncate the result
269                                    // back to the smaller type.
270                                    let promoted_result = emit_va_arg(self, args[0], tcx.types.i32);
271                                    self.trunc(promoted_result, result.layout.llvm_type(self))
272                                } else {
273                                    emit_va_arg(self, args[0], result.layout.ty)
274                                }
275                            }
276                            Primitive::Float(Float::F16) => {
277                                bug!("the va_arg intrinsic does not work with `f16`")
278                            }
279                            Primitive::Float(Float::F64) | Primitive::Pointer(_) => {
280                                emit_va_arg(self, args[0], result.layout.ty)
281                            }
282                            // `va_arg` should never be used with the return type f32.
283                            Primitive::Float(Float::F32) => {
284                                bug!("the va_arg intrinsic does not work with `f32`")
285                            }
286                            Primitive::Float(Float::F128) => {
287                                bug!("the va_arg intrinsic does not work with `f128`")
288                            }
289                        }
290                    }
291                    _ => bug!("the va_arg intrinsic does not work with non-scalar types"),
292                }
293            }
294
295            sym::volatile_load | sym::unaligned_volatile_load => {
296                let ptr = args[0].immediate();
297                let load = self.volatile_load(result.layout.llvm_type(self), ptr);
298                let align = if name == sym::unaligned_volatile_load {
299                    1
300                } else {
301                    result.layout.align.abi.bytes() as u32
302                };
303                unsafe {
304                    llvm::LLVMSetAlignment(load, align);
305                }
306                if !result.layout.is_zst() {
307                    self.store_to_place(load, result.val);
308                }
309                return Ok(());
310            }
311            sym::volatile_store => {
312                let dst = args[0].deref(self.cx());
313                args[1].val.volatile_store(self, dst);
314                return Ok(());
315            }
316            sym::unaligned_volatile_store => {
317                let dst = args[0].deref(self.cx());
318                args[1].val.unaligned_volatile_store(self, dst);
319                return Ok(());
320            }
321            sym::prefetch_read_data
322            | sym::prefetch_write_data
323            | sym::prefetch_read_instruction
324            | sym::prefetch_write_instruction => {
325                let (rw, cache_type) = match name {
326                    sym::prefetch_read_data => (0, 1),
327                    sym::prefetch_write_data => (1, 1),
328                    sym::prefetch_read_instruction => (0, 0),
329                    sym::prefetch_write_instruction => (1, 0),
330                    _ => bug!(),
331                };
332                let ptr = args[0].immediate();
333                self.call_intrinsic(
334                    "llvm.prefetch",
335                    &[self.val_ty(ptr)],
336                    &[ptr, self.const_i32(rw), args[1].immediate(), self.const_i32(cache_type)],
337                )
338            }
339            sym::carrying_mul_add => {
340                let (size, signed) = fn_args.type_at(0).int_size_and_signed(self.tcx);
341
342                let wide_llty = self.type_ix(size.bits() * 2);
343                let args = args.as_array().unwrap();
344                let [a, b, c, d] = args.map(|a| self.intcast(a.immediate(), wide_llty, signed));
345
346                let wide = if signed {
347                    let prod = self.unchecked_smul(a, b);
348                    let acc = self.unchecked_sadd(prod, c);
349                    self.unchecked_sadd(acc, d)
350                } else {
351                    let prod = self.unchecked_umul(a, b);
352                    let acc = self.unchecked_uadd(prod, c);
353                    self.unchecked_uadd(acc, d)
354                };
355
356                let narrow_llty = self.type_ix(size.bits());
357                let low = self.trunc(wide, narrow_llty);
358                let bits_const = self.const_uint(wide_llty, size.bits());
359                // No need for ashr when signed; LLVM changes it to lshr anyway.
360                let high = self.lshr(wide, bits_const);
361                // FIXME: could be `trunc nuw`, even for signed.
362                let high = self.trunc(high, narrow_llty);
363
364                let pair_llty = self.type_struct(&[narrow_llty, narrow_llty], false);
365                let pair = self.const_poison(pair_llty);
366                let pair = self.insert_value(pair, low, 0);
367                let pair = self.insert_value(pair, high, 1);
368                pair
369            }
370            sym::ctlz
371            | sym::ctlz_nonzero
372            | sym::cttz
373            | sym::cttz_nonzero
374            | sym::ctpop
375            | sym::bswap
376            | sym::bitreverse
377            | sym::rotate_left
378            | sym::rotate_right
379            | sym::saturating_add
380            | sym::saturating_sub => {
381                let ty = args[0].layout.ty;
382                if !ty.is_integral() {
383                    tcx.dcx().emit_err(InvalidMonomorphization::BasicIntegerType {
384                        span,
385                        name,
386                        ty,
387                    });
388                    return Ok(());
389                }
390                let (size, signed) = ty.int_size_and_signed(self.tcx);
391                let width = size.bits();
392                let llty = self.type_ix(width);
393                match name {
394                    sym::ctlz | sym::ctlz_nonzero | sym::cttz | sym::cttz_nonzero => {
395                        let y =
396                            self.const_bool(name == sym::ctlz_nonzero || name == sym::cttz_nonzero);
397                        let llvm_name = if name == sym::ctlz || name == sym::ctlz_nonzero {
398                            "llvm.ctlz"
399                        } else {
400                            "llvm.cttz"
401                        };
402                        let ret =
403                            self.call_intrinsic(llvm_name, &[llty], &[args[0].immediate(), y]);
404                        self.intcast(ret, result.layout.llvm_type(self), false)
405                    }
406                    sym::ctpop => {
407                        let ret =
408                            self.call_intrinsic("llvm.ctpop", &[llty], &[args[0].immediate()]);
409                        self.intcast(ret, result.layout.llvm_type(self), false)
410                    }
411                    sym::bswap => {
412                        if width == 8 {
413                            args[0].immediate() // byte swap a u8/i8 is just a no-op
414                        } else {
415                            self.call_intrinsic("llvm.bswap", &[llty], &[args[0].immediate()])
416                        }
417                    }
418                    sym::bitreverse => {
419                        self.call_intrinsic("llvm.bitreverse", &[llty], &[args[0].immediate()])
420                    }
421                    sym::rotate_left | sym::rotate_right => {
422                        let is_left = name == sym::rotate_left;
423                        let val = args[0].immediate();
424                        let raw_shift = args[1].immediate();
425                        // rotate = funnel shift with first two args the same
426                        let llvm_name = format!("llvm.fsh{}", if is_left { 'l' } else { 'r' });
427
428                        // llvm expects shift to be the same type as the values, but rust
429                        // always uses `u32`.
430                        let raw_shift = self.intcast(raw_shift, self.val_ty(val), false);
431
432                        self.call_intrinsic(llvm_name, &[llty], &[val, val, raw_shift])
433                    }
434                    sym::saturating_add | sym::saturating_sub => {
435                        let is_add = name == sym::saturating_add;
436                        let lhs = args[0].immediate();
437                        let rhs = args[1].immediate();
438                        let llvm_name = format!(
439                            "llvm.{}{}.sat",
440                            if signed { 's' } else { 'u' },
441                            if is_add { "add" } else { "sub" },
442                        );
443                        self.call_intrinsic(llvm_name, &[llty], &[lhs, rhs])
444                    }
445                    _ => bug!(),
446                }
447            }
448
449            sym::raw_eq => {
450                use BackendRepr::*;
451                let tp_ty = fn_args.type_at(0);
452                let layout = self.layout_of(tp_ty).layout;
453                let use_integer_compare = match layout.backend_repr() {
454                    Scalar(_) | ScalarPair(_, _) => true,
455                    SimdVector { .. } => false,
456                    Memory { .. } => {
457                        // For rusty ABIs, small aggregates are actually passed
458                        // as `RegKind::Integer` (see `FnAbi::adjust_for_abi`),
459                        // so we re-use that same threshold here.
460                        layout.size() <= self.data_layout().pointer_size() * 2
461                    }
462                };
463
464                let a = args[0].immediate();
465                let b = args[1].immediate();
466                if layout.size().bytes() == 0 {
467                    self.const_bool(true)
468                } else if use_integer_compare {
469                    let integer_ty = self.type_ix(layout.size().bits());
470                    let a_val = self.load(integer_ty, a, layout.align().abi);
471                    let b_val = self.load(integer_ty, b, layout.align().abi);
472                    self.icmp(IntPredicate::IntEQ, a_val, b_val)
473                } else {
474                    let n = self.const_usize(layout.size().bytes());
475                    let cmp = self.call_intrinsic("memcmp", &[], &[a, b, n]);
476                    self.icmp(IntPredicate::IntEQ, cmp, self.const_int(self.type_int(), 0))
477                }
478            }
479
480            sym::compare_bytes => {
481                // Here we assume that the `memcmp` provided by the target is a NOP for size 0.
482                let cmp = self.call_intrinsic(
483                    "memcmp",
484                    &[],
485                    &[args[0].immediate(), args[1].immediate(), args[2].immediate()],
486                );
487                // Some targets have `memcmp` returning `i16`, but the intrinsic is always `i32`.
488                self.sext(cmp, self.type_ix(32))
489            }
490
491            sym::black_box => {
492                args[0].val.store(self, result);
493                let result_val_span = [result.val.llval];
494                // We need to "use" the argument in some way LLVM can't introspect, and on
495                // targets that support it we can typically leverage inline assembly to do
496                // this. LLVM's interpretation of inline assembly is that it's, well, a black
497                // box. This isn't the greatest implementation since it probably deoptimizes
498                // more than we want, but it's so far good enough.
499                //
500                // For zero-sized types, the location pointed to by the result may be
501                // uninitialized. Do not "use" the result in this case; instead just clobber
502                // the memory.
503                let (constraint, inputs): (&str, &[_]) = if result.layout.is_zst() {
504                    ("~{memory}", &[])
505                } else {
506                    ("r,~{memory}", &result_val_span)
507                };
508                crate::asm::inline_asm_call(
509                    self,
510                    "",
511                    constraint,
512                    inputs,
513                    self.type_void(),
514                    &[],
515                    true,
516                    false,
517                    llvm::AsmDialect::Att,
518                    &[span],
519                    false,
520                    None,
521                    None,
522                )
523                .unwrap_or_else(|| bug!("failed to generate inline asm call for `black_box`"));
524
525                // We have copied the value to `result` already.
526                return Ok(());
527            }
528
529            _ if name.as_str().starts_with("simd_") => {
530                // Unpack non-power-of-2 #[repr(packed, simd)] arguments.
531                // This gives them the expected layout of a regular #[repr(simd)] vector.
532                let mut loaded_args = Vec::new();
533                for arg in args {
534                    loaded_args.push(
535                        // #[repr(packed, simd)] vectors are passed like arrays (as references,
536                        // with reduced alignment and no padding) rather than as immediates.
537                        // We can use a vector load to fix the layout and turn the argument
538                        // into an immediate.
539                        if arg.layout.ty.is_simd()
540                            && let OperandValue::Ref(place) = arg.val
541                        {
542                            let (size, elem_ty) = arg.layout.ty.simd_size_and_type(self.tcx());
543                            let elem_ll_ty = match elem_ty.kind() {
544                                ty::Float(f) => self.type_float_from_ty(*f),
545                                ty::Int(i) => self.type_int_from_ty(*i),
546                                ty::Uint(u) => self.type_uint_from_ty(*u),
547                                ty::RawPtr(_, _) => self.type_ptr(),
548                                _ => unreachable!(),
549                            };
550                            let loaded =
551                                self.load_from_place(self.type_vector(elem_ll_ty, size), place);
552                            OperandRef::from_immediate_or_packed_pair(self, loaded, arg.layout)
553                        } else {
554                            *arg
555                        },
556                    );
557                }
558
559                let llret_ty = if result.layout.ty.is_simd()
560                    && let BackendRepr::Memory { .. } = result.layout.backend_repr
561                {
562                    let (size, elem_ty) = result.layout.ty.simd_size_and_type(self.tcx());
563                    let elem_ll_ty = match elem_ty.kind() {
564                        ty::Float(f) => self.type_float_from_ty(*f),
565                        ty::Int(i) => self.type_int_from_ty(*i),
566                        ty::Uint(u) => self.type_uint_from_ty(*u),
567                        ty::RawPtr(_, _) => self.type_ptr(),
568                        _ => unreachable!(),
569                    };
570                    self.type_vector(elem_ll_ty, size)
571                } else {
572                    result.layout.llvm_type(self)
573                };
574
575                match generic_simd_intrinsic(
576                    self,
577                    name,
578                    fn_args,
579                    &loaded_args,
580                    result.layout.ty,
581                    llret_ty,
582                    span,
583                ) {
584                    Ok(llval) => llval,
585                    // If there was an error, just skip this invocation... we'll abort compilation
586                    // anyway, but we can keep codegen'ing to find more errors.
587                    Err(()) => return Ok(()),
588                }
589            }
590
591            _ => {
592                debug!("unknown intrinsic '{}' -- falling back to default body", name);
593                // Call the fallback body instead of generating the intrinsic code
594                return Err(ty::Instance::new_raw(instance.def_id(), instance.args));
595            }
596        };
597
598        if result.layout.ty.is_bool() {
599            let val = self.from_immediate(llval);
600            self.store_to_place(val, result.val);
601        } else if !result.layout.ty.is_unit() {
602            self.store_to_place(llval, result.val);
603        }
604        Ok(())
605    }
606
607    fn abort(&mut self) {
608        self.call_intrinsic("llvm.trap", &[], &[]);
609    }
610
611    fn assume(&mut self, val: Self::Value) {
612        if self.cx.sess().opts.optimize != rustc_session::config::OptLevel::No {
613            self.call_intrinsic("llvm.assume", &[], &[val]);
614        }
615    }
616
617    fn expect(&mut self, cond: Self::Value, expected: bool) -> Self::Value {
618        if self.cx.sess().opts.optimize != rustc_session::config::OptLevel::No {
619            self.call_intrinsic(
620                "llvm.expect",
621                &[self.type_i1()],
622                &[cond, self.const_bool(expected)],
623            )
624        } else {
625            cond
626        }
627    }
628
629    fn type_checked_load(
630        &mut self,
631        llvtable: &'ll Value,
632        vtable_byte_offset: u64,
633        typeid: &'ll Metadata,
634    ) -> Self::Value {
635        let typeid = self.get_metadata_value(typeid);
636        let vtable_byte_offset = self.const_i32(vtable_byte_offset as i32);
637        let type_checked_load = self.call_intrinsic(
638            "llvm.type.checked.load",
639            &[],
640            &[llvtable, vtable_byte_offset, typeid],
641        );
642        self.extract_value(type_checked_load, 0)
643    }
644
645    fn va_start(&mut self, va_list: &'ll Value) -> &'ll Value {
646        self.call_intrinsic("llvm.va_start", &[self.val_ty(va_list)], &[va_list])
647    }
648
649    fn va_end(&mut self, va_list: &'ll Value) -> &'ll Value {
650        self.call_intrinsic("llvm.va_end", &[self.val_ty(va_list)], &[va_list])
651    }
652}
653
654fn catch_unwind_intrinsic<'ll, 'tcx>(
655    bx: &mut Builder<'_, 'll, 'tcx>,
656    try_func: &'ll Value,
657    data: &'ll Value,
658    catch_func: &'ll Value,
659    dest: PlaceRef<'tcx, &'ll Value>,
660) {
661    if bx.sess().panic_strategy() == PanicStrategy::Abort {
662        let try_func_ty = bx.type_func(&[bx.type_ptr()], bx.type_void());
663        bx.call(try_func_ty, None, None, try_func, &[data], None, None);
664        // Return 0 unconditionally from the intrinsic call;
665        // we can never unwind.
666        OperandValue::Immediate(bx.const_i32(0)).store(bx, dest);
667    } else if wants_msvc_seh(bx.sess()) {
668        codegen_msvc_try(bx, try_func, data, catch_func, dest);
669    } else if wants_wasm_eh(bx.sess()) {
670        codegen_wasm_try(bx, try_func, data, catch_func, dest);
671    } else if bx.sess().target.os == "emscripten" {
672        codegen_emcc_try(bx, try_func, data, catch_func, dest);
673    } else {
674        codegen_gnu_try(bx, try_func, data, catch_func, dest);
675    }
676}
677
678// MSVC's definition of the `rust_try` function.
679//
680// This implementation uses the new exception handling instructions in LLVM
681// which have support in LLVM for SEH on MSVC targets. Although these
682// instructions are meant to work for all targets, as of the time of this
683// writing, however, LLVM does not recommend the usage of these new instructions
684// as the old ones are still more optimized.
685fn codegen_msvc_try<'ll, 'tcx>(
686    bx: &mut Builder<'_, 'll, 'tcx>,
687    try_func: &'ll Value,
688    data: &'ll Value,
689    catch_func: &'ll Value,
690    dest: PlaceRef<'tcx, &'ll Value>,
691) {
692    let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
693        bx.set_personality_fn(bx.eh_personality());
694
695        let normal = bx.append_sibling_block("normal");
696        let catchswitch = bx.append_sibling_block("catchswitch");
697        let catchpad_rust = bx.append_sibling_block("catchpad_rust");
698        let catchpad_foreign = bx.append_sibling_block("catchpad_foreign");
699        let caught = bx.append_sibling_block("caught");
700
701        let try_func = llvm::get_param(bx.llfn(), 0);
702        let data = llvm::get_param(bx.llfn(), 1);
703        let catch_func = llvm::get_param(bx.llfn(), 2);
704
705        // We're generating an IR snippet that looks like:
706        //
707        //   declare i32 @rust_try(%try_func, %data, %catch_func) {
708        //      %slot = alloca i8*
709        //      invoke %try_func(%data) to label %normal unwind label %catchswitch
710        //
711        //   normal:
712        //      ret i32 0
713        //
714        //   catchswitch:
715        //      %cs = catchswitch within none [%catchpad_rust, %catchpad_foreign] unwind to caller
716        //
717        //   catchpad_rust:
718        //      %tok = catchpad within %cs [%type_descriptor, 8, %slot]
719        //      %ptr = load %slot
720        //      call %catch_func(%data, %ptr)
721        //      catchret from %tok to label %caught
722        //
723        //   catchpad_foreign:
724        //      %tok = catchpad within %cs [null, 64, null]
725        //      call %catch_func(%data, null)
726        //      catchret from %tok to label %caught
727        //
728        //   caught:
729        //      ret i32 1
730        //   }
731        //
732        // This structure follows the basic usage of throw/try/catch in LLVM.
733        // For example, compile this C++ snippet to see what LLVM generates:
734        //
735        //      struct rust_panic {
736        //          rust_panic(const rust_panic&);
737        //          ~rust_panic();
738        //
739        //          void* x[2];
740        //      };
741        //
742        //      int __rust_try(
743        //          void (*try_func)(void*),
744        //          void *data,
745        //          void (*catch_func)(void*, void*) noexcept
746        //      ) {
747        //          try {
748        //              try_func(data);
749        //              return 0;
750        //          } catch(rust_panic& a) {
751        //              catch_func(data, &a);
752        //              return 1;
753        //          } catch(...) {
754        //              catch_func(data, NULL);
755        //              return 1;
756        //          }
757        //      }
758        //
759        // More information can be found in libstd's seh.rs implementation.
760        let ptr_size = bx.tcx().data_layout.pointer_size();
761        let ptr_align = bx.tcx().data_layout.pointer_align().abi;
762        let slot = bx.alloca(ptr_size, ptr_align);
763        let try_func_ty = bx.type_func(&[bx.type_ptr()], bx.type_void());
764        bx.invoke(try_func_ty, None, None, try_func, &[data], normal, catchswitch, None, None);
765
766        bx.switch_to_block(normal);
767        bx.ret(bx.const_i32(0));
768
769        bx.switch_to_block(catchswitch);
770        let cs = bx.catch_switch(None, None, &[catchpad_rust, catchpad_foreign]);
771
772        // We can't use the TypeDescriptor defined in libpanic_unwind because it
773        // might be in another DLL and the SEH encoding only supports specifying
774        // a TypeDescriptor from the current module.
775        //
776        // However this isn't an issue since the MSVC runtime uses string
777        // comparison on the type name to match TypeDescriptors rather than
778        // pointer equality.
779        //
780        // So instead we generate a new TypeDescriptor in each module that uses
781        // `try` and let the linker merge duplicate definitions in the same
782        // module.
783        //
784        // When modifying, make sure that the type_name string exactly matches
785        // the one used in library/panic_unwind/src/seh.rs.
786        let type_info_vtable = bx.declare_global("??_7type_info@@6B@", bx.type_ptr());
787        let type_name = bx.const_bytes(b"rust_panic\0");
788        let type_info =
789            bx.const_struct(&[type_info_vtable, bx.const_null(bx.type_ptr()), type_name], false);
790        let tydesc = bx.declare_global(
791            &mangle_internal_symbol(bx.tcx, "__rust_panic_type_info"),
792            bx.val_ty(type_info),
793        );
794
795        llvm::set_linkage(tydesc, llvm::Linkage::LinkOnceODRLinkage);
796        if bx.cx.tcx.sess.target.supports_comdat() {
797            llvm::SetUniqueComdat(bx.llmod, tydesc);
798        }
799        llvm::set_initializer(tydesc, type_info);
800
801        // The flag value of 8 indicates that we are catching the exception by
802        // reference instead of by value. We can't use catch by value because
803        // that requires copying the exception object, which we don't support
804        // since our exception object effectively contains a Box.
805        //
806        // Source: MicrosoftCXXABI::getAddrOfCXXCatchHandlerType in clang
807        bx.switch_to_block(catchpad_rust);
808        let flags = bx.const_i32(8);
809        let funclet = bx.catch_pad(cs, &[tydesc, flags, slot]);
810        let ptr = bx.load(bx.type_ptr(), slot, ptr_align);
811        let catch_ty = bx.type_func(&[bx.type_ptr(), bx.type_ptr()], bx.type_void());
812        bx.call(catch_ty, None, None, catch_func, &[data, ptr], Some(&funclet), None);
813        bx.catch_ret(&funclet, caught);
814
815        // The flag value of 64 indicates a "catch-all".
816        bx.switch_to_block(catchpad_foreign);
817        let flags = bx.const_i32(64);
818        let null = bx.const_null(bx.type_ptr());
819        let funclet = bx.catch_pad(cs, &[null, flags, null]);
820        bx.call(catch_ty, None, None, catch_func, &[data, null], Some(&funclet), None);
821        bx.catch_ret(&funclet, caught);
822
823        bx.switch_to_block(caught);
824        bx.ret(bx.const_i32(1));
825    });
826
827    // Note that no invoke is used here because by definition this function
828    // can't panic (that's what it's catching).
829    let ret = bx.call(llty, None, None, llfn, &[try_func, data, catch_func], None, None);
830    OperandValue::Immediate(ret).store(bx, dest);
831}
832
833// WASM's definition of the `rust_try` function.
834fn codegen_wasm_try<'ll, 'tcx>(
835    bx: &mut Builder<'_, 'll, 'tcx>,
836    try_func: &'ll Value,
837    data: &'ll Value,
838    catch_func: &'ll Value,
839    dest: PlaceRef<'tcx, &'ll Value>,
840) {
841    let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
842        bx.set_personality_fn(bx.eh_personality());
843
844        let normal = bx.append_sibling_block("normal");
845        let catchswitch = bx.append_sibling_block("catchswitch");
846        let catchpad = bx.append_sibling_block("catchpad");
847        let caught = bx.append_sibling_block("caught");
848
849        let try_func = llvm::get_param(bx.llfn(), 0);
850        let data = llvm::get_param(bx.llfn(), 1);
851        let catch_func = llvm::get_param(bx.llfn(), 2);
852
853        // We're generating an IR snippet that looks like:
854        //
855        //   declare i32 @rust_try(%try_func, %data, %catch_func) {
856        //      %slot = alloca i8*
857        //      invoke %try_func(%data) to label %normal unwind label %catchswitch
858        //
859        //   normal:
860        //      ret i32 0
861        //
862        //   catchswitch:
863        //      %cs = catchswitch within none [%catchpad] unwind to caller
864        //
865        //   catchpad:
866        //      %tok = catchpad within %cs [null]
867        //      %ptr = call @llvm.wasm.get.exception(token %tok)
868        //      %sel = call @llvm.wasm.get.ehselector(token %tok)
869        //      call %catch_func(%data, %ptr)
870        //      catchret from %tok to label %caught
871        //
872        //   caught:
873        //      ret i32 1
874        //   }
875        //
876        let try_func_ty = bx.type_func(&[bx.type_ptr()], bx.type_void());
877        bx.invoke(try_func_ty, None, None, try_func, &[data], normal, catchswitch, None, None);
878
879        bx.switch_to_block(normal);
880        bx.ret(bx.const_i32(0));
881
882        bx.switch_to_block(catchswitch);
883        let cs = bx.catch_switch(None, None, &[catchpad]);
884
885        bx.switch_to_block(catchpad);
886        let null = bx.const_null(bx.type_ptr());
887        let funclet = bx.catch_pad(cs, &[null]);
888
889        let ptr = bx.call_intrinsic("llvm.wasm.get.exception", &[], &[funclet.cleanuppad()]);
890        let _sel = bx.call_intrinsic("llvm.wasm.get.ehselector", &[], &[funclet.cleanuppad()]);
891
892        let catch_ty = bx.type_func(&[bx.type_ptr(), bx.type_ptr()], bx.type_void());
893        bx.call(catch_ty, None, None, catch_func, &[data, ptr], Some(&funclet), None);
894        bx.catch_ret(&funclet, caught);
895
896        bx.switch_to_block(caught);
897        bx.ret(bx.const_i32(1));
898    });
899
900    // Note that no invoke is used here because by definition this function
901    // can't panic (that's what it's catching).
902    let ret = bx.call(llty, None, None, llfn, &[try_func, data, catch_func], None, None);
903    OperandValue::Immediate(ret).store(bx, dest);
904}
905
906// Definition of the standard `try` function for Rust using the GNU-like model
907// of exceptions (e.g., the normal semantics of LLVM's `landingpad` and `invoke`
908// instructions).
909//
910// This codegen is a little surprising because we always call a shim
911// function instead of inlining the call to `invoke` manually here. This is done
912// because in LLVM we're only allowed to have one personality per function
913// definition. The call to the `try` intrinsic is being inlined into the
914// function calling it, and that function may already have other personality
915// functions in play. By calling a shim we're guaranteed that our shim will have
916// the right personality function.
917fn codegen_gnu_try<'ll, 'tcx>(
918    bx: &mut Builder<'_, 'll, 'tcx>,
919    try_func: &'ll Value,
920    data: &'ll Value,
921    catch_func: &'ll Value,
922    dest: PlaceRef<'tcx, &'ll Value>,
923) {
924    let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
925        // Codegens the shims described above:
926        //
927        //   bx:
928        //      invoke %try_func(%data) normal %normal unwind %catch
929        //
930        //   normal:
931        //      ret 0
932        //
933        //   catch:
934        //      (%ptr, _) = landingpad
935        //      call %catch_func(%data, %ptr)
936        //      ret 1
937        let then = bx.append_sibling_block("then");
938        let catch = bx.append_sibling_block("catch");
939
940        let try_func = llvm::get_param(bx.llfn(), 0);
941        let data = llvm::get_param(bx.llfn(), 1);
942        let catch_func = llvm::get_param(bx.llfn(), 2);
943        let try_func_ty = bx.type_func(&[bx.type_ptr()], bx.type_void());
944        bx.invoke(try_func_ty, None, None, try_func, &[data], then, catch, None, None);
945
946        bx.switch_to_block(then);
947        bx.ret(bx.const_i32(0));
948
949        // Type indicator for the exception being thrown.
950        //
951        // The first value in this tuple is a pointer to the exception object
952        // being thrown. The second value is a "selector" indicating which of
953        // the landing pad clauses the exception's type had been matched to.
954        // rust_try ignores the selector.
955        bx.switch_to_block(catch);
956        let lpad_ty = bx.type_struct(&[bx.type_ptr(), bx.type_i32()], false);
957        let vals = bx.landing_pad(lpad_ty, bx.eh_personality(), 1);
958        let tydesc = bx.const_null(bx.type_ptr());
959        bx.add_clause(vals, tydesc);
960        let ptr = bx.extract_value(vals, 0);
961        let catch_ty = bx.type_func(&[bx.type_ptr(), bx.type_ptr()], bx.type_void());
962        bx.call(catch_ty, None, None, catch_func, &[data, ptr], None, None);
963        bx.ret(bx.const_i32(1));
964    });
965
966    // Note that no invoke is used here because by definition this function
967    // can't panic (that's what it's catching).
968    let ret = bx.call(llty, None, None, llfn, &[try_func, data, catch_func], None, None);
969    OperandValue::Immediate(ret).store(bx, dest);
970}
971
972// Variant of codegen_gnu_try used for emscripten where Rust panics are
973// implemented using C++ exceptions. Here we use exceptions of a specific type
974// (`struct rust_panic`) to represent Rust panics.
975fn codegen_emcc_try<'ll, 'tcx>(
976    bx: &mut Builder<'_, 'll, 'tcx>,
977    try_func: &'ll Value,
978    data: &'ll Value,
979    catch_func: &'ll Value,
980    dest: PlaceRef<'tcx, &'ll Value>,
981) {
982    let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
983        // Codegens the shims described above:
984        //
985        //   bx:
986        //      invoke %try_func(%data) normal %normal unwind %catch
987        //
988        //   normal:
989        //      ret 0
990        //
991        //   catch:
992        //      (%ptr, %selector) = landingpad
993        //      %rust_typeid = @llvm.eh.typeid.for(@_ZTI10rust_panic)
994        //      %is_rust_panic = %selector == %rust_typeid
995        //      %catch_data = alloca { i8*, i8 }
996        //      %catch_data[0] = %ptr
997        //      %catch_data[1] = %is_rust_panic
998        //      call %catch_func(%data, %catch_data)
999        //      ret 1
1000        let then = bx.append_sibling_block("then");
1001        let catch = bx.append_sibling_block("catch");
1002
1003        let try_func = llvm::get_param(bx.llfn(), 0);
1004        let data = llvm::get_param(bx.llfn(), 1);
1005        let catch_func = llvm::get_param(bx.llfn(), 2);
1006        let try_func_ty = bx.type_func(&[bx.type_ptr()], bx.type_void());
1007        bx.invoke(try_func_ty, None, None, try_func, &[data], then, catch, None, None);
1008
1009        bx.switch_to_block(then);
1010        bx.ret(bx.const_i32(0));
1011
1012        // Type indicator for the exception being thrown.
1013        //
1014        // The first value in this tuple is a pointer to the exception object
1015        // being thrown. The second value is a "selector" indicating which of
1016        // the landing pad clauses the exception's type had been matched to.
1017        bx.switch_to_block(catch);
1018        let tydesc = bx.eh_catch_typeinfo();
1019        let lpad_ty = bx.type_struct(&[bx.type_ptr(), bx.type_i32()], false);
1020        let vals = bx.landing_pad(lpad_ty, bx.eh_personality(), 2);
1021        bx.add_clause(vals, tydesc);
1022        bx.add_clause(vals, bx.const_null(bx.type_ptr()));
1023        let ptr = bx.extract_value(vals, 0);
1024        let selector = bx.extract_value(vals, 1);
1025
1026        // Check if the typeid we got is the one for a Rust panic.
1027        let rust_typeid = bx.call_intrinsic("llvm.eh.typeid.for", &[bx.val_ty(tydesc)], &[tydesc]);
1028        let is_rust_panic = bx.icmp(IntPredicate::IntEQ, selector, rust_typeid);
1029        let is_rust_panic = bx.zext(is_rust_panic, bx.type_bool());
1030
1031        // We need to pass two values to catch_func (ptr and is_rust_panic), so
1032        // create an alloca and pass a pointer to that.
1033        let ptr_size = bx.tcx().data_layout.pointer_size();
1034        let ptr_align = bx.tcx().data_layout.pointer_align().abi;
1035        let i8_align = bx.tcx().data_layout.i8_align.abi;
1036        // Required in order for there to be no padding between the fields.
1037        assert!(i8_align <= ptr_align);
1038        let catch_data = bx.alloca(2 * ptr_size, ptr_align);
1039        bx.store(ptr, catch_data, ptr_align);
1040        let catch_data_1 = bx.inbounds_ptradd(catch_data, bx.const_usize(ptr_size.bytes()));
1041        bx.store(is_rust_panic, catch_data_1, i8_align);
1042
1043        let catch_ty = bx.type_func(&[bx.type_ptr(), bx.type_ptr()], bx.type_void());
1044        bx.call(catch_ty, None, None, catch_func, &[data, catch_data], None, None);
1045        bx.ret(bx.const_i32(1));
1046    });
1047
1048    // Note that no invoke is used here because by definition this function
1049    // can't panic (that's what it's catching).
1050    let ret = bx.call(llty, None, None, llfn, &[try_func, data, catch_func], None, None);
1051    OperandValue::Immediate(ret).store(bx, dest);
1052}
1053
1054// Helper function to give a Block to a closure to codegen a shim function.
1055// This is currently primarily used for the `try` intrinsic functions above.
1056fn gen_fn<'a, 'll, 'tcx>(
1057    cx: &'a CodegenCx<'ll, 'tcx>,
1058    name: &str,
1059    rust_fn_sig: ty::PolyFnSig<'tcx>,
1060    codegen: &mut dyn FnMut(Builder<'a, 'll, 'tcx>),
1061) -> (&'ll Type, &'ll Value) {
1062    let fn_abi = cx.fn_abi_of_fn_ptr(rust_fn_sig, ty::List::empty());
1063    let llty = fn_abi.llvm_type(cx);
1064    let llfn = cx.declare_fn(name, fn_abi, None);
1065    cx.set_frame_pointer_type(llfn);
1066    cx.apply_target_cpu_attr(llfn);
1067    // FIXME(eddyb) find a nicer way to do this.
1068    llvm::set_linkage(llfn, llvm::Linkage::InternalLinkage);
1069    let llbb = Builder::append_block(cx, llfn, "entry-block");
1070    let bx = Builder::build(cx, llbb);
1071    codegen(bx);
1072    (llty, llfn)
1073}
1074
1075// Helper function used to get a handle to the `__rust_try` function used to
1076// catch exceptions.
1077//
1078// This function is only generated once and is then cached.
1079fn get_rust_try_fn<'a, 'll, 'tcx>(
1080    cx: &'a CodegenCx<'ll, 'tcx>,
1081    codegen: &mut dyn FnMut(Builder<'a, 'll, 'tcx>),
1082) -> (&'ll Type, &'ll Value) {
1083    if let Some(llfn) = cx.rust_try_fn.get() {
1084        return llfn;
1085    }
1086
1087    // Define the type up front for the signature of the rust_try function.
1088    let tcx = cx.tcx;
1089    let i8p = Ty::new_mut_ptr(tcx, tcx.types.i8);
1090    // `unsafe fn(*mut i8) -> ()`
1091    let try_fn_ty = Ty::new_fn_ptr(
1092        tcx,
1093        ty::Binder::dummy(tcx.mk_fn_sig(
1094            [i8p],
1095            tcx.types.unit,
1096            false,
1097            hir::Safety::Unsafe,
1098            ExternAbi::Rust,
1099        )),
1100    );
1101    // `unsafe fn(*mut i8, *mut i8) -> ()`
1102    let catch_fn_ty = Ty::new_fn_ptr(
1103        tcx,
1104        ty::Binder::dummy(tcx.mk_fn_sig(
1105            [i8p, i8p],
1106            tcx.types.unit,
1107            false,
1108            hir::Safety::Unsafe,
1109            ExternAbi::Rust,
1110        )),
1111    );
1112    // `unsafe fn(unsafe fn(*mut i8) -> (), *mut i8, unsafe fn(*mut i8, *mut i8) -> ()) -> i32`
1113    let rust_fn_sig = ty::Binder::dummy(cx.tcx.mk_fn_sig(
1114        [try_fn_ty, i8p, catch_fn_ty],
1115        tcx.types.i32,
1116        false,
1117        hir::Safety::Unsafe,
1118        ExternAbi::Rust,
1119    ));
1120    let rust_try = gen_fn(cx, "__rust_try", rust_fn_sig, codegen);
1121    cx.rust_try_fn.set(Some(rust_try));
1122    rust_try
1123}
1124
1125fn codegen_autodiff<'ll, 'tcx>(
1126    bx: &mut Builder<'_, 'll, 'tcx>,
1127    tcx: TyCtxt<'tcx>,
1128    instance: ty::Instance<'tcx>,
1129    args: &[OperandRef<'tcx, &'ll Value>],
1130    result: PlaceRef<'tcx, &'ll Value>,
1131) {
1132    if !tcx.sess.opts.unstable_opts.autodiff.contains(&rustc_session::config::AutoDiff::Enable) {
1133        let _ = tcx.dcx().emit_almost_fatal(AutoDiffWithoutEnable);
1134    }
1135
1136    let fn_args = instance.args;
1137    let callee_ty = instance.ty(tcx, bx.typing_env());
1138
1139    let sig = callee_ty.fn_sig(tcx).skip_binder();
1140
1141    let ret_ty = sig.output();
1142    let llret_ty = bx.layout_of(ret_ty).llvm_type(bx);
1143
1144    // Get source, diff, and attrs
1145    let (source_id, source_args) = match fn_args.into_type_list(tcx)[0].kind() {
1146        ty::FnDef(def_id, source_params) => (def_id, source_params),
1147        _ => bug!("invalid autodiff intrinsic args"),
1148    };
1149
1150    let fn_source = match Instance::try_resolve(tcx, bx.cx.typing_env(), *source_id, source_args) {
1151        Ok(Some(instance)) => instance,
1152        Ok(None) => bug!(
1153            "could not resolve ({:?}, {:?}) to a specific autodiff instance",
1154            source_id,
1155            source_args
1156        ),
1157        Err(_) => {
1158            // An error has already been emitted
1159            return;
1160        }
1161    };
1162
1163    let source_symbol = symbol_name_for_instance_in_crate(tcx, fn_source.clone(), LOCAL_CRATE);
1164    let Some(fn_to_diff) = bx.cx.get_function(&source_symbol) else {
1165        bug!("could not find source function")
1166    };
1167
1168    let (diff_id, diff_args) = match fn_args.into_type_list(tcx)[1].kind() {
1169        ty::FnDef(def_id, diff_args) => (def_id, diff_args),
1170        _ => bug!("invalid args"),
1171    };
1172
1173    let fn_diff = match Instance::try_resolve(tcx, bx.cx.typing_env(), *diff_id, diff_args) {
1174        Ok(Some(instance)) => instance,
1175        Ok(None) => bug!(
1176            "could not resolve ({:?}, {:?}) to a specific autodiff instance",
1177            diff_id,
1178            diff_args
1179        ),
1180        Err(_) => {
1181            // An error has already been emitted
1182            return;
1183        }
1184    };
1185
1186    let val_arr = get_args_from_tuple(bx, args[2], fn_diff);
1187    let diff_symbol = symbol_name_for_instance_in_crate(tcx, fn_diff.clone(), LOCAL_CRATE);
1188
1189    let Some(mut diff_attrs) = autodiff_attrs(tcx, fn_diff.def_id()) else {
1190        bug!("could not find autodiff attrs")
1191    };
1192
1193    adjust_activity_to_abi(
1194        tcx,
1195        fn_source.ty(tcx, TypingEnv::fully_monomorphized()),
1196        &mut diff_attrs.input_activity,
1197    );
1198
1199    // Build body
1200    generate_enzyme_call(
1201        bx,
1202        bx.cx,
1203        fn_to_diff,
1204        &diff_symbol,
1205        llret_ty,
1206        &val_arr,
1207        diff_attrs.clone(),
1208        result,
1209    );
1210}
1211
1212fn get_args_from_tuple<'ll, 'tcx>(
1213    bx: &mut Builder<'_, 'll, 'tcx>,
1214    tuple_op: OperandRef<'tcx, &'ll Value>,
1215    fn_instance: Instance<'tcx>,
1216) -> Vec<&'ll Value> {
1217    let cx = bx.cx;
1218    let fn_abi = cx.fn_abi_of_instance(fn_instance, ty::List::empty());
1219
1220    match tuple_op.val {
1221        OperandValue::Immediate(val) => vec![val],
1222        OperandValue::Pair(v1, v2) => vec![v1, v2],
1223        OperandValue::Ref(ptr) => {
1224            let tuple_place = PlaceRef { val: ptr, layout: tuple_op.layout };
1225
1226            let mut result = Vec::with_capacity(fn_abi.args.len());
1227            let mut tuple_index = 0;
1228
1229            for arg in &fn_abi.args {
1230                match arg.mode {
1231                    PassMode::Ignore => {}
1232                    PassMode::Direct(_) | PassMode::Cast { .. } => {
1233                        let field = tuple_place.project_field(bx, tuple_index);
1234                        let llvm_ty = field.layout.llvm_type(bx.cx);
1235                        let val = bx.load(llvm_ty, field.val.llval, field.val.align);
1236                        result.push(val);
1237                        tuple_index += 1;
1238                    }
1239                    PassMode::Pair(_, _) => {
1240                        let field = tuple_place.project_field(bx, tuple_index);
1241                        let llvm_ty = field.layout.llvm_type(bx.cx);
1242                        let pair_val = bx.load(llvm_ty, field.val.llval, field.val.align);
1243                        result.push(bx.extract_value(pair_val, 0));
1244                        result.push(bx.extract_value(pair_val, 1));
1245                        tuple_index += 1;
1246                    }
1247                    PassMode::Indirect { .. } => {
1248                        let field = tuple_place.project_field(bx, tuple_index);
1249                        result.push(field.val.llval);
1250                        tuple_index += 1;
1251                    }
1252                }
1253            }
1254
1255            result
1256        }
1257
1258        OperandValue::ZeroSized => vec![],
1259    }
1260}
1261
1262fn generic_simd_intrinsic<'ll, 'tcx>(
1263    bx: &mut Builder<'_, 'll, 'tcx>,
1264    name: Symbol,
1265    fn_args: GenericArgsRef<'tcx>,
1266    args: &[OperandRef<'tcx, &'ll Value>],
1267    ret_ty: Ty<'tcx>,
1268    llret_ty: &'ll Type,
1269    span: Span,
1270) -> Result<&'ll Value, ()> {
1271    macro_rules! return_error {
1272        ($diag: expr) => {{
1273            bx.sess().dcx().emit_err($diag);
1274            return Err(());
1275        }};
1276    }
1277
1278    macro_rules! require {
1279        ($cond: expr, $diag: expr) => {
1280            if !$cond {
1281                return_error!($diag);
1282            }
1283        };
1284    }
1285
1286    macro_rules! require_simd {
1287        ($ty: expr, $variant:ident) => {{
1288            require!($ty.is_simd(), InvalidMonomorphization::$variant { span, name, ty: $ty });
1289            $ty.simd_size_and_type(bx.tcx())
1290        }};
1291    }
1292
1293    /// Returns the bitwidth of the `$ty` argument if it is an `Int` or `Uint` type.
1294    macro_rules! require_int_or_uint_ty {
1295        ($ty: expr, $diag: expr) => {
1296            match $ty {
1297                ty::Int(i) => {
1298                    i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size().bits())
1299                }
1300                ty::Uint(i) => {
1301                    i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size().bits())
1302                }
1303                _ => {
1304                    return_error!($diag);
1305                }
1306            }
1307        };
1308    }
1309
1310    /// Converts a vector mask, where each element has a bit width equal to the data elements it is used with,
1311    /// down to an i1 based mask that can be used by llvm intrinsics.
1312    ///
1313    /// The rust simd semantics are that each element should either consist of all ones or all zeroes,
1314    /// but this information is not available to llvm. Truncating the vector effectively uses the lowest bit,
1315    /// but codegen for several targets is better if we consider the highest bit by shifting.
1316    ///
1317    /// For x86 SSE/AVX targets this is beneficial since most instructions with mask parameters only consider the highest bit.
1318    /// So even though on llvm level we have an additional shift, in the final assembly there is no shift or truncate and
1319    /// instead the mask can be used as is.
1320    ///
1321    /// For aarch64 and other targets there is a benefit because a mask from the sign bit can be more
1322    /// efficiently converted to an all ones / all zeroes mask by comparing whether each element is negative.
1323    fn vector_mask_to_bitmask<'a, 'll, 'tcx>(
1324        bx: &mut Builder<'a, 'll, 'tcx>,
1325        i_xn: &'ll Value,
1326        in_elem_bitwidth: u64,
1327        in_len: u64,
1328    ) -> &'ll Value {
1329        // Shift the MSB to the right by "in_elem_bitwidth - 1" into the first bit position.
1330        let shift_idx = bx.cx.const_int(bx.type_ix(in_elem_bitwidth), (in_elem_bitwidth - 1) as _);
1331        let shift_indices = vec![shift_idx; in_len as _];
1332        let i_xn_msb = bx.lshr(i_xn, bx.const_vector(shift_indices.as_slice()));
1333        // Truncate vector to an <i1 x N>
1334        bx.trunc(i_xn_msb, bx.type_vector(bx.type_i1(), in_len))
1335    }
1336
1337    // Sanity-check: all vector arguments must be immediates.
1338    if cfg!(debug_assertions) {
1339        for arg in args {
1340            if arg.layout.ty.is_simd() {
1341                assert_matches!(arg.val, OperandValue::Immediate(_));
1342            }
1343        }
1344    }
1345
1346    if name == sym::simd_select_bitmask {
1347        let (len, _) = require_simd!(args[1].layout.ty, SimdArgument);
1348
1349        let expected_int_bits = len.max(8).next_power_of_two();
1350        let expected_bytes = len.div_ceil(8);
1351
1352        let mask_ty = args[0].layout.ty;
1353        let mask = match mask_ty.kind() {
1354            ty::Int(i) if i.bit_width() == Some(expected_int_bits) => args[0].immediate(),
1355            ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => args[0].immediate(),
1356            ty::Array(elem, len)
1357                if matches!(elem.kind(), ty::Uint(ty::UintTy::U8))
1358                    && len
1359                        .try_to_target_usize(bx.tcx)
1360                        .expect("expected monomorphic const in codegen")
1361                        == expected_bytes =>
1362            {
1363                let place = PlaceRef::alloca(bx, args[0].layout);
1364                args[0].val.store(bx, place);
1365                let int_ty = bx.type_ix(expected_bytes * 8);
1366                bx.load(int_ty, place.val.llval, Align::ONE)
1367            }
1368            _ => return_error!(InvalidMonomorphization::InvalidBitmask {
1369                span,
1370                name,
1371                mask_ty,
1372                expected_int_bits,
1373                expected_bytes
1374            }),
1375        };
1376
1377        let i1 = bx.type_i1();
1378        let im = bx.type_ix(len);
1379        let i1xn = bx.type_vector(i1, len);
1380        let m_im = bx.trunc(mask, im);
1381        let m_i1s = bx.bitcast(m_im, i1xn);
1382        return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1383    }
1384
1385    // every intrinsic below takes a SIMD vector as its first argument
1386    let (in_len, in_elem) = require_simd!(args[0].layout.ty, SimdInput);
1387    let in_ty = args[0].layout.ty;
1388
1389    let comparison = match name {
1390        sym::simd_eq => Some(BinOp::Eq),
1391        sym::simd_ne => Some(BinOp::Ne),
1392        sym::simd_lt => Some(BinOp::Lt),
1393        sym::simd_le => Some(BinOp::Le),
1394        sym::simd_gt => Some(BinOp::Gt),
1395        sym::simd_ge => Some(BinOp::Ge),
1396        _ => None,
1397    };
1398
1399    if let Some(cmp_op) = comparison {
1400        let (out_len, out_ty) = require_simd!(ret_ty, SimdReturn);
1401
1402        require!(
1403            in_len == out_len,
1404            InvalidMonomorphization::ReturnLengthInputType {
1405                span,
1406                name,
1407                in_len,
1408                in_ty,
1409                ret_ty,
1410                out_len
1411            }
1412        );
1413        require!(
1414            bx.type_kind(bx.element_type(llret_ty)) == TypeKind::Integer,
1415            InvalidMonomorphization::ReturnIntegerType { span, name, ret_ty, out_ty }
1416        );
1417
1418        return Ok(compare_simd_types(
1419            bx,
1420            args[0].immediate(),
1421            args[1].immediate(),
1422            in_elem,
1423            llret_ty,
1424            cmp_op,
1425        ));
1426    }
1427
1428    if name == sym::simd_shuffle_const_generic {
1429        let idx = fn_args[2].expect_const().to_value().valtree.unwrap_branch();
1430        let n = idx.len() as u64;
1431
1432        let (out_len, out_ty) = require_simd!(ret_ty, SimdReturn);
1433        require!(
1434            out_len == n,
1435            InvalidMonomorphization::ReturnLength { span, name, in_len: n, ret_ty, out_len }
1436        );
1437        require!(
1438            in_elem == out_ty,
1439            InvalidMonomorphization::ReturnElement { span, name, in_elem, in_ty, ret_ty, out_ty }
1440        );
1441
1442        let total_len = in_len * 2;
1443
1444        let indices: Option<Vec<_>> = idx
1445            .iter()
1446            .enumerate()
1447            .map(|(arg_idx, val)| {
1448                let idx = val.unwrap_leaf().to_i32();
1449                if idx >= i32::try_from(total_len).unwrap() {
1450                    bx.sess().dcx().emit_err(InvalidMonomorphization::SimdIndexOutOfBounds {
1451                        span,
1452                        name,
1453                        arg_idx: arg_idx as u64,
1454                        total_len: total_len.into(),
1455                    });
1456                    None
1457                } else {
1458                    Some(bx.const_i32(idx))
1459                }
1460            })
1461            .collect();
1462        let Some(indices) = indices else {
1463            return Ok(bx.const_null(llret_ty));
1464        };
1465
1466        return Ok(bx.shuffle_vector(
1467            args[0].immediate(),
1468            args[1].immediate(),
1469            bx.const_vector(&indices),
1470        ));
1471    }
1472
1473    if name == sym::simd_shuffle {
1474        // Make sure this is actually a SIMD vector.
1475        let idx_ty = args[2].layout.ty;
1476        let n: u64 = if idx_ty.is_simd()
1477            && matches!(idx_ty.simd_size_and_type(bx.cx.tcx).1.kind(), ty::Uint(ty::UintTy::U32))
1478        {
1479            idx_ty.simd_size_and_type(bx.cx.tcx).0
1480        } else {
1481            return_error!(InvalidMonomorphization::SimdShuffle { span, name, ty: idx_ty })
1482        };
1483
1484        let (out_len, out_ty) = require_simd!(ret_ty, SimdReturn);
1485        require!(
1486            out_len == n,
1487            InvalidMonomorphization::ReturnLength { span, name, in_len: n, ret_ty, out_len }
1488        );
1489        require!(
1490            in_elem == out_ty,
1491            InvalidMonomorphization::ReturnElement { span, name, in_elem, in_ty, ret_ty, out_ty }
1492        );
1493
1494        let total_len = u128::from(in_len) * 2;
1495
1496        // Check that the indices are in-bounds.
1497        let indices = args[2].immediate();
1498        for i in 0..n {
1499            let val = bx.const_get_elt(indices, i as u64);
1500            let idx = bx
1501                .const_to_opt_u128(val, true)
1502                .unwrap_or_else(|| bug!("typeck should have already ensured that these are const"));
1503            if idx >= total_len {
1504                return_error!(InvalidMonomorphization::SimdIndexOutOfBounds {
1505                    span,
1506                    name,
1507                    arg_idx: i,
1508                    total_len,
1509                });
1510            }
1511        }
1512
1513        return Ok(bx.shuffle_vector(args[0].immediate(), args[1].immediate(), indices));
1514    }
1515
1516    if name == sym::simd_insert || name == sym::simd_insert_dyn {
1517        require!(
1518            in_elem == args[2].layout.ty,
1519            InvalidMonomorphization::InsertedType {
1520                span,
1521                name,
1522                in_elem,
1523                in_ty,
1524                out_ty: args[2].layout.ty
1525            }
1526        );
1527
1528        let index_imm = if name == sym::simd_insert {
1529            let idx = bx
1530                .const_to_opt_u128(args[1].immediate(), false)
1531                .expect("typeck should have ensure that this is a const");
1532            if idx >= in_len.into() {
1533                return_error!(InvalidMonomorphization::SimdIndexOutOfBounds {
1534                    span,
1535                    name,
1536                    arg_idx: 1,
1537                    total_len: in_len.into(),
1538                });
1539            }
1540            bx.const_i32(idx as i32)
1541        } else {
1542            args[1].immediate()
1543        };
1544
1545        return Ok(bx.insert_element(args[0].immediate(), args[2].immediate(), index_imm));
1546    }
1547    if name == sym::simd_extract || name == sym::simd_extract_dyn {
1548        require!(
1549            ret_ty == in_elem,
1550            InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty }
1551        );
1552        let index_imm = if name == sym::simd_extract {
1553            let idx = bx
1554                .const_to_opt_u128(args[1].immediate(), false)
1555                .expect("typeck should have ensure that this is a const");
1556            if idx >= in_len.into() {
1557                return_error!(InvalidMonomorphization::SimdIndexOutOfBounds {
1558                    span,
1559                    name,
1560                    arg_idx: 1,
1561                    total_len: in_len.into(),
1562                });
1563            }
1564            bx.const_i32(idx as i32)
1565        } else {
1566            args[1].immediate()
1567        };
1568
1569        return Ok(bx.extract_element(args[0].immediate(), index_imm));
1570    }
1571
1572    if name == sym::simd_select {
1573        let m_elem_ty = in_elem;
1574        let m_len = in_len;
1575        let (v_len, _) = require_simd!(args[1].layout.ty, SimdArgument);
1576        require!(
1577            m_len == v_len,
1578            InvalidMonomorphization::MismatchedLengths { span, name, m_len, v_len }
1579        );
1580        let in_elem_bitwidth = require_int_or_uint_ty!(
1581            m_elem_ty.kind(),
1582            InvalidMonomorphization::MaskWrongElementType { span, name, ty: m_elem_ty }
1583        );
1584        let m_i1s = vector_mask_to_bitmask(bx, args[0].immediate(), in_elem_bitwidth, m_len);
1585        return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1586    }
1587
1588    if name == sym::simd_bitmask {
1589        // The `fn simd_bitmask(vector) -> unsigned integer` intrinsic takes a vector mask and
1590        // returns one bit for each lane (which must all be `0` or `!0`) in the form of either:
1591        // * an unsigned integer
1592        // * an array of `u8`
1593        // If the vector has less than 8 lanes, a u8 is returned with zeroed trailing bits.
1594        //
1595        // The bit order of the result depends on the byte endianness, LSB-first for little
1596        // endian and MSB-first for big endian.
1597        let expected_int_bits = in_len.max(8).next_power_of_two();
1598        let expected_bytes = in_len.div_ceil(8);
1599
1600        // Integer vector <i{in_bitwidth} x in_len>:
1601        let in_elem_bitwidth = require_int_or_uint_ty!(
1602            in_elem.kind(),
1603            InvalidMonomorphization::MaskWrongElementType { span, name, ty: in_elem }
1604        );
1605
1606        let i1xn = vector_mask_to_bitmask(bx, args[0].immediate(), in_elem_bitwidth, in_len);
1607        // Bitcast <i1 x N> to iN:
1608        let i_ = bx.bitcast(i1xn, bx.type_ix(in_len));
1609
1610        match ret_ty.kind() {
1611            ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => {
1612                // Zero-extend iN to the bitmask type:
1613                return Ok(bx.zext(i_, bx.type_ix(expected_int_bits)));
1614            }
1615            ty::Array(elem, len)
1616                if matches!(elem.kind(), ty::Uint(ty::UintTy::U8))
1617                    && len
1618                        .try_to_target_usize(bx.tcx)
1619                        .expect("expected monomorphic const in codegen")
1620                        == expected_bytes =>
1621            {
1622                // Zero-extend iN to the array length:
1623                let ze = bx.zext(i_, bx.type_ix(expected_bytes * 8));
1624
1625                // Convert the integer to a byte array
1626                let ptr = bx.alloca(Size::from_bytes(expected_bytes), Align::ONE);
1627                bx.store(ze, ptr, Align::ONE);
1628                let array_ty = bx.type_array(bx.type_i8(), expected_bytes);
1629                return Ok(bx.load(array_ty, ptr, Align::ONE));
1630            }
1631            _ => return_error!(InvalidMonomorphization::CannotReturn {
1632                span,
1633                name,
1634                ret_ty,
1635                expected_int_bits,
1636                expected_bytes
1637            }),
1638        }
1639    }
1640
1641    fn simd_simple_float_intrinsic<'ll, 'tcx>(
1642        name: Symbol,
1643        in_elem: Ty<'_>,
1644        in_ty: Ty<'_>,
1645        in_len: u64,
1646        bx: &mut Builder<'_, 'll, 'tcx>,
1647        span: Span,
1648        args: &[OperandRef<'tcx, &'ll Value>],
1649    ) -> Result<&'ll Value, ()> {
1650        macro_rules! return_error {
1651            ($diag: expr) => {{
1652                bx.sess().dcx().emit_err($diag);
1653                return Err(());
1654            }};
1655        }
1656
1657        let elem_ty = if let ty::Float(f) = in_elem.kind() {
1658            bx.cx.type_float_from_ty(*f)
1659        } else {
1660            return_error!(InvalidMonomorphization::FloatingPointType { span, name, in_ty });
1661        };
1662
1663        let vec_ty = bx.type_vector(elem_ty, in_len);
1664
1665        let intr_name = match name {
1666            sym::simd_ceil => "llvm.ceil",
1667            sym::simd_fabs => "llvm.fabs",
1668            sym::simd_fcos => "llvm.cos",
1669            sym::simd_fexp2 => "llvm.exp2",
1670            sym::simd_fexp => "llvm.exp",
1671            sym::simd_flog10 => "llvm.log10",
1672            sym::simd_flog2 => "llvm.log2",
1673            sym::simd_flog => "llvm.log",
1674            sym::simd_floor => "llvm.floor",
1675            sym::simd_fma => "llvm.fma",
1676            sym::simd_relaxed_fma => "llvm.fmuladd",
1677            sym::simd_fsin => "llvm.sin",
1678            sym::simd_fsqrt => "llvm.sqrt",
1679            sym::simd_round => "llvm.round",
1680            sym::simd_round_ties_even => "llvm.rint",
1681            sym::simd_trunc => "llvm.trunc",
1682            _ => return_error!(InvalidMonomorphization::UnrecognizedIntrinsic { span, name }),
1683        };
1684        Ok(bx.call_intrinsic(
1685            intr_name,
1686            &[vec_ty],
1687            &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
1688        ))
1689    }
1690
1691    if std::matches!(
1692        name,
1693        sym::simd_ceil
1694            | sym::simd_fabs
1695            | sym::simd_fcos
1696            | sym::simd_fexp2
1697            | sym::simd_fexp
1698            | sym::simd_flog10
1699            | sym::simd_flog2
1700            | sym::simd_flog
1701            | sym::simd_floor
1702            | sym::simd_fma
1703            | sym::simd_fsin
1704            | sym::simd_fsqrt
1705            | sym::simd_relaxed_fma
1706            | sym::simd_round
1707            | sym::simd_round_ties_even
1708            | sym::simd_trunc
1709    ) {
1710        return simd_simple_float_intrinsic(name, in_elem, in_ty, in_len, bx, span, args);
1711    }
1712
1713    fn llvm_vector_ty<'ll>(cx: &CodegenCx<'ll, '_>, elem_ty: Ty<'_>, vec_len: u64) -> &'ll Type {
1714        let elem_ty = match *elem_ty.kind() {
1715            ty::Int(v) => cx.type_int_from_ty(v),
1716            ty::Uint(v) => cx.type_uint_from_ty(v),
1717            ty::Float(v) => cx.type_float_from_ty(v),
1718            ty::RawPtr(_, _) => cx.type_ptr(),
1719            _ => unreachable!(),
1720        };
1721        cx.type_vector(elem_ty, vec_len)
1722    }
1723
1724    if name == sym::simd_gather {
1725        // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1726        //             mask: <N x i{M}>) -> <N x T>
1727        // * N: number of elements in the input vectors
1728        // * T: type of the element to load
1729        // * M: any integer width is supported, will be truncated to i1
1730
1731        // All types must be simd vector types
1732
1733        // The second argument must be a simd vector with an element type that's a pointer
1734        // to the element type of the first argument
1735        let (_, element_ty0) = require_simd!(in_ty, SimdFirst);
1736        let (out_len, element_ty1) = require_simd!(args[1].layout.ty, SimdSecond);
1737        // The element type of the third argument must be a signed integer type of any width:
1738        let (out_len2, element_ty2) = require_simd!(args[2].layout.ty, SimdThird);
1739        require_simd!(ret_ty, SimdReturn);
1740
1741        // Of the same length:
1742        require!(
1743            in_len == out_len,
1744            InvalidMonomorphization::SecondArgumentLength {
1745                span,
1746                name,
1747                in_len,
1748                in_ty,
1749                arg_ty: args[1].layout.ty,
1750                out_len
1751            }
1752        );
1753        require!(
1754            in_len == out_len2,
1755            InvalidMonomorphization::ThirdArgumentLength {
1756                span,
1757                name,
1758                in_len,
1759                in_ty,
1760                arg_ty: args[2].layout.ty,
1761                out_len: out_len2
1762            }
1763        );
1764
1765        // The return type must match the first argument type
1766        require!(
1767            ret_ty == in_ty,
1768            InvalidMonomorphization::ExpectedReturnType { span, name, in_ty, ret_ty }
1769        );
1770
1771        require!(
1772            matches!(
1773                *element_ty1.kind(),
1774                ty::RawPtr(p_ty, _) if p_ty == in_elem && p_ty.kind() == element_ty0.kind()
1775            ),
1776            InvalidMonomorphization::ExpectedElementType {
1777                span,
1778                name,
1779                expected_element: element_ty1,
1780                second_arg: args[1].layout.ty,
1781                in_elem,
1782                in_ty,
1783                mutability: ExpectedPointerMutability::Not,
1784            }
1785        );
1786
1787        let mask_elem_bitwidth = require_int_or_uint_ty!(
1788            element_ty2.kind(),
1789            InvalidMonomorphization::MaskWrongElementType { span, name, ty: element_ty2 }
1790        );
1791
1792        // Alignment of T, must be a constant integer value:
1793        let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1794
1795        // Truncate the mask vector to a vector of i1s:
1796        let mask = vector_mask_to_bitmask(bx, args[2].immediate(), mask_elem_bitwidth, in_len);
1797
1798        // Type of the vector of pointers:
1799        let llvm_pointer_vec_ty = llvm_vector_ty(bx, element_ty1, in_len);
1800
1801        // Type of the vector of elements:
1802        let llvm_elem_vec_ty = llvm_vector_ty(bx, element_ty0, in_len);
1803
1804        return Ok(bx.call_intrinsic(
1805            "llvm.masked.gather",
1806            &[llvm_elem_vec_ty, llvm_pointer_vec_ty],
1807            &[args[1].immediate(), alignment, mask, args[0].immediate()],
1808        ));
1809    }
1810
1811    if name == sym::simd_masked_load {
1812        // simd_masked_load(mask: <N x i{M}>, pointer: *_ T, values: <N x T>) -> <N x T>
1813        // * N: number of elements in the input vectors
1814        // * T: type of the element to load
1815        // * M: any integer width is supported, will be truncated to i1
1816        // Loads contiguous elements from memory behind `pointer`, but only for
1817        // those lanes whose `mask` bit is enabled.
1818        // The memory addresses corresponding to the “off” lanes are not accessed.
1819
1820        // The element type of the "mask" argument must be a signed integer type of any width
1821        let mask_ty = in_ty;
1822        let (mask_len, mask_elem) = (in_len, in_elem);
1823
1824        // The second argument must be a pointer matching the element type
1825        let pointer_ty = args[1].layout.ty;
1826
1827        // The last argument is a passthrough vector providing values for disabled lanes
1828        let values_ty = args[2].layout.ty;
1829        let (values_len, values_elem) = require_simd!(values_ty, SimdThird);
1830
1831        require_simd!(ret_ty, SimdReturn);
1832
1833        // Of the same length:
1834        require!(
1835            values_len == mask_len,
1836            InvalidMonomorphization::ThirdArgumentLength {
1837                span,
1838                name,
1839                in_len: mask_len,
1840                in_ty: mask_ty,
1841                arg_ty: values_ty,
1842                out_len: values_len
1843            }
1844        );
1845
1846        // The return type must match the last argument type
1847        require!(
1848            ret_ty == values_ty,
1849            InvalidMonomorphization::ExpectedReturnType { span, name, in_ty: values_ty, ret_ty }
1850        );
1851
1852        require!(
1853            matches!(
1854                *pointer_ty.kind(),
1855                ty::RawPtr(p_ty, _) if p_ty == values_elem && p_ty.kind() == values_elem.kind()
1856            ),
1857            InvalidMonomorphization::ExpectedElementType {
1858                span,
1859                name,
1860                expected_element: values_elem,
1861                second_arg: pointer_ty,
1862                in_elem: values_elem,
1863                in_ty: values_ty,
1864                mutability: ExpectedPointerMutability::Not,
1865            }
1866        );
1867
1868        let m_elem_bitwidth = require_int_or_uint_ty!(
1869            mask_elem.kind(),
1870            InvalidMonomorphization::MaskWrongElementType { span, name, ty: mask_elem }
1871        );
1872
1873        let mask = vector_mask_to_bitmask(bx, args[0].immediate(), m_elem_bitwidth, mask_len);
1874
1875        // Alignment of T, must be a constant integer value:
1876        let alignment = bx.const_i32(bx.align_of(values_elem).bytes() as i32);
1877
1878        let llvm_pointer = bx.type_ptr();
1879
1880        // Type of the vector of elements:
1881        let llvm_elem_vec_ty = llvm_vector_ty(bx, values_elem, values_len);
1882
1883        return Ok(bx.call_intrinsic(
1884            "llvm.masked.load",
1885            &[llvm_elem_vec_ty, llvm_pointer],
1886            &[args[1].immediate(), alignment, mask, args[2].immediate()],
1887        ));
1888    }
1889
1890    if name == sym::simd_masked_store {
1891        // simd_masked_store(mask: <N x i{M}>, pointer: *mut T, values: <N x T>) -> ()
1892        // * N: number of elements in the input vectors
1893        // * T: type of the element to load
1894        // * M: any integer width is supported, will be truncated to i1
1895        // Stores contiguous elements to memory behind `pointer`, but only for
1896        // those lanes whose `mask` bit is enabled.
1897        // The memory addresses corresponding to the “off” lanes are not accessed.
1898
1899        // The element type of the "mask" argument must be a signed integer type of any width
1900        let mask_ty = in_ty;
1901        let (mask_len, mask_elem) = (in_len, in_elem);
1902
1903        // The second argument must be a pointer matching the element type
1904        let pointer_ty = args[1].layout.ty;
1905
1906        // The last argument specifies the values to store to memory
1907        let values_ty = args[2].layout.ty;
1908        let (values_len, values_elem) = require_simd!(values_ty, SimdThird);
1909
1910        // Of the same length:
1911        require!(
1912            values_len == mask_len,
1913            InvalidMonomorphization::ThirdArgumentLength {
1914                span,
1915                name,
1916                in_len: mask_len,
1917                in_ty: mask_ty,
1918                arg_ty: values_ty,
1919                out_len: values_len
1920            }
1921        );
1922
1923        // The second argument must be a mutable pointer type matching the element type
1924        require!(
1925            matches!(
1926                *pointer_ty.kind(),
1927                ty::RawPtr(p_ty, p_mutbl)
1928                    if p_ty == values_elem && p_ty.kind() == values_elem.kind() && p_mutbl.is_mut()
1929            ),
1930            InvalidMonomorphization::ExpectedElementType {
1931                span,
1932                name,
1933                expected_element: values_elem,
1934                second_arg: pointer_ty,
1935                in_elem: values_elem,
1936                in_ty: values_ty,
1937                mutability: ExpectedPointerMutability::Mut,
1938            }
1939        );
1940
1941        let m_elem_bitwidth = require_int_or_uint_ty!(
1942            mask_elem.kind(),
1943            InvalidMonomorphization::MaskWrongElementType { span, name, ty: mask_elem }
1944        );
1945
1946        let mask = vector_mask_to_bitmask(bx, args[0].immediate(), m_elem_bitwidth, mask_len);
1947
1948        // Alignment of T, must be a constant integer value:
1949        let alignment = bx.const_i32(bx.align_of(values_elem).bytes() as i32);
1950
1951        let llvm_pointer = bx.type_ptr();
1952
1953        // Type of the vector of elements:
1954        let llvm_elem_vec_ty = llvm_vector_ty(bx, values_elem, values_len);
1955
1956        return Ok(bx.call_intrinsic(
1957            "llvm.masked.store",
1958            &[llvm_elem_vec_ty, llvm_pointer],
1959            &[args[2].immediate(), args[1].immediate(), alignment, mask],
1960        ));
1961    }
1962
1963    if name == sym::simd_scatter {
1964        // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1965        //             mask: <N x i{M}>) -> ()
1966        // * N: number of elements in the input vectors
1967        // * T: type of the element to load
1968        // * M: any integer width is supported, will be truncated to i1
1969
1970        // All types must be simd vector types
1971        // The second argument must be a simd vector with an element type that's a pointer
1972        // to the element type of the first argument
1973        let (_, element_ty0) = require_simd!(in_ty, SimdFirst);
1974        let (element_len1, element_ty1) = require_simd!(args[1].layout.ty, SimdSecond);
1975        let (element_len2, element_ty2) = require_simd!(args[2].layout.ty, SimdThird);
1976
1977        // Of the same length:
1978        require!(
1979            in_len == element_len1,
1980            InvalidMonomorphization::SecondArgumentLength {
1981                span,
1982                name,
1983                in_len,
1984                in_ty,
1985                arg_ty: args[1].layout.ty,
1986                out_len: element_len1
1987            }
1988        );
1989        require!(
1990            in_len == element_len2,
1991            InvalidMonomorphization::ThirdArgumentLength {
1992                span,
1993                name,
1994                in_len,
1995                in_ty,
1996                arg_ty: args[2].layout.ty,
1997                out_len: element_len2
1998            }
1999        );
2000
2001        require!(
2002            matches!(
2003                *element_ty1.kind(),
2004                ty::RawPtr(p_ty, p_mutbl)
2005                    if p_ty == in_elem && p_mutbl.is_mut() && p_ty.kind() == element_ty0.kind()
2006            ),
2007            InvalidMonomorphization::ExpectedElementType {
2008                span,
2009                name,
2010                expected_element: element_ty1,
2011                second_arg: args[1].layout.ty,
2012                in_elem,
2013                in_ty,
2014                mutability: ExpectedPointerMutability::Mut,
2015            }
2016        );
2017
2018        // The element type of the third argument must be an integer type of any width:
2019        let mask_elem_bitwidth = require_int_or_uint_ty!(
2020            element_ty2.kind(),
2021            InvalidMonomorphization::MaskWrongElementType { span, name, ty: element_ty2 }
2022        );
2023
2024        // Alignment of T, must be a constant integer value:
2025        let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
2026
2027        // Truncate the mask vector to a vector of i1s:
2028        let mask = vector_mask_to_bitmask(bx, args[2].immediate(), mask_elem_bitwidth, in_len);
2029
2030        // Type of the vector of pointers:
2031        let llvm_pointer_vec_ty = llvm_vector_ty(bx, element_ty1, in_len);
2032
2033        // Type of the vector of elements:
2034        let llvm_elem_vec_ty = llvm_vector_ty(bx, element_ty0, in_len);
2035
2036        return Ok(bx.call_intrinsic(
2037            "llvm.masked.scatter",
2038            &[llvm_elem_vec_ty, llvm_pointer_vec_ty],
2039            &[args[0].immediate(), args[1].immediate(), alignment, mask],
2040        ));
2041    }
2042
2043    macro_rules! arith_red {
2044        ($name:ident : $integer_reduce:ident, $float_reduce:ident, $ordered:expr, $op:ident,
2045         $identity:expr) => {
2046            if name == sym::$name {
2047                require!(
2048                    ret_ty == in_elem,
2049                    InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty }
2050                );
2051                return match in_elem.kind() {
2052                    ty::Int(_) | ty::Uint(_) => {
2053                        let r = bx.$integer_reduce(args[0].immediate());
2054                        if $ordered {
2055                            // if overflow occurs, the result is the
2056                            // mathematical result modulo 2^n:
2057                            Ok(bx.$op(args[1].immediate(), r))
2058                        } else {
2059                            Ok(bx.$integer_reduce(args[0].immediate()))
2060                        }
2061                    }
2062                    ty::Float(f) => {
2063                        let acc = if $ordered {
2064                            // ordered arithmetic reductions take an accumulator
2065                            args[1].immediate()
2066                        } else {
2067                            // unordered arithmetic reductions use the identity accumulator
2068                            match f.bit_width() {
2069                                32 => bx.const_real(bx.type_f32(), $identity),
2070                                64 => bx.const_real(bx.type_f64(), $identity),
2071                                v => return_error!(
2072                                    InvalidMonomorphization::UnsupportedSymbolOfSize {
2073                                        span,
2074                                        name,
2075                                        symbol: sym::$name,
2076                                        in_ty,
2077                                        in_elem,
2078                                        size: v,
2079                                        ret_ty
2080                                    }
2081                                ),
2082                            }
2083                        };
2084                        Ok(bx.$float_reduce(acc, args[0].immediate()))
2085                    }
2086                    _ => return_error!(InvalidMonomorphization::UnsupportedSymbol {
2087                        span,
2088                        name,
2089                        symbol: sym::$name,
2090                        in_ty,
2091                        in_elem,
2092                        ret_ty
2093                    }),
2094                };
2095            }
2096        };
2097    }
2098
2099    arith_red!(simd_reduce_add_ordered: vector_reduce_add, vector_reduce_fadd, true, add, -0.0);
2100    arith_red!(simd_reduce_mul_ordered: vector_reduce_mul, vector_reduce_fmul, true, mul, 1.0);
2101    arith_red!(
2102        simd_reduce_add_unordered: vector_reduce_add,
2103        vector_reduce_fadd_reassoc,
2104        false,
2105        add,
2106        -0.0
2107    );
2108    arith_red!(
2109        simd_reduce_mul_unordered: vector_reduce_mul,
2110        vector_reduce_fmul_reassoc,
2111        false,
2112        mul,
2113        1.0
2114    );
2115
2116    macro_rules! minmax_red {
2117        ($name:ident: $int_red:ident, $float_red:ident) => {
2118            if name == sym::$name {
2119                require!(
2120                    ret_ty == in_elem,
2121                    InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty }
2122                );
2123                return match in_elem.kind() {
2124                    ty::Int(_i) => Ok(bx.$int_red(args[0].immediate(), true)),
2125                    ty::Uint(_u) => Ok(bx.$int_red(args[0].immediate(), false)),
2126                    ty::Float(_f) => Ok(bx.$float_red(args[0].immediate())),
2127                    _ => return_error!(InvalidMonomorphization::UnsupportedSymbol {
2128                        span,
2129                        name,
2130                        symbol: sym::$name,
2131                        in_ty,
2132                        in_elem,
2133                        ret_ty
2134                    }),
2135                };
2136            }
2137        };
2138    }
2139
2140    minmax_red!(simd_reduce_min: vector_reduce_min, vector_reduce_fmin);
2141    minmax_red!(simd_reduce_max: vector_reduce_max, vector_reduce_fmax);
2142
2143    macro_rules! bitwise_red {
2144        ($name:ident : $red:ident, $boolean:expr) => {
2145            if name == sym::$name {
2146                let input = if !$boolean {
2147                    require!(
2148                        ret_ty == in_elem,
2149                        InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty }
2150                    );
2151                    args[0].immediate()
2152                } else {
2153                    let bitwidth = match in_elem.kind() {
2154                        ty::Int(i) => {
2155                            i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size().bits())
2156                        }
2157                        ty::Uint(i) => {
2158                            i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size().bits())
2159                        }
2160                        _ => return_error!(InvalidMonomorphization::UnsupportedSymbol {
2161                            span,
2162                            name,
2163                            symbol: sym::$name,
2164                            in_ty,
2165                            in_elem,
2166                            ret_ty
2167                        }),
2168                    };
2169
2170                    vector_mask_to_bitmask(bx, args[0].immediate(), bitwidth, in_len as _)
2171                };
2172                return match in_elem.kind() {
2173                    ty::Int(_) | ty::Uint(_) => {
2174                        let r = bx.$red(input);
2175                        Ok(if !$boolean { r } else { bx.zext(r, bx.type_bool()) })
2176                    }
2177                    _ => return_error!(InvalidMonomorphization::UnsupportedSymbol {
2178                        span,
2179                        name,
2180                        symbol: sym::$name,
2181                        in_ty,
2182                        in_elem,
2183                        ret_ty
2184                    }),
2185                };
2186            }
2187        };
2188    }
2189
2190    bitwise_red!(simd_reduce_and: vector_reduce_and, false);
2191    bitwise_red!(simd_reduce_or: vector_reduce_or, false);
2192    bitwise_red!(simd_reduce_xor: vector_reduce_xor, false);
2193    bitwise_red!(simd_reduce_all: vector_reduce_and, true);
2194    bitwise_red!(simd_reduce_any: vector_reduce_or, true);
2195
2196    if name == sym::simd_cast_ptr {
2197        let (out_len, out_elem) = require_simd!(ret_ty, SimdReturn);
2198        require!(
2199            in_len == out_len,
2200            InvalidMonomorphization::ReturnLengthInputType {
2201                span,
2202                name,
2203                in_len,
2204                in_ty,
2205                ret_ty,
2206                out_len
2207            }
2208        );
2209
2210        match in_elem.kind() {
2211            ty::RawPtr(p_ty, _) => {
2212                let metadata = p_ty.ptr_metadata_ty(bx.tcx, |ty| {
2213                    bx.tcx.normalize_erasing_regions(bx.typing_env(), ty)
2214                });
2215                require!(
2216                    metadata.is_unit(),
2217                    InvalidMonomorphization::CastWidePointer { span, name, ty: in_elem }
2218                );
2219            }
2220            _ => {
2221                return_error!(InvalidMonomorphization::ExpectedPointer { span, name, ty: in_elem })
2222            }
2223        }
2224        match out_elem.kind() {
2225            ty::RawPtr(p_ty, _) => {
2226                let metadata = p_ty.ptr_metadata_ty(bx.tcx, |ty| {
2227                    bx.tcx.normalize_erasing_regions(bx.typing_env(), ty)
2228                });
2229                require!(
2230                    metadata.is_unit(),
2231                    InvalidMonomorphization::CastWidePointer { span, name, ty: out_elem }
2232                );
2233            }
2234            _ => {
2235                return_error!(InvalidMonomorphization::ExpectedPointer { span, name, ty: out_elem })
2236            }
2237        }
2238
2239        return Ok(args[0].immediate());
2240    }
2241
2242    if name == sym::simd_expose_provenance {
2243        let (out_len, out_elem) = require_simd!(ret_ty, SimdReturn);
2244        require!(
2245            in_len == out_len,
2246            InvalidMonomorphization::ReturnLengthInputType {
2247                span,
2248                name,
2249                in_len,
2250                in_ty,
2251                ret_ty,
2252                out_len
2253            }
2254        );
2255
2256        match in_elem.kind() {
2257            ty::RawPtr(_, _) => {}
2258            _ => {
2259                return_error!(InvalidMonomorphization::ExpectedPointer { span, name, ty: in_elem })
2260            }
2261        }
2262        match out_elem.kind() {
2263            ty::Uint(ty::UintTy::Usize) => {}
2264            _ => return_error!(InvalidMonomorphization::ExpectedUsize { span, name, ty: out_elem }),
2265        }
2266
2267        return Ok(bx.ptrtoint(args[0].immediate(), llret_ty));
2268    }
2269
2270    if name == sym::simd_with_exposed_provenance {
2271        let (out_len, out_elem) = require_simd!(ret_ty, SimdReturn);
2272        require!(
2273            in_len == out_len,
2274            InvalidMonomorphization::ReturnLengthInputType {
2275                span,
2276                name,
2277                in_len,
2278                in_ty,
2279                ret_ty,
2280                out_len
2281            }
2282        );
2283
2284        match in_elem.kind() {
2285            ty::Uint(ty::UintTy::Usize) => {}
2286            _ => return_error!(InvalidMonomorphization::ExpectedUsize { span, name, ty: in_elem }),
2287        }
2288        match out_elem.kind() {
2289            ty::RawPtr(_, _) => {}
2290            _ => {
2291                return_error!(InvalidMonomorphization::ExpectedPointer { span, name, ty: out_elem })
2292            }
2293        }
2294
2295        return Ok(bx.inttoptr(args[0].immediate(), llret_ty));
2296    }
2297
2298    if name == sym::simd_cast || name == sym::simd_as {
2299        let (out_len, out_elem) = require_simd!(ret_ty, SimdReturn);
2300        require!(
2301            in_len == out_len,
2302            InvalidMonomorphization::ReturnLengthInputType {
2303                span,
2304                name,
2305                in_len,
2306                in_ty,
2307                ret_ty,
2308                out_len
2309            }
2310        );
2311        // casting cares about nominal type, not just structural type
2312        if in_elem == out_elem {
2313            return Ok(args[0].immediate());
2314        }
2315
2316        #[derive(Copy, Clone)]
2317        enum Sign {
2318            Unsigned,
2319            Signed,
2320        }
2321        use Sign::*;
2322
2323        enum Style {
2324            Float,
2325            Int(Sign),
2326            Unsupported,
2327        }
2328
2329        let (in_style, in_width) = match in_elem.kind() {
2330            // vectors of pointer-sized integers should've been
2331            // disallowed before here, so this unwrap is safe.
2332            ty::Int(i) => (
2333                Style::Int(Signed),
2334                i.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
2335            ),
2336            ty::Uint(u) => (
2337                Style::Int(Unsigned),
2338                u.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
2339            ),
2340            ty::Float(f) => (Style::Float, f.bit_width()),
2341            _ => (Style::Unsupported, 0),
2342        };
2343        let (out_style, out_width) = match out_elem.kind() {
2344            ty::Int(i) => (
2345                Style::Int(Signed),
2346                i.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
2347            ),
2348            ty::Uint(u) => (
2349                Style::Int(Unsigned),
2350                u.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
2351            ),
2352            ty::Float(f) => (Style::Float, f.bit_width()),
2353            _ => (Style::Unsupported, 0),
2354        };
2355
2356        match (in_style, out_style) {
2357            (Style::Int(sign), Style::Int(_)) => {
2358                return Ok(match in_width.cmp(&out_width) {
2359                    Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
2360                    Ordering::Equal => args[0].immediate(),
2361                    Ordering::Less => match sign {
2362                        Sign::Signed => bx.sext(args[0].immediate(), llret_ty),
2363                        Sign::Unsigned => bx.zext(args[0].immediate(), llret_ty),
2364                    },
2365                });
2366            }
2367            (Style::Int(Sign::Signed), Style::Float) => {
2368                return Ok(bx.sitofp(args[0].immediate(), llret_ty));
2369            }
2370            (Style::Int(Sign::Unsigned), Style::Float) => {
2371                return Ok(bx.uitofp(args[0].immediate(), llret_ty));
2372            }
2373            (Style::Float, Style::Int(sign)) => {
2374                return Ok(match (sign, name == sym::simd_as) {
2375                    (Sign::Unsigned, false) => bx.fptoui(args[0].immediate(), llret_ty),
2376                    (Sign::Signed, false) => bx.fptosi(args[0].immediate(), llret_ty),
2377                    (_, true) => bx.cast_float_to_int(
2378                        matches!(sign, Sign::Signed),
2379                        args[0].immediate(),
2380                        llret_ty,
2381                    ),
2382                });
2383            }
2384            (Style::Float, Style::Float) => {
2385                return Ok(match in_width.cmp(&out_width) {
2386                    Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
2387                    Ordering::Equal => args[0].immediate(),
2388                    Ordering::Less => bx.fpext(args[0].immediate(), llret_ty),
2389                });
2390            }
2391            _ => { /* Unsupported. Fallthrough. */ }
2392        }
2393        return_error!(InvalidMonomorphization::UnsupportedCast {
2394            span,
2395            name,
2396            in_ty,
2397            in_elem,
2398            ret_ty,
2399            out_elem
2400        });
2401    }
2402    macro_rules! arith_binary {
2403        ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
2404            $(if name == sym::$name {
2405                match in_elem.kind() {
2406                    $($(ty::$p(_))|* => {
2407                        return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
2408                    })*
2409                    _ => {},
2410                }
2411                return_error!(
2412                    InvalidMonomorphization::UnsupportedOperation { span, name, in_ty, in_elem }
2413                );
2414            })*
2415        }
2416    }
2417    arith_binary! {
2418        simd_add: Uint, Int => add, Float => fadd;
2419        simd_sub: Uint, Int => sub, Float => fsub;
2420        simd_mul: Uint, Int => mul, Float => fmul;
2421        simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
2422        simd_rem: Uint => urem, Int => srem, Float => frem;
2423        simd_shl: Uint, Int => shl;
2424        simd_shr: Uint => lshr, Int => ashr;
2425        simd_and: Uint, Int => and;
2426        simd_or: Uint, Int => or;
2427        simd_xor: Uint, Int => xor;
2428        simd_fmax: Float => maxnum;
2429        simd_fmin: Float => minnum;
2430
2431    }
2432    macro_rules! arith_unary {
2433        ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
2434            $(if name == sym::$name {
2435                match in_elem.kind() {
2436                    $($(ty::$p(_))|* => {
2437                        return Ok(bx.$call(args[0].immediate()))
2438                    })*
2439                    _ => {},
2440                }
2441                return_error!(
2442                    InvalidMonomorphization::UnsupportedOperation { span, name, in_ty, in_elem }
2443                );
2444            })*
2445        }
2446    }
2447    arith_unary! {
2448        simd_neg: Int => neg, Float => fneg;
2449    }
2450
2451    // Unary integer intrinsics
2452    if matches!(
2453        name,
2454        sym::simd_bswap
2455            | sym::simd_bitreverse
2456            | sym::simd_ctlz
2457            | sym::simd_ctpop
2458            | sym::simd_cttz
2459            | sym::simd_funnel_shl
2460            | sym::simd_funnel_shr
2461    ) {
2462        let vec_ty = bx.cx.type_vector(
2463            match *in_elem.kind() {
2464                ty::Int(i) => bx.cx.type_int_from_ty(i),
2465                ty::Uint(i) => bx.cx.type_uint_from_ty(i),
2466                _ => return_error!(InvalidMonomorphization::UnsupportedOperation {
2467                    span,
2468                    name,
2469                    in_ty,
2470                    in_elem
2471                }),
2472            },
2473            in_len as u64,
2474        );
2475        let llvm_intrinsic = match name {
2476            sym::simd_bswap => "llvm.bswap",
2477            sym::simd_bitreverse => "llvm.bitreverse",
2478            sym::simd_ctlz => "llvm.ctlz",
2479            sym::simd_ctpop => "llvm.ctpop",
2480            sym::simd_cttz => "llvm.cttz",
2481            sym::simd_funnel_shl => "llvm.fshl",
2482            sym::simd_funnel_shr => "llvm.fshr",
2483            _ => unreachable!(),
2484        };
2485        let int_size = in_elem.int_size_and_signed(bx.tcx()).0.bits();
2486
2487        return match name {
2488            // byte swap is no-op for i8/u8
2489            sym::simd_bswap if int_size == 8 => Ok(args[0].immediate()),
2490            sym::simd_ctlz | sym::simd_cttz => {
2491                // for the (int, i1 immediate) pair, the second arg adds `(0, true) => poison`
2492                let dont_poison_on_zero = bx.const_int(bx.type_i1(), 0);
2493                Ok(bx.call_intrinsic(
2494                    llvm_intrinsic,
2495                    &[vec_ty],
2496                    &[args[0].immediate(), dont_poison_on_zero],
2497                ))
2498            }
2499            sym::simd_bswap | sym::simd_bitreverse | sym::simd_ctpop => {
2500                // simple unary argument cases
2501                Ok(bx.call_intrinsic(llvm_intrinsic, &[vec_ty], &[args[0].immediate()]))
2502            }
2503            sym::simd_funnel_shl | sym::simd_funnel_shr => Ok(bx.call_intrinsic(
2504                llvm_intrinsic,
2505                &[vec_ty],
2506                &[args[0].immediate(), args[1].immediate(), args[2].immediate()],
2507            )),
2508            _ => unreachable!(),
2509        };
2510    }
2511
2512    if name == sym::simd_arith_offset {
2513        // This also checks that the first operand is a ptr type.
2514        let pointee = in_elem.builtin_deref(true).unwrap_or_else(|| {
2515            span_bug!(span, "must be called with a vector of pointer types as first argument")
2516        });
2517        let layout = bx.layout_of(pointee);
2518        let ptrs = args[0].immediate();
2519        // The second argument must be a ptr-sized integer.
2520        // (We don't care about the signedness, this is wrapping anyway.)
2521        let (_offsets_len, offsets_elem) = args[1].layout.ty.simd_size_and_type(bx.tcx());
2522        if !matches!(offsets_elem.kind(), ty::Int(ty::IntTy::Isize) | ty::Uint(ty::UintTy::Usize)) {
2523            span_bug!(
2524                span,
2525                "must be called with a vector of pointer-sized integers as second argument"
2526            );
2527        }
2528        let offsets = args[1].immediate();
2529
2530        return Ok(bx.gep(bx.backend_type(layout), ptrs, &[offsets]));
2531    }
2532
2533    if name == sym::simd_saturating_add || name == sym::simd_saturating_sub {
2534        let lhs = args[0].immediate();
2535        let rhs = args[1].immediate();
2536        let is_add = name == sym::simd_saturating_add;
2537        let (signed, elem_ty) = match *in_elem.kind() {
2538            ty::Int(i) => (true, bx.cx.type_int_from_ty(i)),
2539            ty::Uint(i) => (false, bx.cx.type_uint_from_ty(i)),
2540            _ => {
2541                return_error!(InvalidMonomorphization::ExpectedVectorElementType {
2542                    span,
2543                    name,
2544                    expected_element: args[0].layout.ty.simd_size_and_type(bx.tcx()).1,
2545                    vector_type: args[0].layout.ty
2546                });
2547            }
2548        };
2549        let llvm_intrinsic = format!(
2550            "llvm.{}{}.sat",
2551            if signed { 's' } else { 'u' },
2552            if is_add { "add" } else { "sub" },
2553        );
2554        let vec_ty = bx.cx.type_vector(elem_ty, in_len as u64);
2555
2556        return Ok(bx.call_intrinsic(llvm_intrinsic, &[vec_ty], &[lhs, rhs]));
2557    }
2558
2559    span_bug!(span, "unknown SIMD intrinsic");
2560}