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