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