Skip to main content

rustc_codegen_llvm/
intrinsic.rs

1use std::cmp::Ordering;
2use std::ffi::c_uint;
3use std::{assert_matches, iter, ptr};
4
5use rustc_abi::{
6    AddressSpace, Align, BackendRepr, CVariadicStatus, Float, HasDataLayout, Integer,
7    NumScalableVectors, Primitive, Size, WrappingRange,
8};
9use rustc_codegen_ssa::base::{compare_simd_types, wants_msvc_seh, wants_wasm_eh};
10use rustc_codegen_ssa::common::{IntPredicate, TypeKind};
11use rustc_codegen_ssa::errors::{ExpectedPointerMutability, InvalidMonomorphization};
12use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
13use rustc_codegen_ssa::mir::place::{PlaceRef, PlaceValue};
14use rustc_codegen_ssa::traits::*;
15use rustc_hir as hir;
16use rustc_hir::def_id::LOCAL_CRATE;
17use rustc_hir::find_attr;
18use rustc_middle::mir::BinOp;
19use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt, HasTypingEnv, LayoutOf};
20use rustc_middle::ty::offload_meta::OffloadMetadata;
21use rustc_middle::ty::{
22    self, GenericArgsRef, Instance, SimdAlign, Ty, TyCtxt, TypingEnv, Unnormalized,
23};
24use rustc_middle::{bug, span_bug};
25use rustc_session::config::CrateType;
26use rustc_session::errors::feature_err;
27use rustc_session::lint::builtin::DEPRECATED_LLVM_INTRINSIC;
28use rustc_span::{Span, Symbol, sym};
29use rustc_symbol_mangling::{mangle_internal_symbol, symbol_name_for_instance_in_crate};
30use rustc_target::callconv::PassMode;
31use rustc_target::spec::{Arch, Os};
32use tracing::debug;
33
34use crate::abi::FnAbiLlvmExt;
35use crate::builder::Builder;
36use crate::builder::autodiff::{adjust_activity_to_abi, generate_enzyme_call};
37use crate::builder::gpu_offload::{
38    OffloadKernelDims, gen_call_handling, gen_define_handling, register_offload,
39};
40use crate::context::CodegenCx;
41use crate::declare::declare_raw_fn;
42use crate::errors::{
43    AutoDiffWithoutEnable, AutoDiffWithoutLto, IntrinsicSignatureMismatch, IntrinsicWrongArch,
44    OffloadWithoutEnable, OffloadWithoutFatLTO, UnknownIntrinsic,
45};
46use crate::llvm::{self, Type, Value};
47use crate::type_of::LayoutLlvmExt;
48use crate::va_arg::emit_va_arg;
49
50fn call_simple_intrinsic<'ll, 'tcx>(
51    bx: &mut Builder<'_, 'll, 'tcx>,
52    name: Symbol,
53    args: &[OperandRef<'tcx, &'ll Value>],
54) -> Option<&'ll Value> {
55    let (base_name, type_params): (&'static str, &[&'ll Type]) = match name {
56        sym::sqrtf16 => ("llvm.sqrt", &[bx.type_f16()]),
57        sym::sqrtf32 => ("llvm.sqrt", &[bx.type_f32()]),
58        sym::sqrtf64 => ("llvm.sqrt", &[bx.type_f64()]),
59        sym::sqrtf128 => ("llvm.sqrt", &[bx.type_f128()]),
60
61        sym::powif16 => ("llvm.powi", &[bx.type_f16(), bx.type_i32()]),
62        sym::powif32 => ("llvm.powi", &[bx.type_f32(), bx.type_i32()]),
63        sym::powif64 => ("llvm.powi", &[bx.type_f64(), bx.type_i32()]),
64        sym::powif128 => ("llvm.powi", &[bx.type_f128(), bx.type_i32()]),
65
66        sym::sinf16 => ("llvm.sin", &[bx.type_f16()]),
67        sym::sinf32 => ("llvm.sin", &[bx.type_f32()]),
68        sym::sinf64 => ("llvm.sin", &[bx.type_f64()]),
69        sym::sinf128 => ("llvm.sin", &[bx.type_f128()]),
70
71        sym::cosf16 => ("llvm.cos", &[bx.type_f16()]),
72        sym::cosf32 => ("llvm.cos", &[bx.type_f32()]),
73        sym::cosf64 => ("llvm.cos", &[bx.type_f64()]),
74        sym::cosf128 => ("llvm.cos", &[bx.type_f128()]),
75
76        sym::powf16 => ("llvm.pow", &[bx.type_f16()]),
77        sym::powf32 => ("llvm.pow", &[bx.type_f32()]),
78        sym::powf64 => ("llvm.pow", &[bx.type_f64()]),
79        sym::powf128 => ("llvm.pow", &[bx.type_f128()]),
80
81        sym::expf16 => ("llvm.exp", &[bx.type_f16()]),
82        sym::expf32 => ("llvm.exp", &[bx.type_f32()]),
83        sym::expf64 => ("llvm.exp", &[bx.type_f64()]),
84        sym::expf128 => ("llvm.exp", &[bx.type_f128()]),
85
86        sym::exp2f16 => ("llvm.exp2", &[bx.type_f16()]),
87        sym::exp2f32 => ("llvm.exp2", &[bx.type_f32()]),
88        sym::exp2f64 => ("llvm.exp2", &[bx.type_f64()]),
89        sym::exp2f128 => ("llvm.exp2", &[bx.type_f128()]),
90
91        sym::logf16 => ("llvm.log", &[bx.type_f16()]),
92        sym::logf32 => ("llvm.log", &[bx.type_f32()]),
93        sym::logf64 => ("llvm.log", &[bx.type_f64()]),
94        sym::logf128 => ("llvm.log", &[bx.type_f128()]),
95
96        sym::log10f16 => ("llvm.log10", &[bx.type_f16()]),
97        sym::log10f32 => ("llvm.log10", &[bx.type_f32()]),
98        sym::log10f64 => ("llvm.log10", &[bx.type_f64()]),
99        sym::log10f128 => ("llvm.log10", &[bx.type_f128()]),
100
101        sym::log2f16 => ("llvm.log2", &[bx.type_f16()]),
102        sym::log2f32 => ("llvm.log2", &[bx.type_f32()]),
103        sym::log2f64 => ("llvm.log2", &[bx.type_f64()]),
104        sym::log2f128 => ("llvm.log2", &[bx.type_f128()]),
105
106        sym::fmaf16 => ("llvm.fma", &[bx.type_f16()]),
107        sym::fmaf32 => ("llvm.fma", &[bx.type_f32()]),
108        sym::fmaf64 => ("llvm.fma", &[bx.type_f64()]),
109        sym::fmaf128 => ("llvm.fma", &[bx.type_f128()]),
110
111        sym::fmuladdf16 => ("llvm.fmuladd", &[bx.type_f16()]),
112        sym::fmuladdf32 => ("llvm.fmuladd", &[bx.type_f32()]),
113        sym::fmuladdf64 => ("llvm.fmuladd", &[bx.type_f64()]),
114        sym::fmuladdf128 => ("llvm.fmuladd", &[bx.type_f128()]),
115
116        // FIXME: LLVM currently mis-compile those intrinsics, re-enable them
117        // when llvm/llvm-project#{139380,139381,140445} are fixed.
118        //sym::minimumf16 => ("llvm.minimum", &[bx.type_f16()]),
119        //sym::minimumf32 => ("llvm.minimum", &[bx.type_f32()]),
120        //sym::minimumf64 => ("llvm.minimum", &[bx.type_f64()]),
121        //sym::minimumf128 => ("llvm.minimum", &[cx.type_f128()]),
122        //
123        // FIXME: LLVM currently mis-compile those intrinsics, re-enable them
124        // when llvm/llvm-project#{139380,139381,140445} are fixed.
125        //sym::maximumf16 => ("llvm.maximum", &[bx.type_f16()]),
126        //sym::maximumf32 => ("llvm.maximum", &[bx.type_f32()]),
127        //sym::maximumf64 => ("llvm.maximum", &[bx.type_f64()]),
128        //sym::maximumf128 => ("llvm.maximum", &[cx.type_f128()]),
129        //
130        sym::copysignf16 => ("llvm.copysign", &[bx.type_f16()]),
131        sym::copysignf32 => ("llvm.copysign", &[bx.type_f32()]),
132        sym::copysignf64 => ("llvm.copysign", &[bx.type_f64()]),
133        sym::copysignf128 => ("llvm.copysign", &[bx.type_f128()]),
134
135        sym::floorf16 => ("llvm.floor", &[bx.type_f16()]),
136        sym::floorf32 => ("llvm.floor", &[bx.type_f32()]),
137        sym::floorf64 => ("llvm.floor", &[bx.type_f64()]),
138        sym::floorf128 => ("llvm.floor", &[bx.type_f128()]),
139
140        sym::ceilf16 => ("llvm.ceil", &[bx.type_f16()]),
141        sym::ceilf32 => ("llvm.ceil", &[bx.type_f32()]),
142        sym::ceilf64 => ("llvm.ceil", &[bx.type_f64()]),
143        sym::ceilf128 => ("llvm.ceil", &[bx.type_f128()]),
144
145        sym::truncf16 => ("llvm.trunc", &[bx.type_f16()]),
146        sym::truncf32 => ("llvm.trunc", &[bx.type_f32()]),
147        sym::truncf64 => ("llvm.trunc", &[bx.type_f64()]),
148        sym::truncf128 => ("llvm.trunc", &[bx.type_f128()]),
149
150        // We could use any of `rint`, `nearbyint`, or `roundeven`
151        // for this -- they are all identical in semantics when
152        // assuming the default FP environment.
153        // `rint` is what we used for $forever.
154        sym::round_ties_even_f16 => ("llvm.rint", &[bx.type_f16()]),
155        sym::round_ties_even_f32 => ("llvm.rint", &[bx.type_f32()]),
156        sym::round_ties_even_f64 => ("llvm.rint", &[bx.type_f64()]),
157        sym::round_ties_even_f128 => ("llvm.rint", &[bx.type_f128()]),
158
159        sym::roundf16 => ("llvm.round", &[bx.type_f16()]),
160        sym::roundf32 => ("llvm.round", &[bx.type_f32()]),
161        sym::roundf64 => ("llvm.round", &[bx.type_f64()]),
162        sym::roundf128 => ("llvm.round", &[bx.type_f128()]),
163
164        _ => return None,
165    };
166    Some(bx.call_intrinsic(
167        base_name,
168        type_params,
169        &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
170    ))
171}
172
173impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
174    fn codegen_intrinsic_call(
175        &mut self,
176        instance: ty::Instance<'tcx>,
177        args: &[OperandRef<'tcx, &'ll Value>],
178        result: PlaceRef<'tcx, &'ll Value>,
179        span: Span,
180    ) -> Result<(), ty::Instance<'tcx>> {
181        let tcx = self.tcx;
182        let llvm_version = crate::llvm_util::get_version();
183
184        let name = tcx.item_name(instance.def_id());
185        let fn_args = instance.args;
186
187        let simple = call_simple_intrinsic(self, name, args);
188        let llval = match name {
189            _ if simple.is_some() => simple.unwrap(),
190            sym::minimum_number_nsz_f16
191            | sym::minimum_number_nsz_f32
192            | sym::minimum_number_nsz_f64
193            | sym::minimum_number_nsz_f128
194            | sym::maximum_number_nsz_f16
195            | sym::maximum_number_nsz_f32
196            | sym::maximum_number_nsz_f64
197            | sym::maximum_number_nsz_f128
198                // Need at least LLVM 22 for `min/maximumnum` to not crash LLVM.
199                if llvm_version >= (22, 0, 0) =>
200            {
201                let intrinsic_name = if name.as_str().starts_with("min") {
202                    "llvm.minimumnum"
203                } else {
204                    "llvm.maximumnum"
205                };
206                let call = self.call_intrinsic(
207                    intrinsic_name,
208                    &[args[0].layout.immediate_llvm_type(self.cx)],
209                    &[args[0].immediate(), args[1].immediate()],
210                );
211                // `nsz` on minimumnum/maximumnum is special: its only effect is to make
212                // signed-zero ordering non-deterministic.
213                unsafe { llvm::LLVMRustSetNoSignedZeros(call) };
214                call
215            }
216            sym::ptr_mask => {
217                let ptr = args[0].immediate();
218                self.call_intrinsic(
219                    "llvm.ptrmask",
220                    &[self.val_ty(ptr), self.type_isize()],
221                    &[ptr, args[1].immediate()],
222                )
223            }
224            sym::autodiff => {
225                codegen_autodiff(self, tcx, instance, args, result);
226                return Ok(());
227            }
228            sym::offload => {
229                if tcx.sess.opts.unstable_opts.offload.is_empty() {
230                    let _ = tcx.dcx().emit_almost_fatal(OffloadWithoutEnable);
231                }
232
233                if tcx.sess.lto() != rustc_session::config::Lto::Fat {
234                    let _ = tcx.dcx().emit_almost_fatal(OffloadWithoutFatLTO);
235                }
236
237                codegen_offload(self, tcx, instance, args);
238                return Ok(());
239            }
240            sym::is_val_statically_known => {
241                if let OperandValue::Immediate(imm) = args[0].val {
242                    self.call_intrinsic(
243                        "llvm.is.constant",
244                        &[args[0].layout.immediate_llvm_type(self.cx)],
245                        &[imm],
246                    )
247                } else {
248                    self.const_bool(false)
249                }
250            }
251            sym::select_unpredictable => {
252                let cond = args[0].immediate();
253                match (&args[1].layout, &args[2].layout) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_eq!(args[1].layout, args[2].layout);
254                let select = |bx: &mut Self, true_val, false_val| {
255                    let result = bx.select(cond, true_val, false_val);
256                    bx.set_unpredictable(&result);
257                    result
258                };
259                match (args[1].val, args[2].val) {
260                    (OperandValue::Ref(true_val), OperandValue::Ref(false_val)) => {
261                        if !true_val.llextra.is_none() {
    ::core::panicking::panic("assertion failed: true_val.llextra.is_none()")
};assert!(true_val.llextra.is_none());
262                        if !false_val.llextra.is_none() {
    ::core::panicking::panic("assertion failed: false_val.llextra.is_none()")
};assert!(false_val.llextra.is_none());
263                        match (&true_val.align, &false_val.align) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_eq!(true_val.align, false_val.align);
264                        let ptr = select(self, true_val.llval, false_val.llval);
265                        let selected =
266                            OperandValue::Ref(PlaceValue::new_sized(ptr, true_val.align));
267                        selected.store(self, result);
268                        return Ok(());
269                    }
270                    (OperandValue::Immediate(_), OperandValue::Immediate(_))
271                    | (OperandValue::Pair(_, _), OperandValue::Pair(_, _)) => {
272                        let true_val = args[1].immediate_or_packed_pair(self);
273                        let false_val = args[2].immediate_or_packed_pair(self);
274                        select(self, true_val, false_val)
275                    }
276                    (OperandValue::ZeroSized, OperandValue::ZeroSized) => return Ok(()),
277                    _ => ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("Incompatible OperandValue for select_unpredictable"))span_bug!(span, "Incompatible OperandValue for select_unpredictable"),
278                }
279            }
280            sym::catch_unwind => {
281                catch_unwind_intrinsic(
282                    self,
283                    args[0].immediate(),
284                    args[1].immediate(),
285                    args[2].immediate(),
286                    result,
287                );
288                return Ok(());
289            }
290            sym::breakpoint => self.call_intrinsic("llvm.debugtrap", &[], &[]),
291            sym::va_arg => {
292                let target = &self.cx.tcx.sess.target;
293                let stability = target.supports_c_variadic_definitions();
294                if let CVariadicStatus::Unstable { feature } = stability
295                    && !self.tcx.features().enabled(feature)
296                {
297                    let msg =
298                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("C-variadic function definitions on this target are unstable"))
    })format!("C-variadic function definitions on this target are unstable");
299                    feature_err(&*self.sess(), feature, span, msg).emit();
300                }
301
302                let BackendRepr::Scalar(scalar) = result.layout.backend_repr else {
303                    ::rustc_middle::util::bug::bug_fmt(format_args!("the va_arg intrinsic does not support non-scalar types"))bug!("the va_arg intrinsic does not support non-scalar types")
304                };
305
306                // We reject types that would never be passed as varargs in C because
307                // they get promoted to a larger type, specifically integers smaller than
308                // c_int and float type smaller than c_double.
309                match scalar.primitive() {
310                    Primitive::Pointer(_) => {
311                        // Pointers are always OK.
312                    }
313                    Primitive::Int(Integer::I128, _) => {
314                        // FIXME: maybe we should support these? At least on 32-bit powerpc
315                        // the logic in LLVM does not handle i128 correctly though.
316                        ::rustc_middle::util::bug::bug_fmt(format_args!("the va_arg intrinsic does not support `i128`/`u128`"))bug!("the va_arg intrinsic does not support `i128`/`u128`")
317                    }
318                    Primitive::Int(..) => {
319                        let int_width = self.cx().size_of(result.layout.ty).bits();
320                        let target_c_int_width = self.cx().sess().target.options.c_int_width;
321                        if int_width < u64::from(target_c_int_width) {
322                            // Smaller integer types are automatically promototed and `va_arg`
323                            // should not be called on them.
324                            ::rustc_middle::util::bug::bug_fmt(format_args!("va_arg got i{0} but needs at least c_int (an i{1})",
        int_width, target_c_int_width));bug!(
325                                "va_arg got i{} but needs at least c_int (an i{})",
326                                int_width,
327                                target_c_int_width
328                            );
329                        }
330                    }
331                    Primitive::Float(Float::F16) => {
332                        ::rustc_middle::util::bug::bug_fmt(format_args!("the va_arg intrinsic does not support `f16`"))bug!("the va_arg intrinsic does not support `f16`")
333                    }
334                    Primitive::Float(Float::F32) => {
335                        // c_double is actually f32 on avr.
336                        if self.cx().sess().target.arch != Arch::Avr {
337                            ::rustc_middle::util::bug::bug_fmt(format_args!("the va_arg intrinsic does not support `f32` on this target"))bug!("the va_arg intrinsic does not support `f32` on this target")
338                        }
339                    }
340                    Primitive::Float(Float::F64) => {
341                        // 64-bit floats are always OK.
342                    }
343                    Primitive::Float(Float::F128) => {
344                        // FIXME(f128) figure out whether we should support this.
345                        ::rustc_middle::util::bug::bug_fmt(format_args!("the va_arg intrinsic does not support `f128`"))bug!("the va_arg intrinsic does not support `f128`")
346                    }
347                }
348
349                emit_va_arg(self, args[0], result.layout.ty)
350            }
351
352            sym::volatile_load | sym::unaligned_volatile_load => {
353                let ptr = args[0].immediate();
354                let load = self.volatile_load(result.layout.llvm_type(self), ptr);
355                let align = if name == sym::unaligned_volatile_load {
356                    1
357                } else {
358                    result.layout.align.bytes() as u32
359                };
360                unsafe {
361                    llvm::LLVMSetAlignment(load, align);
362                }
363                if !result.layout.is_zst() {
364                    self.store_to_place(load, result.val);
365                }
366                return Ok(());
367            }
368            sym::volatile_store => {
369                let dst = args[0].deref(self.cx());
370                args[1].val.volatile_store(self, dst);
371                return Ok(());
372            }
373            sym::unaligned_volatile_store => {
374                let dst = args[0].deref(self.cx());
375                args[1].val.unaligned_volatile_store(self, dst);
376                return Ok(());
377            }
378            sym::prefetch_read_data
379            | sym::prefetch_write_data
380            | sym::prefetch_read_instruction
381            | sym::prefetch_write_instruction => {
382                let (rw, cache_type) = match name {
383                    sym::prefetch_read_data => (0, 1),
384                    sym::prefetch_write_data => (1, 1),
385                    sym::prefetch_read_instruction => (0, 0),
386                    sym::prefetch_write_instruction => (1, 0),
387                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
388                };
389                let ptr = args[0].immediate();
390                let locality = fn_args.const_at(1).to_leaf().to_i32();
391                self.call_intrinsic(
392                    "llvm.prefetch",
393                    &[self.val_ty(ptr)],
394                    &[
395                        ptr,
396                        self.const_i32(rw),
397                        self.const_i32(locality),
398                        self.const_i32(cache_type),
399                    ],
400                )
401            }
402            sym::carrying_mul_add => {
403                let (size, signed) = fn_args.type_at(0).int_size_and_signed(self.tcx);
404
405                let wide_llty = self.type_ix(size.bits() * 2);
406                let args = args.as_array().unwrap();
407                let [a, b, c, d] = args.map(|a| self.intcast(a.immediate(), wide_llty, signed));
408
409                let wide = if signed {
410                    let prod = self.unchecked_smul(a, b);
411                    let acc = self.unchecked_sadd(prod, c);
412                    self.unchecked_sadd(acc, d)
413                } else {
414                    let prod = self.unchecked_umul(a, b);
415                    let acc = self.unchecked_uadd(prod, c);
416                    self.unchecked_uadd(acc, d)
417                };
418
419                let narrow_llty = self.type_ix(size.bits());
420                let low = self.trunc(wide, narrow_llty);
421                let bits_const = self.const_uint(wide_llty, size.bits());
422                // No need for ashr when signed; LLVM changes it to lshr anyway.
423                let high = self.lshr(wide, bits_const);
424                // FIXME: could be `trunc nuw`, even for signed.
425                let high = self.trunc(high, narrow_llty);
426
427                let pair_llty = self.type_struct(&[narrow_llty, narrow_llty], false);
428                let pair = self.const_poison(pair_llty);
429                let pair = self.insert_value(pair, low, 0);
430                let pair = self.insert_value(pair, high, 1);
431                pair
432            }
433
434            // FIXME move into the branch below when LLVM 22 is the lowest version we support.
435            sym::carryless_mul if llvm_version >= (22, 0, 0) => {
436                let ty = args[0].layout.ty;
437                if !ty.is_integral() {
438                    tcx.dcx().emit_err(InvalidMonomorphization::BasicIntegerType {
439                        span,
440                        name,
441                        ty,
442                    });
443                    return Ok(());
444                }
445                let (size, _) = ty.int_size_and_signed(self.tcx);
446                let width = size.bits();
447                let llty = self.type_ix(width);
448
449                let lhs = args[0].immediate();
450                let rhs = args[1].immediate();
451                self.call_intrinsic("llvm.clmul", &[llty], &[lhs, rhs])
452            }
453
454            sym::ctlz
455            | sym::ctlz_nonzero
456            | sym::cttz
457            | sym::cttz_nonzero
458            | sym::ctpop
459            | sym::bswap
460            | sym::bitreverse
461            | sym::saturating_add
462            | sym::saturating_sub
463            | sym::unchecked_funnel_shl
464            | sym::unchecked_funnel_shr => {
465                let ty = args[0].layout.ty;
466                if !ty.is_integral() {
467                    tcx.dcx().emit_err(InvalidMonomorphization::BasicIntegerType {
468                        span,
469                        name,
470                        ty,
471                    });
472                    return Ok(());
473                }
474                let (size, signed) = ty.int_size_and_signed(self.tcx);
475                let width = size.bits();
476                let llty = self.type_ix(width);
477                match name {
478                    sym::ctlz | sym::ctlz_nonzero | sym::cttz | sym::cttz_nonzero => {
479                        let y =
480                            self.const_bool(name == sym::ctlz_nonzero || name == sym::cttz_nonzero);
481                        let llvm_name = if name == sym::ctlz || name == sym::ctlz_nonzero {
482                            "llvm.ctlz"
483                        } else {
484                            "llvm.cttz"
485                        };
486                        let ret =
487                            self.call_intrinsic(llvm_name, &[llty], &[args[0].immediate(), y]);
488                        self.intcast(ret, result.layout.llvm_type(self), false)
489                    }
490                    sym::ctpop => {
491                        let ret =
492                            self.call_intrinsic("llvm.ctpop", &[llty], &[args[0].immediate()]);
493                        self.intcast(ret, result.layout.llvm_type(self), false)
494                    }
495                    sym::bswap => {
496                        if width == 8 {
497                            args[0].immediate() // byte swap a u8/i8 is just a no-op
498                        } else {
499                            self.call_intrinsic("llvm.bswap", &[llty], &[args[0].immediate()])
500                        }
501                    }
502                    sym::bitreverse => {
503                        self.call_intrinsic("llvm.bitreverse", &[llty], &[args[0].immediate()])
504                    }
505                    sym::unchecked_funnel_shl | sym::unchecked_funnel_shr => {
506                        let is_left = name == sym::unchecked_funnel_shl;
507                        let lhs = args[0].immediate();
508                        let rhs = args[1].immediate();
509                        let raw_shift = args[2].immediate();
510                        let llvm_name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("llvm.fsh{0}",
                if is_left { 'l' } else { 'r' }))
    })format!("llvm.fsh{}", if is_left { 'l' } else { 'r' });
511
512                        // llvm expects shift to be the same type as the values, but rust
513                        // always uses `u32`.
514                        let raw_shift = self.intcast(raw_shift, self.val_ty(lhs), false);
515
516                        self.call_intrinsic(llvm_name, &[llty], &[lhs, rhs, raw_shift])
517                    }
518                    sym::saturating_add | sym::saturating_sub => {
519                        let is_add = name == sym::saturating_add;
520                        let lhs = args[0].immediate();
521                        let rhs = args[1].immediate();
522                        let llvm_name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("llvm.{0}{1}.sat",
                if signed { 's' } else { 'u' },
                if is_add { "add" } else { "sub" }))
    })format!(
523                            "llvm.{}{}.sat",
524                            if signed { 's' } else { 'u' },
525                            if is_add { "add" } else { "sub" },
526                        );
527                        self.call_intrinsic(llvm_name, &[llty], &[lhs, rhs])
528                    }
529                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
530                }
531            }
532
533            sym::fabs => {
534                let ty = args[0].layout.ty;
535                let ty::Float(f) = ty.kind() else {
536                    ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("the `fabs` intrinsic requires a floating-point argument, got {0:?}",
        ty));span_bug!(span, "the `fabs` intrinsic requires a floating-point argument, got {:?}", ty);
537                };
538                let llty = self.type_float_from_ty(*f);
539                let llvm_name = "llvm.fabs";
540                self.call_intrinsic(
541                    llvm_name,
542                    &[llty],
543                    &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
544                )
545            }
546
547            sym::raw_eq => {
548                use BackendRepr::*;
549                let tp_ty = fn_args.type_at(0);
550                let layout = self.layout_of(tp_ty).layout;
551                let use_integer_compare = match layout.backend_repr() {
552                    Scalar(_) | ScalarPair(_, _) => true,
553                    SimdVector { .. } => false,
554                    SimdScalableVector { .. } => {
555                        tcx.dcx().emit_err(InvalidMonomorphization::NonScalableType {
556                            span,
557                            name: sym::raw_eq,
558                            ty: tp_ty,
559                        });
560                        return Ok(());
561                    }
562                    Memory { .. } => {
563                        // For rusty ABIs, small aggregates are actually passed
564                        // as `RegKind::Integer` (see `FnAbi::adjust_for_abi`),
565                        // so we re-use that same threshold here.
566                        layout.size() <= self.data_layout().pointer_size() * 2
567                    }
568                };
569
570                let a = args[0].immediate();
571                let b = args[1].immediate();
572                if layout.size().bytes() == 0 {
573                    self.const_bool(true)
574                } else if use_integer_compare {
575                    let integer_ty = self.type_ix(layout.size().bits());
576                    let a_val = self.load(integer_ty, a, layout.align().abi);
577                    let b_val = self.load(integer_ty, b, layout.align().abi);
578                    self.icmp(IntPredicate::IntEQ, a_val, b_val)
579                } else {
580                    let n = self.const_usize(layout.size().bytes());
581                    let cmp = self.call_intrinsic("memcmp", &[], &[a, b, n]);
582                    self.icmp(IntPredicate::IntEQ, cmp, self.const_int(self.type_int(), 0))
583                }
584            }
585
586            sym::compare_bytes => {
587                // Here we assume that the `memcmp` provided by the target is a NOP for size 0.
588                let cmp = self.call_intrinsic(
589                    "memcmp",
590                    &[],
591                    &[args[0].immediate(), args[1].immediate(), args[2].immediate()],
592                );
593                // Some targets have `memcmp` returning `i16`, but the intrinsic is always `i32`.
594                self.sext(cmp, self.type_ix(32))
595            }
596
597            sym::black_box => {
598                args[0].val.store(self, result);
599                let result_val_span = [result.val.llval];
600                // We need to "use" the argument in some way LLVM can't introspect, and on
601                // targets that support it we can typically leverage inline assembly to do
602                // this. LLVM's interpretation of inline assembly is that it's, well, a black
603                // box. This isn't the greatest implementation since it probably deoptimizes
604                // more than we want, but it's so far good enough.
605                //
606                // For zero-sized types, the location pointed to by the result may be
607                // uninitialized. Do not "use" the result in this case; instead just clobber
608                // the memory.
609                let (constraint, inputs): (&str, &[_]) = if result.layout.is_zst() {
610                    ("~{memory}", &[])
611                } else {
612                    ("r,~{memory}", &result_val_span)
613                };
614                crate::asm::inline_asm_call(
615                    self,
616                    "",
617                    constraint,
618                    inputs,
619                    self.type_void(),
620                    &[],
621                    true,
622                    false,
623                    llvm::AsmDialect::Att,
624                    &[span],
625                    false,
626                    None,
627                    None,
628                )
629                .unwrap_or_else(|| ::rustc_middle::util::bug::bug_fmt(format_args!("failed to generate inline asm call for `black_box`"))bug!("failed to generate inline asm call for `black_box`"));
630
631                // We have copied the value to `result` already.
632                return Ok(());
633            }
634
635            sym::gpu_launch_sized_workgroup_mem => {
636                // Generate an anonymous global per call, with these properties:
637                // 1. The global is in the address space for workgroup memory
638                // 2. It is an `external` global
639                // 3. It is correctly aligned for the pointee `T`
640                // All instances of extern addrspace(gpu_workgroup) globals are merged in the LLVM backend.
641                // The name is irrelevant.
642                // See https://docs.nvidia.com/cuda/cuda-c-programming-guide/#shared
643                let name = if llvm_version < (23, 0, 0) && tcx.sess.target.arch == Arch::Nvptx64 {
644                    // The auto-assigned name for extern shared globals in the nvptx backend does
645                    // not compile in ptxas. Workaround this issue by assigning a name.
646                    // Fixed in LLVM 23.
647                    "gpu_launch_sized_workgroup_mem"
648                } else {
649                    ""
650                };
651                let global = self.declare_global_in_addrspace(
652                    name,
653                    self.type_array(self.type_i8(), 0),
654                    AddressSpace::GPU_WORKGROUP,
655                );
656                let ty::RawPtr(inner_ty, _) = result.layout.ty.kind() else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
657                // The alignment of the global is used to specify the *minimum* alignment that
658                // must be obeyed by the GPU runtime.
659                // When multiple of these global variables are used by a kernel, the maximum alignment is taken.
660                // See https://github.com/llvm/llvm-project/blob/a271d07488a85ce677674bbe8101b10efff58c95/llvm/lib/Target/AMDGPU/AMDGPULowerModuleLDSPass.cpp#L821
661                let alignment = self.align_of(*inner_ty).bytes() as u32;
662                unsafe {
663                    // FIXME Workaround the above issue by taking maximum alignment if the global existed
664                    if tcx.sess.target.arch == Arch::Nvptx64 {
665                        if alignment > llvm::LLVMGetAlignment(global) {
666                            llvm::LLVMSetAlignment(global, alignment);
667                        }
668                    } else {
669                        llvm::LLVMSetAlignment(global, alignment);
670                    }
671                }
672                self.cx().const_pointercast(global, self.type_ptr())
673            }
674
675            sym::amdgpu_dispatch_ptr => {
676                let val = self.call_intrinsic("llvm.amdgcn.dispatch.ptr", &[], &[]);
677                // Relying on `LLVMBuildPointerCast` to produce an addrspacecast
678                self.pointercast(val, self.type_ptr())
679            }
680
681            sym::sve_tuple_create2 => {
682                {
    match self.layout_of(fn_args.type_at(0)).backend_repr {
        BackendRepr::SimdScalableVector {
            number_of_vectors: NumScalableVectors(1), .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "BackendRepr::SimdScalableVector\n{ number_of_vectors: NumScalableVectors(1), .. }",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
683                    self.layout_of(fn_args.type_at(0)).backend_repr,
684                    BackendRepr::SimdScalableVector {
685                        number_of_vectors: NumScalableVectors(1),
686                        ..
687                    }
688                );
689                let tuple_ty = self.layout_of(fn_args.type_at(1));
690                {
    match tuple_ty.backend_repr {
        BackendRepr::SimdScalableVector {
            number_of_vectors: NumScalableVectors(2), .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "BackendRepr::SimdScalableVector\n{ number_of_vectors: NumScalableVectors(2), .. }",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
691                    tuple_ty.backend_repr,
692                    BackendRepr::SimdScalableVector {
693                        number_of_vectors: NumScalableVectors(2),
694                        ..
695                    }
696                );
697                let ret = self.const_poison(self.backend_type(tuple_ty));
698                let ret = self.insert_value(ret, args[0].immediate(), 0);
699                self.insert_value(ret, args[1].immediate(), 1)
700            }
701
702            sym::sve_tuple_create3 => {
703                {
    match self.layout_of(fn_args.type_at(0)).backend_repr {
        BackendRepr::SimdScalableVector {
            number_of_vectors: NumScalableVectors(1), .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "BackendRepr::SimdScalableVector\n{ number_of_vectors: NumScalableVectors(1), .. }",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
704                    self.layout_of(fn_args.type_at(0)).backend_repr,
705                    BackendRepr::SimdScalableVector {
706                        number_of_vectors: NumScalableVectors(1),
707                        ..
708                    }
709                );
710                let tuple_ty = self.layout_of(fn_args.type_at(1));
711                {
    match tuple_ty.backend_repr {
        BackendRepr::SimdScalableVector {
            number_of_vectors: NumScalableVectors(3), .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "BackendRepr::SimdScalableVector\n{ number_of_vectors: NumScalableVectors(3), .. }",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
712                    tuple_ty.backend_repr,
713                    BackendRepr::SimdScalableVector {
714                        number_of_vectors: NumScalableVectors(3),
715                        ..
716                    }
717                );
718                let ret = self.const_poison(self.backend_type(tuple_ty));
719                let ret = self.insert_value(ret, args[0].immediate(), 0);
720                let ret = self.insert_value(ret, args[1].immediate(), 1);
721                self.insert_value(ret, args[2].immediate(), 2)
722            }
723
724            sym::sve_tuple_create4 => {
725                {
    match self.layout_of(fn_args.type_at(0)).backend_repr {
        BackendRepr::SimdScalableVector {
            number_of_vectors: NumScalableVectors(1), .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "BackendRepr::SimdScalableVector\n{ number_of_vectors: NumScalableVectors(1), .. }",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
726                    self.layout_of(fn_args.type_at(0)).backend_repr,
727                    BackendRepr::SimdScalableVector {
728                        number_of_vectors: NumScalableVectors(1),
729                        ..
730                    }
731                );
732                let tuple_ty = self.layout_of(fn_args.type_at(1));
733                {
    match tuple_ty.backend_repr {
        BackendRepr::SimdScalableVector {
            number_of_vectors: NumScalableVectors(4), .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "BackendRepr::SimdScalableVector\n{ number_of_vectors: NumScalableVectors(4), .. }",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
734                    tuple_ty.backend_repr,
735                    BackendRepr::SimdScalableVector {
736                        number_of_vectors: NumScalableVectors(4),
737                        ..
738                    }
739                );
740                let ret = self.const_poison(self.backend_type(tuple_ty));
741                let ret = self.insert_value(ret, args[0].immediate(), 0);
742                let ret = self.insert_value(ret, args[1].immediate(), 1);
743                let ret = self.insert_value(ret, args[2].immediate(), 2);
744                self.insert_value(ret, args[3].immediate(), 3)
745            }
746
747            sym::sve_tuple_get => {
748                {
    match self.layout_of(fn_args.type_at(0)).backend_repr {
        BackendRepr::SimdScalableVector {
            number_of_vectors: NumScalableVectors(2 | 3 | 4 | 5 | 6 | 7 | 8),
            .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "BackendRepr::SimdScalableVector\n{ number_of_vectors: NumScalableVectors(2 | 3 | 4 | 5 | 6 | 7 | 8), .. }",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
749                    self.layout_of(fn_args.type_at(0)).backend_repr,
750                    BackendRepr::SimdScalableVector {
751                        number_of_vectors: NumScalableVectors(2 | 3 | 4 | 5 | 6 | 7 | 8),
752                        ..
753                    }
754                );
755                {
    match self.layout_of(fn_args.type_at(1)).backend_repr {
        BackendRepr::SimdScalableVector {
            number_of_vectors: NumScalableVectors(1), .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "BackendRepr::SimdScalableVector\n{ number_of_vectors: NumScalableVectors(1), .. }",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
756                    self.layout_of(fn_args.type_at(1)).backend_repr,
757                    BackendRepr::SimdScalableVector {
758                        number_of_vectors: NumScalableVectors(1),
759                        ..
760                    }
761                );
762                self.extract_value(
763                    args[0].immediate(),
764                    fn_args.const_at(2).to_leaf().to_i32() as u64,
765                )
766            }
767
768            sym::sve_tuple_set => {
769                {
    match self.layout_of(fn_args.type_at(0)).backend_repr {
        BackendRepr::SimdScalableVector {
            number_of_vectors: NumScalableVectors(2 | 3 | 4 | 5 | 6 | 7 | 8),
            .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "BackendRepr::SimdScalableVector\n{ number_of_vectors: NumScalableVectors(2 | 3 | 4 | 5 | 6 | 7 | 8), .. }",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
770                    self.layout_of(fn_args.type_at(0)).backend_repr,
771                    BackendRepr::SimdScalableVector {
772                        number_of_vectors: NumScalableVectors(2 | 3 | 4 | 5 | 6 | 7 | 8),
773                        ..
774                    }
775                );
776                {
    match self.layout_of(fn_args.type_at(1)).backend_repr {
        BackendRepr::SimdScalableVector {
            number_of_vectors: NumScalableVectors(1), .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "BackendRepr::SimdScalableVector\n{ number_of_vectors: NumScalableVectors(1), .. }",
                ::core::option::Option::None);
        }
    }
};assert_matches!(
777                    self.layout_of(fn_args.type_at(1)).backend_repr,
778                    BackendRepr::SimdScalableVector {
779                        number_of_vectors: NumScalableVectors(1),
780                        ..
781                    }
782                );
783                self.insert_value(
784                    args[0].immediate(),
785                    args[1].immediate(),
786                    fn_args.const_at(2).to_leaf().to_i32() as u64,
787                )
788            }
789
790            _ if name.as_str().starts_with("simd_") => {
791                // Unpack non-power-of-2 #[repr(packed, simd)] arguments.
792                // This gives them the expected layout of a regular #[repr(simd)] vector.
793                let mut loaded_args = Vec::new();
794                for arg in args {
795                    loaded_args.push(
796                        // #[repr(packed, simd)] vectors are passed like arrays (as references,
797                        // with reduced alignment and no padding) rather than as immediates.
798                        // We can use a vector load to fix the layout and turn the argument
799                        // into an immediate.
800                        if arg.layout.ty.is_simd()
801                            && let OperandValue::Ref(place) = arg.val
802                        {
803                            let (size, elem_ty) = arg.layout.ty.simd_size_and_type(self.tcx());
804                            let elem_ll_ty = match elem_ty.kind() {
805                                ty::Float(f) => self.type_float_from_ty(*f),
806                                ty::Int(i) => self.type_int_from_ty(*i),
807                                ty::Uint(u) => self.type_uint_from_ty(*u),
808                                ty::RawPtr(_, _) => self.type_ptr(),
809                                _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
810                            };
811                            let loaded =
812                                self.load_from_place(self.type_vector(elem_ll_ty, size), place);
813                            OperandRef::from_immediate_or_packed_pair(self, loaded, arg.layout)
814                        } else {
815                            *arg
816                        },
817                    );
818                }
819
820                let llret_ty = if result.layout.ty.is_simd()
821                    && let BackendRepr::Memory { .. } = result.layout.backend_repr
822                {
823                    let (size, elem_ty) = result.layout.ty.simd_size_and_type(self.tcx());
824                    let elem_ll_ty = match elem_ty.kind() {
825                        ty::Float(f) => self.type_float_from_ty(*f),
826                        ty::Int(i) => self.type_int_from_ty(*i),
827                        ty::Uint(u) => self.type_uint_from_ty(*u),
828                        ty::RawPtr(_, _) => self.type_ptr(),
829                        _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
830                    };
831                    self.type_vector(elem_ll_ty, size)
832                } else {
833                    result.layout.llvm_type(self)
834                };
835
836                match generic_simd_intrinsic(
837                    self,
838                    name,
839                    fn_args,
840                    &loaded_args,
841                    result.layout.ty,
842                    llret_ty,
843                    span,
844                ) {
845                    Ok(llval) => llval,
846                    // If there was an error, just skip this invocation... we'll abort compilation
847                    // anyway, but we can keep codegen'ing to find more errors.
848                    Err(()) => return Ok(()),
849                }
850            }
851
852            sym::return_address => {
853                match self.sess().target.arch {
854                    // Expand this list as needed
855                    | Arch::Wasm32
856                    | Arch::Wasm64 => {
857                        let ty = self.type_ptr();
858                        self.const_null(ty)
859                    }
860                    _ => {
861                        let ty = self.type_ix(32);
862                        let val = self.const_int(ty, 0);
863
864                        let type_params: &[&'ll Type] = if llvm_version < (23, 0, 0) {
865                            &[]
866                        } else {
867                            &[self.type_ptr()]
868                        };
869
870                        self.call_intrinsic("llvm.returnaddress", type_params, &[val])
871                    }
872                }
873            }
874
875            _ => {
876                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/intrinsic.rs:876",
                        "rustc_codegen_llvm::intrinsic", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/intrinsic.rs"),
                        ::tracing_core::__macro_support::Option::Some(876u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::intrinsic"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("unknown intrinsic \'{0}\' -- falling back to default body",
                                                    name) as &dyn Value))])
            });
    } else { ; }
};debug!("unknown intrinsic '{}' -- falling back to default body", name);
877                // Call the fallback body instead of generating the intrinsic code
878                return Err(ty::Instance::new_raw(instance.def_id(), instance.args));
879            }
880        };
881
882        if result.layout.ty.is_bool() {
883            let val = self.from_immediate(llval);
884            self.store_to_place(val, result.val);
885        } else if !result.layout.ty.is_unit() {
886            self.store_to_place(llval, result.val);
887        }
888        Ok(())
889    }
890
891    fn codegen_llvm_intrinsic_call(
892        &mut self,
893        instance: ty::Instance<'tcx>,
894        args: &[OperandRef<'tcx, Self::Value>],
895        _is_cleanup: bool,
896    ) -> Self::Value {
897        let tcx = self.tcx();
898
899        let fn_ty = instance.ty(tcx, self.typing_env());
900        let fn_sig = match *fn_ty.kind() {
901            ty::FnDef(def_id, args) => tcx.instantiate_bound_regions_with_erased(
902                tcx.fn_sig(def_id).instantiate(tcx, args).skip_norm_wip(),
903            ),
904            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
905        };
906        if !!fn_sig.c_variadic() {
    ::core::panicking::panic("assertion failed: !fn_sig.c_variadic()")
};assert!(!fn_sig.c_variadic());
907
908        let ret_layout = self.layout_of(fn_sig.output());
909        let llreturn_ty = if ret_layout.is_zst() {
910            self.type_void()
911        } else {
912            ret_layout.immediate_llvm_type(self)
913        };
914
915        let mut llargument_tys = Vec::with_capacity(fn_sig.inputs().len());
916        for &arg in fn_sig.inputs() {
917            let arg_layout = self.layout_of(arg);
918            if arg_layout.is_zst() {
919                continue;
920            }
921            llargument_tys.push(arg_layout.immediate_llvm_type(self));
922        }
923
924        let fn_ptr = if let Some(&llfn) = self.intrinsic_instances.borrow().get(&instance) {
925            llfn
926        } else {
927            let sym = tcx.symbol_name(instance).name;
928
929            let llfn = if let Some(llfn) = self.get_declared_value(sym) {
930                llfn
931            } else {
932                intrinsic_fn(self, sym, llreturn_ty, llargument_tys, instance)
933            };
934
935            self.intrinsic_instances.borrow_mut().insert(instance, llfn);
936
937            llfn
938        };
939        let fn_ty = self.get_type_of_global(fn_ptr);
940
941        let mut llargs = ::alloc::vec::Vec::new()vec![];
942
943        for arg in args {
944            match arg.val {
945                OperandValue::ZeroSized => {}
946                OperandValue::Immediate(a) => llargs.push(a),
947                OperandValue::Pair(a, b) => {
948                    llargs.push(a);
949                    llargs.push(b);
950                }
951                OperandValue::Ref(op_place_val) => {
952                    let mut llval = op_place_val.llval;
953                    // We can't use `PlaceRef::load` here because the argument
954                    // may have a type we don't treat as immediate, but the ABI
955                    // used for this call is passing it by-value. In that case,
956                    // the load would just produce `OperandValue::Ref` instead
957                    // of the `OperandValue::Immediate` we need for the call.
958                    llval = self.load(self.backend_type(arg.layout), llval, op_place_val.align);
959                    if let BackendRepr::Scalar(scalar) = arg.layout.backend_repr {
960                        if scalar.is_bool() {
961                            self.range_metadata(llval, WrappingRange { start: 0, end: 1 });
962                        }
963                        // We store bools as `i8` so we need to truncate to `i1`.
964                        llval = self.to_immediate_scalar(llval, scalar);
965                    }
966                    llargs.push(llval);
967                }
968            }
969        }
970
971        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/intrinsic.rs:971",
                        "rustc_codegen_llvm::intrinsic", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/intrinsic.rs"),
                        ::tracing_core::__macro_support::Option::Some(971u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::intrinsic"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("call intrinsic {0:?} with args ({1:?})",
                                                    instance, llargs) as &dyn Value))])
            });
    } else { ; }
};debug!("call intrinsic {:?} with args ({:?})", instance, llargs);
972
973        for (dest_ty, arg) in iter::zip(self.func_params_types(fn_ty), &mut llargs) {
974            let src_ty = self.val_ty(arg);
975            if !can_autocast(self, src_ty, dest_ty) {
    {
        ::core::panicking::panic_fmt(format_args!("Cannot match `{0:?}` (expected) with {1:?} (found) in `{2:?}",
                dest_ty, src_ty, fn_ptr));
    }
};assert!(
976                can_autocast(self, src_ty, dest_ty),
977                "Cannot match `{dest_ty:?}` (expected) with {src_ty:?} (found) in `{fn_ptr:?}"
978            );
979
980            *arg = autocast(self, arg, src_ty, dest_ty);
981        }
982
983        let llret = unsafe {
984            llvm::LLVMBuildCallWithOperandBundles(
985                self.llbuilder,
986                fn_ty,
987                fn_ptr,
988                llargs.as_ptr(),
989                llargs.len() as c_uint,
990                ptr::dangling(),
991                0,
992                c"".as_ptr(),
993            )
994        };
995
996        let src_ty = self.val_ty(llret);
997        let dest_ty = llreturn_ty;
998        if !can_autocast(self, dest_ty, src_ty) {
    {
        ::core::panicking::panic_fmt(format_args!("Cannot match `{0:?}` (expected) with `{1:?}` (found) in `{2:?}`",
                src_ty, dest_ty, fn_ptr));
    }
};assert!(
999            can_autocast(self, dest_ty, src_ty),
1000            "Cannot match `{src_ty:?}` (expected) with `{dest_ty:?}` (found) in `{fn_ptr:?}`"
1001        );
1002
1003        autocast(self, llret, src_ty, dest_ty)
1004    }
1005
1006    fn abort(&mut self) {
1007        self.call_intrinsic("llvm.trap", &[], &[]);
1008    }
1009
1010    fn assume(&mut self, val: Self::Value) {
1011        if self.cx.sess().opts.optimize != rustc_session::config::OptLevel::No {
1012            self.call_intrinsic("llvm.assume", &[], &[val]);
1013        }
1014    }
1015
1016    fn expect(&mut self, cond: Self::Value, expected: bool) -> Self::Value {
1017        if self.cx.sess().opts.optimize != rustc_session::config::OptLevel::No {
1018            self.call_intrinsic(
1019                "llvm.expect",
1020                &[self.type_i1()],
1021                &[cond, self.const_bool(expected)],
1022            )
1023        } else {
1024            cond
1025        }
1026    }
1027
1028    fn type_checked_load(
1029        &mut self,
1030        llvtable: &'ll Value,
1031        vtable_byte_offset: u64,
1032        typeid: &[u8],
1033    ) -> Self::Value {
1034        let typeid = self.create_metadata(typeid);
1035        let typeid = self.get_metadata_value(typeid);
1036        let vtable_byte_offset = self.const_i32(vtable_byte_offset as i32);
1037        let type_checked_load = self.call_intrinsic(
1038            "llvm.type.checked.load",
1039            &[],
1040            &[llvtable, vtable_byte_offset, typeid],
1041        );
1042        self.extract_value(type_checked_load, 0)
1043    }
1044
1045    fn va_start(&mut self, va_list: &'ll Value) -> &'ll Value {
1046        self.call_intrinsic("llvm.va_start", &[self.val_ty(va_list)], &[va_list])
1047    }
1048
1049    fn va_end(&mut self, va_list: &'ll Value) -> &'ll Value {
1050        self.call_intrinsic("llvm.va_end", &[self.val_ty(va_list)], &[va_list])
1051    }
1052}
1053
1054fn llvm_arch_for(rust_arch: &Arch) -> Option<&'static str> {
1055    Some(match rust_arch {
1056        Arch::AArch64 | Arch::Arm64EC => "aarch64",
1057        Arch::AmdGpu => "amdgcn",
1058        Arch::Arm => "arm",
1059        Arch::Bpf => "bpf",
1060        Arch::Hexagon => "hexagon",
1061        Arch::LoongArch32 | Arch::LoongArch64 => "loongarch",
1062        Arch::Mips | Arch::Mips32r6 | Arch::Mips64 | Arch::Mips64r6 => "mips",
1063        Arch::Nvptx64 => "nvvm",
1064        Arch::PowerPC | Arch::PowerPC64 => "ppc",
1065        Arch::RiscV32 | Arch::RiscV64 => "riscv",
1066        Arch::S390x => "s390",
1067        Arch::SpirV => "spv",
1068        Arch::Wasm32 | Arch::Wasm64 => "wasm",
1069        Arch::X86 | Arch::X86_64 => "x86",
1070        _ => return None, // fallback for unknown archs
1071    })
1072}
1073
1074fn can_autocast<'ll>(cx: &CodegenCx<'ll, '_>, rust_ty: &'ll Type, llvm_ty: &'ll Type) -> bool {
1075    if rust_ty == llvm_ty {
1076        return true;
1077    }
1078
1079    match cx.type_kind(llvm_ty) {
1080        // Some LLVM intrinsics return **non-packed** structs, but they can't be mimicked from Rust
1081        // due to auto field-alignment in non-packed structs (packed structs are represented in LLVM
1082        // as, well, packed structs, so they won't match with those either)
1083        TypeKind::Struct if cx.type_kind(rust_ty) == TypeKind::Struct => {
1084            let rust_element_tys = cx.struct_element_types(rust_ty);
1085            let llvm_element_tys = cx.struct_element_types(llvm_ty);
1086
1087            if rust_element_tys.len() != llvm_element_tys.len() {
1088                return false;
1089            }
1090
1091            iter::zip(rust_element_tys, llvm_element_tys).all(
1092                |(rust_element_ty, llvm_element_ty)| {
1093                    can_autocast(cx, rust_element_ty, llvm_element_ty)
1094                },
1095            )
1096        }
1097        TypeKind::Vector => {
1098            let llvm_element_ty = cx.element_type(llvm_ty);
1099            let element_count = cx.vector_length(llvm_ty) as u64;
1100
1101            if llvm_element_ty == cx.type_bf16() {
1102                rust_ty == cx.type_vector(cx.type_i16(), element_count)
1103            } else if llvm_element_ty == cx.type_i1() {
1104                let int_width = element_count.next_power_of_two().max(8);
1105                rust_ty == cx.type_ix(int_width)
1106            } else {
1107                false
1108            }
1109        }
1110        TypeKind::BFloat => rust_ty == cx.type_i16(),
1111        TypeKind::X86_AMX if cx.type_kind(rust_ty) == TypeKind::Vector => {
1112            let element_ty = cx.element_type(rust_ty);
1113            let element_count = cx.vector_length(rust_ty) as u64;
1114
1115            let element_size_bits = match cx.type_kind(element_ty) {
1116                TypeKind::Half => 16,
1117                TypeKind::Float => 32,
1118                TypeKind::Double => 64,
1119                TypeKind::FP128 => 128,
1120                TypeKind::Integer => cx.int_width(element_ty),
1121                TypeKind::Pointer => cx.int_width(cx.isize_ty),
1122                _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Vector element type `{0:?}` not one of integer, float or pointer",
        element_ty))bug!(
1123                    "Vector element type `{element_ty:?}` not one of integer, float or pointer"
1124                ),
1125            };
1126
1127            element_size_bits * element_count == 8192
1128        }
1129        _ => false,
1130    }
1131}
1132
1133fn autocast<'ll>(
1134    bx: &mut Builder<'_, 'll, '_>,
1135    val: &'ll Value,
1136    src_ty: &'ll Type,
1137    dest_ty: &'ll Type,
1138) -> &'ll Value {
1139    if src_ty == dest_ty {
1140        return val;
1141    }
1142    match (bx.type_kind(src_ty), bx.type_kind(dest_ty)) {
1143        // re-pack structs
1144        (TypeKind::Struct, TypeKind::Struct) => {
1145            let mut ret = bx.const_poison(dest_ty);
1146            for (idx, (src_element_ty, dest_element_ty)) in
1147                iter::zip(bx.struct_element_types(src_ty), bx.struct_element_types(dest_ty))
1148                    .enumerate()
1149            {
1150                let elt = bx.extract_value(val, idx as u64);
1151                let casted_elt = autocast(bx, elt, src_element_ty, dest_element_ty);
1152                ret = bx.insert_value(ret, casted_elt, idx as u64);
1153            }
1154            ret
1155        }
1156        // cast from the i1xN vector type to the primitive type
1157        (TypeKind::Vector, TypeKind::Integer) if bx.element_type(src_ty) == bx.type_i1() => {
1158            let vector_length = bx.vector_length(src_ty) as u64;
1159            let int_width = vector_length.next_power_of_two().max(8);
1160
1161            let val = if vector_length == int_width {
1162                val
1163            } else {
1164                // zero-extends vector
1165                let shuffle_indices = match vector_length {
1166                    0 => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("zero length vectors are not allowed")));
}unreachable!("zero length vectors are not allowed"),
1167                    1 => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [0, 1, 1, 1, 1, 1, 1, 1]))vec![0, 1, 1, 1, 1, 1, 1, 1],
1168                    2 => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [0, 1, 2, 2, 2, 2, 2, 2]))vec![0, 1, 2, 2, 2, 2, 2, 2],
1169                    3 => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [0, 1, 2, 3, 3, 3, 3, 3]))vec![0, 1, 2, 3, 3, 3, 3, 3],
1170                    4.. => (0..int_width as i32).collect(),
1171                };
1172                let shuffle_mask =
1173                    shuffle_indices.into_iter().map(|i| bx.const_i32(i)).collect::<Vec<_>>();
1174                bx.shuffle_vector(val, bx.const_null(src_ty), bx.const_vector(&shuffle_mask))
1175            };
1176            bx.bitcast(val, dest_ty)
1177        }
1178        // cast from the primitive type to the i1xN vector type
1179        (TypeKind::Integer, TypeKind::Vector) if bx.element_type(dest_ty) == bx.type_i1() => {
1180            let vector_length = bx.vector_length(dest_ty) as u64;
1181            let int_width = vector_length.next_power_of_two().max(8);
1182
1183            let intermediate_ty = bx.type_vector(bx.type_i1(), int_width);
1184            let intermediate = bx.bitcast(val, intermediate_ty);
1185
1186            if vector_length == int_width {
1187                intermediate
1188            } else {
1189                let shuffle_mask: Vec<_> =
1190                    (0..vector_length).map(|i| bx.const_i32(i as i32)).collect();
1191                bx.shuffle_vector(
1192                    intermediate,
1193                    bx.const_poison(intermediate_ty),
1194                    bx.const_vector(&shuffle_mask),
1195                )
1196            }
1197        }
1198        (TypeKind::Vector, TypeKind::X86_AMX) => {
1199            bx.call_intrinsic("llvm.x86.cast.vector.to.tile", &[src_ty], &[val])
1200        }
1201        (TypeKind::X86_AMX, TypeKind::Vector) => {
1202            bx.call_intrinsic("llvm.x86.cast.tile.to.vector", &[dest_ty], &[val])
1203        }
1204        _ => bx.bitcast(val, dest_ty), // for `bf16(xN)` <-> `u16(xN)`
1205    }
1206}
1207
1208fn intrinsic_fn<'ll, 'tcx>(
1209    bx: &Builder<'_, 'll, 'tcx>,
1210    name: &str,
1211    rust_return_ty: &'ll Type,
1212    rust_argument_tys: Vec<&'ll Type>,
1213    instance: ty::Instance<'tcx>,
1214) -> &'ll Value {
1215    let tcx = bx.tcx;
1216
1217    let rust_fn_ty = bx.type_func(&rust_argument_tys, rust_return_ty);
1218
1219    let intrinsic = llvm::Intrinsic::lookup(name.as_bytes());
1220
1221    if let Some(intrinsic) = intrinsic
1222        && intrinsic.is_target_specific()
1223    {
1224        let (llvm_arch, _) = name[5..].split_once('.').unwrap();
1225        let rust_arch = &tcx.sess.target.arch;
1226
1227        if let Some(correct_llvm_arch) = llvm_arch_for(rust_arch)
1228            && llvm_arch != correct_llvm_arch
1229        {
1230            tcx.dcx().emit_fatal(IntrinsicWrongArch {
1231                name,
1232                target_arch: rust_arch.desc(),
1233                span: tcx.def_span(instance.def_id()),
1234            });
1235        }
1236    }
1237
1238    if let Some(intrinsic) = intrinsic
1239        && !intrinsic.is_overloaded()
1240    {
1241        // FIXME: also do this for overloaded intrinsics
1242        let llfn = intrinsic.get_declaration(bx.llmod, &[]);
1243        let llvm_fn_ty = bx.get_type_of_global(llfn);
1244
1245        let llvm_return_ty = bx.get_return_type(llvm_fn_ty);
1246        let llvm_argument_tys = bx.func_params_types(llvm_fn_ty);
1247        let llvm_is_variadic = bx.func_is_variadic(llvm_fn_ty);
1248
1249        let is_correct_signature = !llvm_is_variadic
1250            && rust_argument_tys.len() == llvm_argument_tys.len()
1251            && iter::once((rust_return_ty, llvm_return_ty))
1252                .chain(iter::zip(rust_argument_tys, llvm_argument_tys))
1253                .all(|(rust_ty, llvm_ty)| can_autocast(bx, rust_ty, llvm_ty));
1254
1255        if !is_correct_signature {
1256            tcx.dcx().emit_fatal(IntrinsicSignatureMismatch {
1257                name,
1258                llvm_fn_ty: &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", llvm_fn_ty))
    })format!("{llvm_fn_ty:?}"),
1259                rust_fn_ty: &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", rust_fn_ty))
    })format!("{rust_fn_ty:?}"),
1260                span: tcx.def_span(instance.def_id()),
1261            });
1262        }
1263
1264        return llfn;
1265    }
1266
1267    // Function addresses in Rust are never significant, allowing functions to be merged.
1268    let llfn = declare_raw_fn(
1269        bx,
1270        name,
1271        llvm::CCallConv,
1272        llvm::UnnamedAddr::Global,
1273        llvm::Visibility::Default,
1274        rust_fn_ty,
1275    );
1276
1277    if intrinsic.is_none() {
1278        let mut new_llfn = None;
1279        let can_upgrade = unsafe { llvm::LLVMRustUpgradeIntrinsicFunction(llfn, &mut new_llfn) };
1280
1281        if !can_upgrade {
1282            // This is either plain wrong, or this can be caused by incompatible LLVM versions
1283            tcx.dcx().emit_fatal(UnknownIntrinsic { name, span: tcx.def_span(instance.def_id()) });
1284        } else if let Some(def_id) = instance.def_id().as_local() {
1285            // we can emit diagnostics only for local crates
1286            let hir_id = tcx.local_def_id_to_hir_id(def_id);
1287
1288            // not all intrinsics are upgraded to some other intrinsics, most are upgraded to instruction sequences
1289            let msg = if let Some(new_llfn) = new_llfn {
1290                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("using deprecated intrinsic `{1}`, `{0}` can be used instead",
                str::from_utf8(&llvm::get_value_name(new_llfn)).unwrap(),
                name))
    })format!(
1291                    "using deprecated intrinsic `{name}`, `{}` can be used instead",
1292                    str::from_utf8(&llvm::get_value_name(new_llfn)).unwrap()
1293                )
1294            } else {
1295                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("using deprecated intrinsic `{0}`",
                name))
    })format!("using deprecated intrinsic `{name}`")
1296            };
1297
1298            tcx.emit_node_lint(
1299                DEPRECATED_LLVM_INTRINSIC,
1300                hir_id,
1301                rustc_errors::DiagDecorator(|d| {
1302                    d.primary_message(msg).span(tcx.hir_span(hir_id));
1303                }),
1304            );
1305        }
1306    }
1307
1308    llfn
1309}
1310
1311fn catch_unwind_intrinsic<'ll, 'tcx>(
1312    bx: &mut Builder<'_, 'll, 'tcx>,
1313    try_func: &'ll Value,
1314    data: &'ll Value,
1315    catch_func: &'ll Value,
1316    dest: PlaceRef<'tcx, &'ll Value>,
1317) {
1318    if !bx.sess().panic_strategy().unwinds() {
1319        let try_func_ty = bx.type_func(&[bx.type_ptr()], bx.type_void());
1320        bx.call(try_func_ty, None, None, try_func, &[data], None, None);
1321        // Return 0 unconditionally from the intrinsic call;
1322        // we can never unwind.
1323        OperandValue::Immediate(bx.const_i32(0)).store(bx, dest);
1324    } else if wants_msvc_seh(bx.sess()) {
1325        codegen_msvc_try(bx, try_func, data, catch_func, dest);
1326    } else if wants_wasm_eh(bx.sess()) {
1327        codegen_wasm_try(bx, try_func, data, catch_func, dest);
1328    } else if bx.sess().target.os == Os::Emscripten {
1329        codegen_emcc_try(bx, try_func, data, catch_func, dest);
1330    } else {
1331        codegen_gnu_try(bx, try_func, data, catch_func, dest);
1332    }
1333}
1334
1335// MSVC's definition of the `rust_try` function.
1336//
1337// This implementation uses the new exception handling instructions in LLVM
1338// which have support in LLVM for SEH on MSVC targets. Although these
1339// instructions are meant to work for all targets, as of the time of this
1340// writing, however, LLVM does not recommend the usage of these new instructions
1341// as the old ones are still more optimized.
1342fn codegen_msvc_try<'ll, 'tcx>(
1343    bx: &mut Builder<'_, 'll, 'tcx>,
1344    try_func: &'ll Value,
1345    data: &'ll Value,
1346    catch_func: &'ll Value,
1347    dest: PlaceRef<'tcx, &'ll Value>,
1348) {
1349    let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
1350        bx.set_personality_fn(bx.eh_personality());
1351
1352        let normal = bx.append_sibling_block("normal");
1353        let catchswitch = bx.append_sibling_block("catchswitch");
1354        let catchpad_rust = bx.append_sibling_block("catchpad_rust");
1355        let catchpad_foreign = bx.append_sibling_block("catchpad_foreign");
1356        let caught = bx.append_sibling_block("caught");
1357
1358        let try_func = llvm::get_param(bx.llfn(), 0);
1359        let data = llvm::get_param(bx.llfn(), 1);
1360        let catch_func = llvm::get_param(bx.llfn(), 2);
1361
1362        // We're generating an IR snippet that looks like:
1363        //
1364        //   declare i32 @rust_try(%try_func, %data, %catch_func) {
1365        //      %slot = alloca i8*
1366        //      invoke %try_func(%data) to label %normal unwind label %catchswitch
1367        //
1368        //   normal:
1369        //      ret i32 0
1370        //
1371        //   catchswitch:
1372        //      %cs = catchswitch within none [%catchpad_rust, %catchpad_foreign] unwind to caller
1373        //
1374        //   catchpad_rust:
1375        //      %tok = catchpad within %cs [%type_descriptor, 8, %slot]
1376        //      %ptr = load %slot
1377        //      call %catch_func(%data, %ptr)
1378        //      catchret from %tok to label %caught
1379        //
1380        //   catchpad_foreign:
1381        //      %tok = catchpad within %cs [null, 64, null]
1382        //      call %catch_func(%data, null)
1383        //      catchret from %tok to label %caught
1384        //
1385        //   caught:
1386        //      ret i32 1
1387        //   }
1388        //
1389        // This structure follows the basic usage of throw/try/catch in LLVM.
1390        // For example, compile this C++ snippet to see what LLVM generates:
1391        //
1392        //      struct rust_panic {
1393        //          rust_panic(const rust_panic&);
1394        //          ~rust_panic();
1395        //
1396        //          void* x[2];
1397        //      };
1398        //
1399        //      int __rust_try(
1400        //          void (*try_func)(void*),
1401        //          void *data,
1402        //          void (*catch_func)(void*, void*) noexcept
1403        //      ) {
1404        //          try {
1405        //              try_func(data);
1406        //              return 0;
1407        //          } catch(rust_panic& a) {
1408        //              catch_func(data, &a);
1409        //              return 1;
1410        //          } catch(...) {
1411        //              catch_func(data, NULL);
1412        //              return 1;
1413        //          }
1414        //      }
1415        //
1416        // More information can be found in libstd's seh.rs implementation.
1417        let ptr_size = bx.tcx().data_layout.pointer_size();
1418        let ptr_align = bx.tcx().data_layout.pointer_align().abi;
1419        let slot = bx.alloca(ptr_size, ptr_align);
1420        let try_func_ty = bx.type_func(&[bx.type_ptr()], bx.type_void());
1421        bx.invoke(try_func_ty, None, None, try_func, &[data], normal, catchswitch, None, None);
1422
1423        bx.switch_to_block(normal);
1424        bx.ret(bx.const_i32(0));
1425
1426        bx.switch_to_block(catchswitch);
1427        let cs = bx.catch_switch(None, None, &[catchpad_rust, catchpad_foreign]);
1428
1429        // We can't use the TypeDescriptor defined in libpanic_unwind because it
1430        // might be in another DLL and the SEH encoding only supports specifying
1431        // a TypeDescriptor from the current module.
1432        //
1433        // However this isn't an issue since the MSVC runtime uses string
1434        // comparison on the type name to match TypeDescriptors rather than
1435        // pointer equality.
1436        //
1437        // So instead we generate a new TypeDescriptor in each module that uses
1438        // `try` and let the linker merge duplicate definitions in the same
1439        // module.
1440        //
1441        // When modifying, make sure that the type_name string exactly matches
1442        // the one used in library/panic_unwind/src/seh.rs.
1443        let type_info_vtable = bx.declare_global("??_7type_info@@6B@", bx.type_ptr());
1444        let type_name = bx.const_bytes(b"rust_panic\0");
1445        let type_info =
1446            bx.const_struct(&[type_info_vtable, bx.const_null(bx.type_ptr()), type_name], false);
1447        let tydesc = bx.declare_global(
1448            &mangle_internal_symbol(bx.tcx, "__rust_panic_type_info"),
1449            bx.val_ty(type_info),
1450        );
1451
1452        llvm::set_linkage(tydesc, llvm::Linkage::LinkOnceODRLinkage);
1453        if bx.cx.tcx.sess.target.supports_comdat() {
1454            llvm::SetUniqueComdat(bx.llmod, tydesc);
1455        }
1456        llvm::set_initializer(tydesc, type_info);
1457
1458        // The flag value of 8 indicates that we are catching the exception by
1459        // reference instead of by value. We can't use catch by value because
1460        // that requires copying the exception object, which we don't support
1461        // since our exception object effectively contains a Box.
1462        //
1463        // Source: MicrosoftCXXABI::getAddrOfCXXCatchHandlerType in clang
1464        bx.switch_to_block(catchpad_rust);
1465        let flags = bx.const_i32(8);
1466        let funclet = bx.catch_pad(cs, &[tydesc, flags, slot]);
1467        let ptr = bx.load(bx.type_ptr(), slot, ptr_align);
1468        let catch_ty = bx.type_func(&[bx.type_ptr(), bx.type_ptr()], bx.type_void());
1469        bx.call(catch_ty, None, None, catch_func, &[data, ptr], Some(&funclet), None);
1470        bx.catch_ret(&funclet, caught);
1471
1472        // The flag value of 64 indicates a "catch-all".
1473        bx.switch_to_block(catchpad_foreign);
1474        let flags = bx.const_i32(64);
1475        let null = bx.const_null(bx.type_ptr());
1476        let funclet = bx.catch_pad(cs, &[null, flags, null]);
1477        bx.call(catch_ty, None, None, catch_func, &[data, null], Some(&funclet), None);
1478        bx.catch_ret(&funclet, caught);
1479
1480        bx.switch_to_block(caught);
1481        bx.ret(bx.const_i32(1));
1482    });
1483
1484    // Note that no invoke is used here because by definition this function
1485    // can't panic (that's what it's catching).
1486    let ret = bx.call(llty, None, None, llfn, &[try_func, data, catch_func], None, None);
1487    OperandValue::Immediate(ret).store(bx, dest);
1488}
1489
1490// WASM's definition of the `rust_try` function.
1491fn codegen_wasm_try<'ll, 'tcx>(
1492    bx: &mut Builder<'_, 'll, 'tcx>,
1493    try_func: &'ll Value,
1494    data: &'ll Value,
1495    catch_func: &'ll Value,
1496    dest: PlaceRef<'tcx, &'ll Value>,
1497) {
1498    let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
1499        bx.set_personality_fn(bx.eh_personality());
1500
1501        let normal = bx.append_sibling_block("normal");
1502        let catchswitch = bx.append_sibling_block("catchswitch");
1503        let catchpad = bx.append_sibling_block("catchpad");
1504        let caught = bx.append_sibling_block("caught");
1505
1506        let try_func = llvm::get_param(bx.llfn(), 0);
1507        let data = llvm::get_param(bx.llfn(), 1);
1508        let catch_func = llvm::get_param(bx.llfn(), 2);
1509
1510        // We're generating an IR snippet that looks like:
1511        //
1512        //   declare i32 @rust_try(%try_func, %data, %catch_func) {
1513        //      %slot = alloca i8*
1514        //      invoke %try_func(%data) to label %normal unwind label %catchswitch
1515        //
1516        //   normal:
1517        //      ret i32 0
1518        //
1519        //   catchswitch:
1520        //      %cs = catchswitch within none [%catchpad] unwind to caller
1521        //
1522        //   catchpad:
1523        //      %tok = catchpad within %cs [null]
1524        //      %ptr = call @llvm.wasm.get.exception(token %tok)
1525        //      %sel = call @llvm.wasm.get.ehselector(token %tok)
1526        //      call %catch_func(%data, %ptr)
1527        //      catchret from %tok to label %caught
1528        //
1529        //   caught:
1530        //      ret i32 1
1531        //   }
1532        //
1533        let try_func_ty = bx.type_func(&[bx.type_ptr()], bx.type_void());
1534        bx.invoke(try_func_ty, None, None, try_func, &[data], normal, catchswitch, None, None);
1535
1536        bx.switch_to_block(normal);
1537        bx.ret(bx.const_i32(0));
1538
1539        bx.switch_to_block(catchswitch);
1540        let cs = bx.catch_switch(None, None, &[catchpad]);
1541
1542        bx.switch_to_block(catchpad);
1543        let null = bx.const_null(bx.type_ptr());
1544        let funclet = bx.catch_pad(cs, &[null]);
1545
1546        let ptr = bx.call_intrinsic("llvm.wasm.get.exception", &[], &[funclet.cleanuppad()]);
1547        let _sel = bx.call_intrinsic("llvm.wasm.get.ehselector", &[], &[funclet.cleanuppad()]);
1548
1549        let catch_ty = bx.type_func(&[bx.type_ptr(), bx.type_ptr()], bx.type_void());
1550        bx.call(catch_ty, None, None, catch_func, &[data, ptr], Some(&funclet), None);
1551        bx.catch_ret(&funclet, caught);
1552
1553        bx.switch_to_block(caught);
1554        bx.ret(bx.const_i32(1));
1555    });
1556
1557    // Note that no invoke is used here because by definition this function
1558    // can't panic (that's what it's catching).
1559    let ret = bx.call(llty, None, None, llfn, &[try_func, data, catch_func], None, None);
1560    OperandValue::Immediate(ret).store(bx, dest);
1561}
1562
1563// Definition of the standard `try` function for Rust using the GNU-like model
1564// of exceptions (e.g., the normal semantics of LLVM's `landingpad` and `invoke`
1565// instructions).
1566//
1567// This codegen is a little surprising because we always call a shim
1568// function instead of inlining the call to `invoke` manually here. This is done
1569// because in LLVM we're only allowed to have one personality per function
1570// definition. The call to the `try` intrinsic is being inlined into the
1571// function calling it, and that function may already have other personality
1572// functions in play. By calling a shim we're guaranteed that our shim will have
1573// the right personality function.
1574fn codegen_gnu_try<'ll, 'tcx>(
1575    bx: &mut Builder<'_, 'll, 'tcx>,
1576    try_func: &'ll Value,
1577    data: &'ll Value,
1578    catch_func: &'ll Value,
1579    dest: PlaceRef<'tcx, &'ll Value>,
1580) {
1581    let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
1582        // Codegens the shims described above:
1583        //
1584        //   bx:
1585        //      invoke %try_func(%data) normal %normal unwind %catch
1586        //
1587        //   normal:
1588        //      ret 0
1589        //
1590        //   catch:
1591        //      (%ptr, _) = landingpad
1592        //      call %catch_func(%data, %ptr)
1593        //      ret 1
1594        let then = bx.append_sibling_block("then");
1595        let catch = bx.append_sibling_block("catch");
1596
1597        let try_func = llvm::get_param(bx.llfn(), 0);
1598        let data = llvm::get_param(bx.llfn(), 1);
1599        let catch_func = llvm::get_param(bx.llfn(), 2);
1600        let try_func_ty = bx.type_func(&[bx.type_ptr()], bx.type_void());
1601        bx.invoke(try_func_ty, None, None, try_func, &[data], then, catch, None, None);
1602
1603        bx.switch_to_block(then);
1604        bx.ret(bx.const_i32(0));
1605
1606        // Type indicator for the exception being thrown.
1607        //
1608        // The first value in this tuple is a pointer to the exception object
1609        // being thrown. The second value is a "selector" indicating which of
1610        // the landing pad clauses the exception's type had been matched to.
1611        // rust_try ignores the selector.
1612        bx.switch_to_block(catch);
1613        let lpad_ty = bx.type_struct(&[bx.type_ptr(), bx.type_i32()], false);
1614        let vals = bx.landing_pad(lpad_ty, bx.eh_personality(), 1);
1615        let tydesc = bx.const_null(bx.type_ptr());
1616        bx.add_clause(vals, tydesc);
1617        let ptr = bx.extract_value(vals, 0);
1618        let catch_ty = bx.type_func(&[bx.type_ptr(), bx.type_ptr()], bx.type_void());
1619        bx.call(catch_ty, None, None, catch_func, &[data, ptr], None, None);
1620        bx.ret(bx.const_i32(1));
1621    });
1622
1623    // Note that no invoke is used here because by definition this function
1624    // can't panic (that's what it's catching).
1625    let ret = bx.call(llty, None, None, llfn, &[try_func, data, catch_func], None, None);
1626    OperandValue::Immediate(ret).store(bx, dest);
1627}
1628
1629// Variant of codegen_gnu_try used for emscripten where Rust panics are
1630// implemented using C++ exceptions. Here we use exceptions of a specific type
1631// (`struct rust_panic`) to represent Rust panics.
1632fn codegen_emcc_try<'ll, 'tcx>(
1633    bx: &mut Builder<'_, 'll, 'tcx>,
1634    try_func: &'ll Value,
1635    data: &'ll Value,
1636    catch_func: &'ll Value,
1637    dest: PlaceRef<'tcx, &'ll Value>,
1638) {
1639    let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
1640        // Codegens the shims described above:
1641        //
1642        //   bx:
1643        //      invoke %try_func(%data) normal %normal unwind %catch
1644        //
1645        //   normal:
1646        //      ret 0
1647        //
1648        //   catch:
1649        //      (%ptr, %selector) = landingpad
1650        //      %rust_typeid = @llvm.eh.typeid.for(@_ZTI10rust_panic)
1651        //      %is_rust_panic = %selector == %rust_typeid
1652        //      %catch_data = alloca { i8*, i8 }
1653        //      %catch_data[0] = %ptr
1654        //      %catch_data[1] = %is_rust_panic
1655        //      call %catch_func(%data, %catch_data)
1656        //      ret 1
1657        let then = bx.append_sibling_block("then");
1658        let catch = bx.append_sibling_block("catch");
1659
1660        let try_func = llvm::get_param(bx.llfn(), 0);
1661        let data = llvm::get_param(bx.llfn(), 1);
1662        let catch_func = llvm::get_param(bx.llfn(), 2);
1663        let try_func_ty = bx.type_func(&[bx.type_ptr()], bx.type_void());
1664        bx.invoke(try_func_ty, None, None, try_func, &[data], then, catch, None, None);
1665
1666        bx.switch_to_block(then);
1667        bx.ret(bx.const_i32(0));
1668
1669        // Type indicator for the exception being thrown.
1670        //
1671        // The first value in this tuple is a pointer to the exception object
1672        // being thrown. The second value is a "selector" indicating which of
1673        // the landing pad clauses the exception's type had been matched to.
1674        bx.switch_to_block(catch);
1675        let tydesc = bx.eh_catch_typeinfo();
1676        let lpad_ty = bx.type_struct(&[bx.type_ptr(), bx.type_i32()], false);
1677        let vals = bx.landing_pad(lpad_ty, bx.eh_personality(), 2);
1678        bx.add_clause(vals, tydesc);
1679        bx.add_clause(vals, bx.const_null(bx.type_ptr()));
1680        let ptr = bx.extract_value(vals, 0);
1681        let selector = bx.extract_value(vals, 1);
1682
1683        // Check if the typeid we got is the one for a Rust panic.
1684        let rust_typeid = bx.call_intrinsic("llvm.eh.typeid.for", &[bx.val_ty(tydesc)], &[tydesc]);
1685        let is_rust_panic = bx.icmp(IntPredicate::IntEQ, selector, rust_typeid);
1686        let is_rust_panic = bx.zext(is_rust_panic, bx.type_bool());
1687
1688        // We need to pass two values to catch_func (ptr and is_rust_panic), so
1689        // create an alloca and pass a pointer to that.
1690        let ptr_size = bx.tcx().data_layout.pointer_size();
1691        let ptr_align = bx.tcx().data_layout.pointer_align().abi;
1692        let i8_align = bx.tcx().data_layout.i8_align;
1693        // Required in order for there to be no padding between the fields.
1694        if !(i8_align <= ptr_align) {
    ::core::panicking::panic("assertion failed: i8_align <= ptr_align")
};assert!(i8_align <= ptr_align);
1695        let catch_data = bx.alloca(2 * ptr_size, ptr_align);
1696        bx.store(ptr, catch_data, ptr_align);
1697        let catch_data_1 = bx.inbounds_ptradd(catch_data, bx.const_usize(ptr_size.bytes()));
1698        bx.store(is_rust_panic, catch_data_1, i8_align);
1699
1700        let catch_ty = bx.type_func(&[bx.type_ptr(), bx.type_ptr()], bx.type_void());
1701        bx.call(catch_ty, None, None, catch_func, &[data, catch_data], None, None);
1702        bx.ret(bx.const_i32(1));
1703    });
1704
1705    // Note that no invoke is used here because by definition this function
1706    // can't panic (that's what it's catching).
1707    let ret = bx.call(llty, None, None, llfn, &[try_func, data, catch_func], None, None);
1708    OperandValue::Immediate(ret).store(bx, dest);
1709}
1710
1711// Helper function to give a Block to a closure to codegen a shim function.
1712// This is currently primarily used for the `try` intrinsic functions above.
1713fn gen_fn<'a, 'll, 'tcx>(
1714    cx: &'a CodegenCx<'ll, 'tcx>,
1715    name: &str,
1716    rust_fn_sig: ty::PolyFnSig<'tcx>,
1717    codegen: &mut dyn FnMut(Builder<'a, 'll, 'tcx>),
1718) -> (&'ll Type, &'ll Value) {
1719    let fn_abi = cx.fn_abi_of_fn_ptr(rust_fn_sig, ty::List::empty());
1720    let llty = fn_abi.llvm_type(cx);
1721    let llfn = cx.declare_fn(name, fn_abi, None);
1722    cx.set_frame_pointer_type(llfn);
1723    cx.apply_target_cpu_attr(llfn);
1724    // FIXME(eddyb) find a nicer way to do this.
1725    llvm::set_linkage(llfn, llvm::Linkage::InternalLinkage);
1726    let llbb = Builder::append_block(cx, llfn, "entry-block");
1727    let bx = Builder::build(cx, llbb);
1728    codegen(bx);
1729    (llty, llfn)
1730}
1731
1732// Helper function used to get a handle to the `__rust_try` function used to
1733// catch exceptions.
1734//
1735// This function is only generated once and is then cached.
1736fn get_rust_try_fn<'a, 'll, 'tcx>(
1737    cx: &'a CodegenCx<'ll, 'tcx>,
1738    codegen: &mut dyn FnMut(Builder<'a, 'll, 'tcx>),
1739) -> (&'ll Type, &'ll Value) {
1740    if let Some(llfn) = cx.rust_try_fn.get() {
1741        return llfn;
1742    }
1743
1744    // Define the type up front for the signature of the rust_try function.
1745    let tcx = cx.tcx;
1746    let i8p = Ty::new_mut_ptr(tcx, tcx.types.i8);
1747    // `unsafe fn(*mut i8) -> ()`
1748    let try_fn_ty = Ty::new_fn_ptr(
1749        tcx,
1750        ty::Binder::dummy(tcx.mk_fn_sig_rust_abi([i8p], tcx.types.unit, hir::Safety::Unsafe)),
1751    );
1752    // `unsafe fn(*mut i8, *mut i8) -> ()`
1753    let catch_fn_ty = Ty::new_fn_ptr(
1754        tcx,
1755        ty::Binder::dummy(tcx.mk_fn_sig_rust_abi([i8p, i8p], tcx.types.unit, hir::Safety::Unsafe)),
1756    );
1757    // `unsafe fn(unsafe fn(*mut i8) -> (), *mut i8, unsafe fn(*mut i8, *mut i8) -> ()) -> i32`
1758    let rust_fn_sig = ty::Binder::dummy(cx.tcx.mk_fn_sig_rust_abi(
1759        [try_fn_ty, i8p, catch_fn_ty],
1760        tcx.types.i32,
1761        hir::Safety::Unsafe,
1762    ));
1763    let rust_try = gen_fn(cx, "__rust_try", rust_fn_sig, codegen);
1764    cx.rust_try_fn.set(Some(rust_try));
1765    rust_try
1766}
1767
1768fn codegen_autodiff<'ll, 'tcx>(
1769    bx: &mut Builder<'_, 'll, 'tcx>,
1770    tcx: TyCtxt<'tcx>,
1771    instance: ty::Instance<'tcx>,
1772    args: &[OperandRef<'tcx, &'ll Value>],
1773    result: PlaceRef<'tcx, &'ll Value>,
1774) {
1775    if !tcx.sess.opts.unstable_opts.autodiff.contains(&rustc_session::config::AutoDiff::Enable) {
1776        let _ = tcx.dcx().emit_almost_fatal(AutoDiffWithoutEnable);
1777    }
1778
1779    let ct = tcx.crate_types();
1780    let lto = tcx.sess.lto();
1781    if ct.len() == 1 && ct.contains(&CrateType::Executable) {
1782        if lto != rustc_session::config::Lto::Fat {
1783            let _ = tcx.dcx().emit_almost_fatal(AutoDiffWithoutLto);
1784        }
1785    } else {
1786        if lto != rustc_session::config::Lto::Fat && !tcx.sess.opts.cg.linker_plugin_lto.enabled() {
1787            let _ = tcx.dcx().emit_almost_fatal(AutoDiffWithoutLto);
1788        }
1789    }
1790
1791    let fn_args = instance.args;
1792    let callee_ty = instance.ty(tcx, bx.typing_env());
1793
1794    let sig = callee_ty.fn_sig(tcx).skip_binder();
1795
1796    let ret_ty = sig.output();
1797    let llret_ty = bx.layout_of(ret_ty).llvm_type(bx);
1798
1799    let source_fn_ptr_ty = fn_args.into_type_list(tcx)[0];
1800    let fn_to_diff = args[0].immediate();
1801
1802    let (diff_id, diff_args) = match fn_args.into_type_list(tcx)[1].kind() {
1803        ty::FnDef(def_id, diff_args) => (def_id, diff_args),
1804        _ => ::rustc_middle::util::bug::bug_fmt(format_args!("invalid args"))bug!("invalid args"),
1805    };
1806
1807    let fn_diff = match Instance::try_resolve(tcx, bx.cx.typing_env(), *diff_id, diff_args) {
1808        Ok(Some(instance)) => instance,
1809        Ok(None) => ::rustc_middle::util::bug::bug_fmt(format_args!("could not resolve ({0:?}, {1:?}) to a specific autodiff instance",
        diff_id, diff_args))bug!(
1810            "could not resolve ({:?}, {:?}) to a specific autodiff instance",
1811            diff_id,
1812            diff_args
1813        ),
1814        Err(_) => {
1815            // An error has already been emitted
1816            return;
1817        }
1818    };
1819
1820    let val_arr = get_args_from_tuple(bx, args[2], fn_diff);
1821    let diff_symbol = symbol_name_for_instance_in_crate(tcx, fn_diff.clone(), LOCAL_CRATE);
1822
1823    let Some(Some(mut diff_attrs)) =
1824        {
    {
        'done:
            {
            for i in
                ::rustc_hir::attrs::HasAttrs::get_attrs(fn_diff.def_id(),
                    &tcx) {
                #[allow(unused_imports)]
                use rustc_hir::attrs::AttributeKind::*;
                let i: &rustc_hir::Attribute = i;
                match i {
                    rustc_hir::Attribute::Parsed(RustcAutodiff(attr)) => {
                        break 'done Some(attr.clone());
                    }
                    rustc_hir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(tcx, fn_diff.def_id(), RustcAutodiff(attr) => attr.clone())
1825    else {
1826        ::rustc_middle::util::bug::bug_fmt(format_args!("could not find autodiff attrs"))bug!("could not find autodiff attrs")
1827    };
1828
1829    adjust_activity_to_abi(
1830        tcx,
1831        source_fn_ptr_ty,
1832        TypingEnv::fully_monomorphized(),
1833        &mut diff_attrs.input_activity,
1834    );
1835
1836    let fnc_tree = rustc_middle::ty::fnc_typetrees(tcx, source_fn_ptr_ty);
1837
1838    // Build body
1839    generate_enzyme_call(
1840        bx,
1841        bx.cx,
1842        fn_to_diff,
1843        &diff_symbol,
1844        llret_ty,
1845        &val_arr,
1846        &diff_attrs,
1847        result,
1848        fnc_tree,
1849    );
1850}
1851
1852// Generates the LLVM code to offload a Rust function to a target device (e.g., GPU).
1853// For each kernel call, it generates the necessary globals (including metadata such as
1854// size and pass mode), manages memory mapping to and from the device, handles all
1855// data transfers, and launches the kernel on the target device.
1856fn codegen_offload<'ll, 'tcx>(
1857    bx: &mut Builder<'_, 'll, 'tcx>,
1858    tcx: TyCtxt<'tcx>,
1859    instance: ty::Instance<'tcx>,
1860    args: &[OperandRef<'tcx, &'ll Value>],
1861) {
1862    let cx = bx.cx;
1863    let fn_args = instance.args;
1864
1865    let (target_id, target_args) = match fn_args.into_type_list(tcx)[0].kind() {
1866        ty::FnDef(def_id, params) => (def_id, params),
1867        _ => ::rustc_middle::util::bug::bug_fmt(format_args!("invalid offload intrinsic arg"))bug!("invalid offload intrinsic arg"),
1868    };
1869
1870    let fn_target = match Instance::try_resolve(tcx, cx.typing_env(), *target_id, target_args) {
1871        Ok(Some(instance)) => instance,
1872        Ok(None) => ::rustc_middle::util::bug::bug_fmt(format_args!("could not resolve ({0:?}, {1:?}) to a specific offload instance",
        target_id, target_args))bug!(
1873            "could not resolve ({:?}, {:?}) to a specific offload instance",
1874            target_id,
1875            target_args
1876        ),
1877        Err(_) => {
1878            // An error has already been emitted
1879            return;
1880        }
1881    };
1882
1883    let offload_dims = OffloadKernelDims::from_operands(bx, &args[1], &args[2]);
1884    let args = get_args_from_tuple(bx, args[3], fn_target);
1885    let target_symbol = symbol_name_for_instance_in_crate(tcx, fn_target, LOCAL_CRATE);
1886
1887    let sig = tcx.fn_sig(fn_target.def_id()).skip_binder();
1888    let sig = tcx.instantiate_bound_regions_with_erased(sig);
1889    let inputs = sig.inputs();
1890
1891    let fn_abi = cx.fn_abi_of_instance(fn_target, ty::List::empty());
1892
1893    let mut metadata = Vec::new();
1894    let mut types = Vec::new();
1895
1896    for (i, arg_abi) in fn_abi.args.iter().enumerate() {
1897        let ty = inputs[i];
1898        let decomposed = OffloadMetadata::handle_abi(cx, tcx, ty, arg_abi);
1899
1900        for (meta, entry_ty) in decomposed {
1901            metadata.push(meta);
1902            types.push(bx.cx.layout_of(entry_ty).llvm_type(bx.cx));
1903        }
1904    }
1905
1906    let offload_globals_ref = cx.offload_globals.borrow();
1907    let offload_globals = match offload_globals_ref.as_ref() {
1908        Some(globals) => globals,
1909        None => {
1910            // Offload is not initialized, cannot continue
1911            return;
1912        }
1913    };
1914    register_offload(cx);
1915    let offload_data = gen_define_handling(&cx, &metadata, target_symbol, offload_globals);
1916    gen_call_handling(bx, &offload_data, &args, &types, &metadata, offload_globals, &offload_dims);
1917}
1918
1919fn get_args_from_tuple<'ll, 'tcx>(
1920    bx: &mut Builder<'_, 'll, 'tcx>,
1921    tuple_op: OperandRef<'tcx, &'ll Value>,
1922    fn_instance: Instance<'tcx>,
1923) -> Vec<&'ll Value> {
1924    let cx = bx.cx;
1925    let fn_abi = cx.fn_abi_of_instance(fn_instance, ty::List::empty());
1926
1927    match tuple_op.val {
1928        OperandValue::Immediate(val) => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [val]))vec![val],
1929        OperandValue::Pair(v1, v2) => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [v1, v2]))vec![v1, v2],
1930        OperandValue::Ref(ptr) => {
1931            let tuple_place = PlaceRef { val: ptr, layout: tuple_op.layout };
1932
1933            let mut result = Vec::with_capacity(fn_abi.args.len());
1934            let mut tuple_index = 0;
1935
1936            for arg in &fn_abi.args {
1937                match arg.mode {
1938                    PassMode::Ignore => {}
1939                    PassMode::Direct(_) | PassMode::Cast { .. } => {
1940                        let field = tuple_place.project_field(bx, tuple_index);
1941                        let llvm_ty = field.layout.llvm_type(bx.cx);
1942                        let val = bx.load(llvm_ty, field.val.llval, field.val.align);
1943                        result.push(val);
1944                        tuple_index += 1;
1945                    }
1946                    PassMode::Pair(_, _) => {
1947                        let field = tuple_place.project_field(bx, tuple_index);
1948                        let llvm_ty = field.layout.llvm_type(bx.cx);
1949                        let pair_val = bx.load(llvm_ty, field.val.llval, field.val.align);
1950                        result.push(bx.extract_value(pair_val, 0));
1951                        result.push(bx.extract_value(pair_val, 1));
1952                        tuple_index += 1;
1953                    }
1954                    PassMode::Indirect { .. } => {
1955                        let field = tuple_place.project_field(bx, tuple_index);
1956                        result.push(field.val.llval);
1957                        tuple_index += 1;
1958                    }
1959                }
1960            }
1961
1962            result
1963        }
1964
1965        OperandValue::ZeroSized => ::alloc::vec::Vec::new()vec![],
1966    }
1967}
1968
1969fn generic_simd_intrinsic<'ll, 'tcx>(
1970    bx: &mut Builder<'_, 'll, 'tcx>,
1971    name: Symbol,
1972    fn_args: GenericArgsRef<'tcx>,
1973    args: &[OperandRef<'tcx, &'ll Value>],
1974    ret_ty: Ty<'tcx>,
1975    llret_ty: &'ll Type,
1976    span: Span,
1977) -> Result<&'ll Value, ()> {
1978    macro_rules! return_error {
1979        ($diag: expr) => {{
1980            bx.sess().dcx().emit_err($diag);
1981            return Err(());
1982        }};
1983    }
1984
1985    macro_rules! require {
1986        ($cond: expr, $diag: expr) => {
1987            if !$cond {
1988                return_error!($diag);
1989            }
1990        };
1991    }
1992
1993    macro_rules! require_simd {
1994        ($ty: expr, $variant:ident) => {{
1995            require!($ty.is_simd(), InvalidMonomorphization::$variant { span, name, ty: $ty });
1996            $ty.simd_size_and_type(bx.tcx())
1997        }};
1998    }
1999
2000    macro_rules! require_simd_or_scalable {
2001        ($ty: expr, $variant:ident) => {{
2002            require!(
2003                $ty.is_simd() || $ty.is_scalable_vector(),
2004                InvalidMonomorphization::$variant { span, name, ty: $ty }
2005            );
2006            if $ty.is_simd() {
2007                let (len, ty) = $ty.simd_size_and_type(bx.tcx());
2008                (len, ty, None)
2009            } else {
2010                let (count, ty, num_vecs) =
2011                    $ty.scalable_vector_parts(bx.tcx()).expect("`is_scalable_vector` was wrong");
2012                (count as u64, ty, Some(num_vecs))
2013            }
2014        }};
2015    }
2016
2017    /// Returns the bitwidth of the `$ty` argument if it is an `Int` or `Uint` type.
2018    macro_rules! require_int_or_uint_ty {
2019        ($ty: expr, $diag: expr) => {
2020            match $ty {
2021                ty::Int(i) => {
2022                    i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size().bits())
2023                }
2024                ty::Uint(i) => {
2025                    i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size().bits())
2026                }
2027                _ => {
2028                    return_error!($diag);
2029                }
2030            }
2031        };
2032    }
2033
2034    let llvm_version = crate::llvm_util::get_version();
2035
2036    /// Converts a vector mask, where each element has a bit width equal to the data elements it is used with,
2037    /// down to an i1 based mask that can be used by llvm intrinsics.
2038    ///
2039    /// The rust simd semantics are that each element should either consist of all ones or all zeroes,
2040    /// but this information is not available to llvm. Truncating the vector effectively uses the lowest bit,
2041    /// but codegen for several targets is better if we consider the highest bit by shifting.
2042    ///
2043    /// For x86 SSE/AVX targets this is beneficial since most instructions with mask parameters only consider the highest bit.
2044    /// So even though on llvm level we have an additional shift, in the final assembly there is no shift or truncate and
2045    /// instead the mask can be used as is.
2046    ///
2047    /// For aarch64 and other targets there is a benefit because a mask from the sign bit can be more
2048    /// efficiently converted to an all ones / all zeroes mask by comparing whether each element is negative.
2049    fn vector_mask_to_bitmask<'a, 'll, 'tcx>(
2050        bx: &mut Builder<'a, 'll, 'tcx>,
2051        i_xn: &'ll Value,
2052        in_elem_bitwidth: u64,
2053        in_len: u64,
2054    ) -> &'ll Value {
2055        // Shift the MSB to the right by "in_elem_bitwidth - 1" into the first bit position.
2056        let shift_idx = bx.cx.const_int(bx.type_ix(in_elem_bitwidth), (in_elem_bitwidth - 1) as _);
2057        let shift_indices = ::alloc::vec::from_elem(shift_idx, in_len as _)vec![shift_idx; in_len as _];
2058        let i_xn_msb = bx.lshr(i_xn, bx.const_vector(shift_indices.as_slice()));
2059        // Truncate vector to an <i1 x N>
2060        bx.trunc(i_xn_msb, bx.type_vector(bx.type_i1(), in_len))
2061    }
2062
2063    // Sanity-check: all vector arguments must be immediates.
2064    if truecfg!(debug_assertions) {
2065        for arg in args {
2066            if arg.layout.ty.is_simd() {
2067                {
    match arg.val {
        OperandValue::Immediate(_) => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "OperandValue::Immediate(_)", ::core::option::Option::None);
        }
    }
};assert_matches!(arg.val, OperandValue::Immediate(_));
2068            }
2069        }
2070    }
2071
2072    if name == sym::simd_select_bitmask {
2073        let (len, _) = {
    if !args[1].layout.ty.is_simd() {
        {
            bx.sess().dcx().emit_err(InvalidMonomorphization::SimdArgument {
                    span,
                    name,
                    ty: args[1].layout.ty,
                });
            return Err(());
        };
    };
    args[1].layout.ty.simd_size_and_type(bx.tcx())
}require_simd!(args[1].layout.ty, SimdArgument);
2074
2075        let expected_int_bits = len.max(8).next_power_of_two();
2076        let expected_bytes = len.div_ceil(8);
2077
2078        let mask_ty = args[0].layout.ty;
2079        let mask = match mask_ty.kind() {
2080            ty::Int(i) if i.bit_width() == Some(expected_int_bits) => args[0].immediate(),
2081            ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => args[0].immediate(),
2082            ty::Array(elem, len)
2083                if #[allow(non_exhaustive_omitted_patterns)] match elem.kind() {
    ty::Uint(ty::UintTy::U8) => true,
    _ => false,
}matches!(elem.kind(), ty::Uint(ty::UintTy::U8))
2084                    && len
2085                        .try_to_target_usize(bx.tcx)
2086                        .expect("expected monomorphic const in codegen")
2087                        == expected_bytes =>
2088            {
2089                let place = PlaceRef::alloca(bx, args[0].layout);
2090                args[0].val.store(bx, place);
2091                let int_ty = bx.type_ix(expected_bytes * 8);
2092                bx.load(int_ty, place.val.llval, Align::ONE)
2093            }
2094            _ => {
    bx.sess().dcx().emit_err(InvalidMonomorphization::InvalidBitmask {
            span,
            name,
            mask_ty,
            expected_int_bits,
            expected_bytes,
        });
    return Err(());
}return_error!(InvalidMonomorphization::InvalidBitmask {
2095                span,
2096                name,
2097                mask_ty,
2098                expected_int_bits,
2099                expected_bytes
2100            }),
2101        };
2102
2103        let i1 = bx.type_i1();
2104        let im = bx.type_ix(len);
2105        let i1xn = bx.type_vector(i1, len);
2106        let m_im = bx.trunc(mask, im);
2107        let m_i1s = bx.bitcast(m_im, i1xn);
2108        return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
2109    }
2110
2111    if name == sym::simd_splat {
2112        let (out_len, out_ty) = {
    if !ret_ty.is_simd() {
        {
            bx.sess().dcx().emit_err(InvalidMonomorphization::SimdReturn {
                    span,
                    name,
                    ty: ret_ty,
                });
            return Err(());
        };
    };
    ret_ty.simd_size_and_type(bx.tcx())
}require_simd!(ret_ty, SimdReturn);
2113
2114        if !(args[0].layout.ty == out_ty) {
    {
        bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedVectorElementType {
                span,
                name,
                expected_element: out_ty,
                vector_type: ret_ty,
            });
        return Err(());
    };
};require!(
2115            args[0].layout.ty == out_ty,
2116            InvalidMonomorphization::ExpectedVectorElementType {
2117                span,
2118                name,
2119                expected_element: out_ty,
2120                vector_type: ret_ty,
2121            }
2122        );
2123
2124        // `insertelement <N x elem> poison, elem %x, i32 0`
2125        let poison_vec = bx.const_poison(llret_ty);
2126        let idx0 = bx.const_i32(0);
2127        let v0 = bx.insert_element(poison_vec, args[0].immediate(), idx0);
2128
2129        // `shufflevector <N x elem> v0, <N x elem> poison, <N x i32> zeroinitializer`
2130        // The masks is all zeros, so this splats lane 0 (which has our element in it).
2131        let mask_ty = bx.type_vector(bx.type_i32(), out_len);
2132        let splat = bx.shuffle_vector(v0, poison_vec, bx.const_null(mask_ty));
2133
2134        return Ok(splat);
2135    }
2136
2137    let supports_scalable = match name {
2138        sym::simd_cast | sym::simd_select => true,
2139        _ => false,
2140    };
2141
2142    // Every intrinsic below takes a SIMD vector as its first argument. Some intrinsics also accept
2143    // scalable vectors. `require_simd_or_scalable` is used regardless as it'll do the right thing
2144    // for non-scalable vectors, and an additional check to prohibit scalable vectors for those
2145    // intrinsics that do not support them is added.
2146    if !supports_scalable {
2147        let _ = {
    if !args[0].layout.ty.is_simd() {
        {
            bx.sess().dcx().emit_err(InvalidMonomorphization::SimdInput {
                    span,
                    name,
                    ty: args[0].layout.ty,
                });
            return Err(());
        };
    };
    args[0].layout.ty.simd_size_and_type(bx.tcx())
}require_simd!(args[0].layout.ty, SimdInput);
2148    }
2149    let (in_len, in_elem, in_num_vecs) = {
    if !(args[0].layout.ty.is_simd() ||
                args[0].layout.ty.is_scalable_vector()) {
        {
            bx.sess().dcx().emit_err(InvalidMonomorphization::SimdInput {
                    span,
                    name,
                    ty: args[0].layout.ty,
                });
            return Err(());
        };
    };
    if args[0].layout.ty.is_simd() {
        let (len, ty) = args[0].layout.ty.simd_size_and_type(bx.tcx());
        (len, ty, None)
    } else {
        let (count, ty, num_vecs) =
            args[0].layout.ty.scalable_vector_parts(bx.tcx()).expect("`is_scalable_vector` was wrong");
        (count as u64, ty, Some(num_vecs))
    }
}require_simd_or_scalable!(args[0].layout.ty, SimdInput);
2150    let in_ty = args[0].layout.ty;
2151
2152    let comparison = match name {
2153        sym::simd_eq => Some(BinOp::Eq),
2154        sym::simd_ne => Some(BinOp::Ne),
2155        sym::simd_lt => Some(BinOp::Lt),
2156        sym::simd_le => Some(BinOp::Le),
2157        sym::simd_gt => Some(BinOp::Gt),
2158        sym::simd_ge => Some(BinOp::Ge),
2159        _ => None,
2160    };
2161
2162    if let Some(cmp_op) = comparison {
2163        let (out_len, out_ty) = {
    if !ret_ty.is_simd() {
        {
            bx.sess().dcx().emit_err(InvalidMonomorphization::SimdReturn {
                    span,
                    name,
                    ty: ret_ty,
                });
            return Err(());
        };
    };
    ret_ty.simd_size_and_type(bx.tcx())
}require_simd!(ret_ty, SimdReturn);
2164
2165        if !(in_len == out_len) {
    {
        bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnLengthInputType {
                span,
                name,
                in_len,
                in_ty,
                ret_ty,
                out_len,
            });
        return Err(());
    };
};require!(
2166            in_len == out_len,
2167            InvalidMonomorphization::ReturnLengthInputType {
2168                span,
2169                name,
2170                in_len,
2171                in_ty,
2172                ret_ty,
2173                out_len
2174            }
2175        );
2176        if !(bx.type_kind(bx.element_type(llret_ty)) == TypeKind::Integer) {
    {
        bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnIntegerType {
                span,
                name,
                ret_ty,
                out_ty,
            });
        return Err(());
    };
};require!(
2177            bx.type_kind(bx.element_type(llret_ty)) == TypeKind::Integer,
2178            InvalidMonomorphization::ReturnIntegerType { span, name, ret_ty, out_ty }
2179        );
2180
2181        return Ok(compare_simd_types(
2182            bx,
2183            args[0].immediate(),
2184            args[1].immediate(),
2185            in_elem,
2186            llret_ty,
2187            cmp_op,
2188        ));
2189    }
2190
2191    if name == sym::simd_shuffle_const_generic {
2192        let idx = fn_args[2].expect_const().to_branch();
2193        let n = idx.len() as u64;
2194
2195        let (out_len, out_ty) = {
    if !ret_ty.is_simd() {
        {
            bx.sess().dcx().emit_err(InvalidMonomorphization::SimdReturn {
                    span,
                    name,
                    ty: ret_ty,
                });
            return Err(());
        };
    };
    ret_ty.simd_size_and_type(bx.tcx())
}require_simd!(ret_ty, SimdReturn);
2196        if !(out_len == n) {
    {
        bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnLength {
                span,
                name,
                in_len: n,
                ret_ty,
                out_len,
            });
        return Err(());
    };
};require!(
2197            out_len == n,
2198            InvalidMonomorphization::ReturnLength { span, name, in_len: n, ret_ty, out_len }
2199        );
2200        if !(in_elem == out_ty) {
    {
        bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnElement {
                span,
                name,
                in_elem,
                in_ty,
                ret_ty,
                out_ty,
            });
        return Err(());
    };
};require!(
2201            in_elem == out_ty,
2202            InvalidMonomorphization::ReturnElement { span, name, in_elem, in_ty, ret_ty, out_ty }
2203        );
2204
2205        let total_len = in_len * 2;
2206
2207        let indices: Option<Vec<_>> = idx
2208            .iter()
2209            .enumerate()
2210            .map(|(arg_idx, val)| {
2211                let idx = val.to_leaf().to_i32();
2212                if idx >= i32::try_from(total_len).unwrap() {
2213                    bx.sess().dcx().emit_err(InvalidMonomorphization::SimdIndexOutOfBounds {
2214                        span,
2215                        name,
2216                        arg_idx: arg_idx as u64,
2217                        total_len: total_len.into(),
2218                    });
2219                    None
2220                } else {
2221                    Some(bx.const_i32(idx))
2222                }
2223            })
2224            .collect();
2225        let Some(indices) = indices else {
2226            return Ok(bx.const_null(llret_ty));
2227        };
2228
2229        return Ok(bx.shuffle_vector(
2230            args[0].immediate(),
2231            args[1].immediate(),
2232            bx.const_vector(&indices),
2233        ));
2234    }
2235
2236    if name == sym::simd_shuffle {
2237        // Make sure this is actually a SIMD vector.
2238        let idx_ty = args[2].layout.ty;
2239        let n: u64 = if idx_ty.is_simd()
2240            && #[allow(non_exhaustive_omitted_patterns)] match idx_ty.simd_size_and_type(bx.cx.tcx).1.kind()
    {
    ty::Uint(ty::UintTy::U32) => true,
    _ => false,
}matches!(idx_ty.simd_size_and_type(bx.cx.tcx).1.kind(), ty::Uint(ty::UintTy::U32))
2241        {
2242            idx_ty.simd_size_and_type(bx.cx.tcx).0
2243        } else {
2244            {
    bx.sess().dcx().emit_err(InvalidMonomorphization::SimdShuffle {
            span,
            name,
            ty: idx_ty,
        });
    return Err(());
}return_error!(InvalidMonomorphization::SimdShuffle { span, name, ty: idx_ty })
2245        };
2246
2247        let (out_len, out_ty) = {
    if !ret_ty.is_simd() {
        {
            bx.sess().dcx().emit_err(InvalidMonomorphization::SimdReturn {
                    span,
                    name,
                    ty: ret_ty,
                });
            return Err(());
        };
    };
    ret_ty.simd_size_and_type(bx.tcx())
}require_simd!(ret_ty, SimdReturn);
2248        if !(out_len == n) {
    {
        bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnLength {
                span,
                name,
                in_len: n,
                ret_ty,
                out_len,
            });
        return Err(());
    };
};require!(
2249            out_len == n,
2250            InvalidMonomorphization::ReturnLength { span, name, in_len: n, ret_ty, out_len }
2251        );
2252        if !(in_elem == out_ty) {
    {
        bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnElement {
                span,
                name,
                in_elem,
                in_ty,
                ret_ty,
                out_ty,
            });
        return Err(());
    };
};require!(
2253            in_elem == out_ty,
2254            InvalidMonomorphization::ReturnElement { span, name, in_elem, in_ty, ret_ty, out_ty }
2255        );
2256
2257        let total_len = u128::from(in_len) * 2;
2258
2259        // Check that the indices are in-bounds.
2260        let indices = args[2].immediate();
2261        for i in 0..n {
2262            let val = bx.const_get_elt(indices, i as u64);
2263            let idx = bx
2264                .const_to_opt_u128(val, true)
2265                .unwrap_or_else(|| ::rustc_middle::util::bug::bug_fmt(format_args!("typeck should have already ensured that these are const"))bug!("typeck should have already ensured that these are const"));
2266            if idx >= total_len {
2267                {
    bx.sess().dcx().emit_err(InvalidMonomorphization::SimdIndexOutOfBounds {
            span,
            name,
            arg_idx: i,
            total_len,
        });
    return Err(());
};return_error!(InvalidMonomorphization::SimdIndexOutOfBounds {
2268                    span,
2269                    name,
2270                    arg_idx: i,
2271                    total_len,
2272                });
2273            }
2274        }
2275
2276        return Ok(bx.shuffle_vector(args[0].immediate(), args[1].immediate(), indices));
2277    }
2278
2279    if name == sym::simd_insert || name == sym::simd_insert_dyn {
2280        if !(in_elem == args[2].layout.ty) {
    {
        bx.sess().dcx().emit_err(InvalidMonomorphization::InsertedType {
                span,
                name,
                in_elem,
                in_ty,
                out_ty: args[2].layout.ty,
            });
        return Err(());
    };
};require!(
2281            in_elem == args[2].layout.ty,
2282            InvalidMonomorphization::InsertedType {
2283                span,
2284                name,
2285                in_elem,
2286                in_ty,
2287                out_ty: args[2].layout.ty
2288            }
2289        );
2290
2291        let index_imm = if name == sym::simd_insert {
2292            let idx = bx
2293                .const_to_opt_u128(args[1].immediate(), false)
2294                .expect("typeck should have ensure that this is a const");
2295            if idx >= in_len.into() {
2296                {
    bx.sess().dcx().emit_err(InvalidMonomorphization::SimdIndexOutOfBounds {
            span,
            name,
            arg_idx: 1,
            total_len: in_len.into(),
        });
    return Err(());
};return_error!(InvalidMonomorphization::SimdIndexOutOfBounds {
2297                    span,
2298                    name,
2299                    arg_idx: 1,
2300                    total_len: in_len.into(),
2301                });
2302            }
2303            bx.const_i32(idx as i32)
2304        } else {
2305            args[1].immediate()
2306        };
2307
2308        return Ok(bx.insert_element(args[0].immediate(), args[2].immediate(), index_imm));
2309    }
2310    if name == sym::simd_extract || name == sym::simd_extract_dyn {
2311        if !(ret_ty == in_elem) {
    {
        bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                span,
                name,
                in_elem,
                in_ty,
                ret_ty,
            });
        return Err(());
    };
};require!(
2312            ret_ty == in_elem,
2313            InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty }
2314        );
2315        let index_imm = if name == sym::simd_extract {
2316            let idx = bx
2317                .const_to_opt_u128(args[1].immediate(), false)
2318                .expect("typeck should have ensure that this is a const");
2319            if idx >= in_len.into() {
2320                {
    bx.sess().dcx().emit_err(InvalidMonomorphization::SimdIndexOutOfBounds {
            span,
            name,
            arg_idx: 1,
            total_len: in_len.into(),
        });
    return Err(());
};return_error!(InvalidMonomorphization::SimdIndexOutOfBounds {
2321                    span,
2322                    name,
2323                    arg_idx: 1,
2324                    total_len: in_len.into(),
2325                });
2326            }
2327            bx.const_i32(idx as i32)
2328        } else {
2329            args[1].immediate()
2330        };
2331
2332        return Ok(bx.extract_element(args[0].immediate(), index_imm));
2333    }
2334
2335    if name == sym::simd_select {
2336        let m_elem_ty = in_elem;
2337        let m_len = in_len;
2338        let (v_len, _, _) = {
    if !(args[1].layout.ty.is_simd() ||
                args[1].layout.ty.is_scalable_vector()) {
        {
            bx.sess().dcx().emit_err(InvalidMonomorphization::SimdArgument {
                    span,
                    name,
                    ty: args[1].layout.ty,
                });
            return Err(());
        };
    };
    if args[1].layout.ty.is_simd() {
        let (len, ty) = args[1].layout.ty.simd_size_and_type(bx.tcx());
        (len, ty, None)
    } else {
        let (count, ty, num_vecs) =
            args[1].layout.ty.scalable_vector_parts(bx.tcx()).expect("`is_scalable_vector` was wrong");
        (count as u64, ty, Some(num_vecs))
    }
}require_simd_or_scalable!(args[1].layout.ty, SimdArgument);
2339        if !(m_len == v_len) {
    {
        bx.sess().dcx().emit_err(InvalidMonomorphization::MismatchedLengths {
                span,
                name,
                m_len,
                v_len,
            });
        return Err(());
    };
};require!(
2340            m_len == v_len,
2341            InvalidMonomorphization::MismatchedLengths { span, name, m_len, v_len }
2342        );
2343
2344        let m_i1s = if args[1].layout.ty.is_scalable_vector() {
2345            match m_elem_ty.kind() {
2346                ty::Bool => {}
2347                _ => {
    bx.sess().dcx().emit_err(InvalidMonomorphization::MaskWrongElementType {
            span,
            name,
            ty: m_elem_ty,
        });
    return Err(());
}return_error!(InvalidMonomorphization::MaskWrongElementType {
2348                    span,
2349                    name,
2350                    ty: m_elem_ty
2351                }),
2352            };
2353            let i1 = bx.type_i1();
2354            let i1xn = bx.type_scalable_vector(i1, m_len as u64);
2355            bx.trunc(args[0].immediate(), i1xn)
2356        } else {
2357            let in_elem_bitwidth = match m_elem_ty.kind() {
    ty::Int(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    ty::Uint(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    _ => {
        {
            bx.sess().dcx().emit_err(InvalidMonomorphization::MaskWrongElementType {
                    span,
                    name,
                    ty: m_elem_ty,
                });
            return Err(());
        };
    }
}require_int_or_uint_ty!(
2358                m_elem_ty.kind(),
2359                InvalidMonomorphization::MaskWrongElementType { span, name, ty: m_elem_ty }
2360            );
2361            vector_mask_to_bitmask(bx, args[0].immediate(), in_elem_bitwidth, m_len)
2362        };
2363
2364        return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
2365    }
2366
2367    if name == sym::simd_bitmask {
2368        // The `fn simd_bitmask(vector) -> unsigned integer` intrinsic takes a vector mask and
2369        // returns one bit for each lane (which must all be `0` or `!0`) in the form of either:
2370        // * an unsigned integer
2371        // * an array of `u8`
2372        // If the vector has less than 8 lanes, a u8 is returned with zeroed trailing bits.
2373        //
2374        // The bit order of the result depends on the byte endianness, LSB-first for little
2375        // endian and MSB-first for big endian.
2376        let expected_int_bits = in_len.max(8).next_power_of_two();
2377        let expected_bytes = in_len.div_ceil(8);
2378
2379        // Integer vector <i{in_bitwidth} x in_len>:
2380        let in_elem_bitwidth = match in_elem.kind() {
    ty::Int(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    ty::Uint(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    _ => {
        {
            bx.sess().dcx().emit_err(InvalidMonomorphization::MaskWrongElementType {
                    span,
                    name,
                    ty: in_elem,
                });
            return Err(());
        };
    }
}require_int_or_uint_ty!(
2381            in_elem.kind(),
2382            InvalidMonomorphization::MaskWrongElementType { span, name, ty: in_elem }
2383        );
2384
2385        let i1xn = vector_mask_to_bitmask(bx, args[0].immediate(), in_elem_bitwidth, in_len);
2386        // Bitcast <i1 x N> to iN:
2387        let i_ = bx.bitcast(i1xn, bx.type_ix(in_len));
2388
2389        match ret_ty.kind() {
2390            ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => {
2391                // Zero-extend iN to the bitmask type:
2392                return Ok(bx.zext(i_, bx.type_ix(expected_int_bits)));
2393            }
2394            ty::Array(elem, len)
2395                if #[allow(non_exhaustive_omitted_patterns)] match elem.kind() {
    ty::Uint(ty::UintTy::U8) => true,
    _ => false,
}matches!(elem.kind(), ty::Uint(ty::UintTy::U8))
2396                    && len
2397                        .try_to_target_usize(bx.tcx)
2398                        .expect("expected monomorphic const in codegen")
2399                        == expected_bytes =>
2400            {
2401                // Zero-extend iN to the array length:
2402                let ze = bx.zext(i_, bx.type_ix(expected_bytes * 8));
2403
2404                // Convert the integer to a byte array
2405                let ptr = bx.alloca(Size::from_bytes(expected_bytes), Align::ONE);
2406                bx.store(ze, ptr, Align::ONE);
2407                let array_ty = bx.type_array(bx.type_i8(), expected_bytes);
2408                return Ok(bx.load(array_ty, ptr, Align::ONE));
2409            }
2410            _ => {
    bx.sess().dcx().emit_err(InvalidMonomorphization::CannotReturn {
            span,
            name,
            ret_ty,
            expected_int_bits,
            expected_bytes,
        });
    return Err(());
}return_error!(InvalidMonomorphization::CannotReturn {
2411                span,
2412                name,
2413                ret_ty,
2414                expected_int_bits,
2415                expected_bytes
2416            }),
2417        }
2418    }
2419
2420    fn simd_simple_float_intrinsic<'ll, 'tcx>(
2421        name: Symbol,
2422        in_elem: Ty<'_>,
2423        in_ty: Ty<'_>,
2424        in_len: u64,
2425        bx: &mut Builder<'_, 'll, 'tcx>,
2426        span: Span,
2427        args: &[OperandRef<'tcx, &'ll Value>],
2428    ) -> Result<&'ll Value, ()> {
2429        macro_rules! return_error {
2430            ($diag: expr) => {{
2431                bx.sess().dcx().emit_err($diag);
2432                return Err(());
2433            }};
2434        }
2435
2436        let ty::Float(f) = in_elem.kind() else {
2437            {
    bx.sess().dcx().emit_err(InvalidMonomorphization::BasicFloatType {
            span,
            name,
            ty: in_ty,
        });
    return Err(());
};return_error!(InvalidMonomorphization::BasicFloatType { span, name, ty: in_ty });
2438        };
2439        let elem_ty = bx.cx.type_float_from_ty(*f);
2440
2441        let vec_ty = bx.type_vector(elem_ty, in_len);
2442
2443        let intr_name = match name {
2444            sym::simd_ceil => "llvm.ceil",
2445            sym::simd_fabs => "llvm.fabs",
2446            sym::simd_fcos => "llvm.cos",
2447            sym::simd_fexp2 => "llvm.exp2",
2448            sym::simd_fexp => "llvm.exp",
2449            sym::simd_flog10 => "llvm.log10",
2450            sym::simd_flog2 => "llvm.log2",
2451            sym::simd_flog => "llvm.log",
2452            sym::simd_floor => "llvm.floor",
2453            sym::simd_fma => "llvm.fma",
2454            sym::simd_relaxed_fma => "llvm.fmuladd",
2455            sym::simd_fsin => "llvm.sin",
2456            sym::simd_fsqrt => "llvm.sqrt",
2457            sym::simd_round => "llvm.round",
2458            sym::simd_round_ties_even => "llvm.rint",
2459            sym::simd_trunc => "llvm.trunc",
2460            _ => {
    bx.sess().dcx().emit_err(InvalidMonomorphization::UnrecognizedIntrinsic {
            span,
            name,
        });
    return Err(());
}return_error!(InvalidMonomorphization::UnrecognizedIntrinsic { span, name }),
2461        };
2462        Ok(bx.call_intrinsic(
2463            intr_name,
2464            &[vec_ty],
2465            &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
2466        ))
2467    }
2468
2469    if #[allow(non_exhaustive_omitted_patterns)] match name {
    sym::simd_ceil | sym::simd_fabs | sym::simd_fcos | sym::simd_fexp2 |
        sym::simd_fexp | sym::simd_flog10 | sym::simd_flog2 | sym::simd_flog |
        sym::simd_floor | sym::simd_fma | sym::simd_fsin | sym::simd_fsqrt |
        sym::simd_relaxed_fma | sym::simd_round | sym::simd_round_ties_even |
        sym::simd_trunc => true,
    _ => false,
}std::matches!(
2470        name,
2471        sym::simd_ceil
2472            | sym::simd_fabs
2473            | sym::simd_fcos
2474            | sym::simd_fexp2
2475            | sym::simd_fexp
2476            | sym::simd_flog10
2477            | sym::simd_flog2
2478            | sym::simd_flog
2479            | sym::simd_floor
2480            | sym::simd_fma
2481            | sym::simd_fsin
2482            | sym::simd_fsqrt
2483            | sym::simd_relaxed_fma
2484            | sym::simd_round
2485            | sym::simd_round_ties_even
2486            | sym::simd_trunc
2487    ) {
2488        return simd_simple_float_intrinsic(name, in_elem, in_ty, in_len, bx, span, args);
2489    }
2490
2491    fn llvm_vector_ty<'ll>(cx: &CodegenCx<'ll, '_>, elem_ty: Ty<'_>, vec_len: u64) -> &'ll Type {
2492        let elem_ty = match *elem_ty.kind() {
2493            ty::Int(v) => cx.type_int_from_ty(v),
2494            ty::Uint(v) => cx.type_uint_from_ty(v),
2495            ty::Float(v) => cx.type_float_from_ty(v),
2496            ty::RawPtr(_, _) => cx.type_ptr(),
2497            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
2498        };
2499        cx.type_vector(elem_ty, vec_len)
2500    }
2501
2502    if name == sym::simd_gather {
2503        // simd_gather(values: <N x T>, pointers: <N x *_ T>,
2504        //             mask: <N x i{M}>) -> <N x T>
2505        // * N: number of elements in the input vectors
2506        // * T: type of the element to load
2507        // * M: any integer width is supported, will be truncated to i1
2508
2509        // All types must be simd vector types
2510
2511        // The second argument must be a simd vector with an element type that's a pointer
2512        // to the element type of the first argument
2513        let (_, element_ty0) = {
    if !in_ty.is_simd() {
        {
            bx.sess().dcx().emit_err(InvalidMonomorphization::SimdFirst {
                    span,
                    name,
                    ty: in_ty,
                });
            return Err(());
        };
    };
    in_ty.simd_size_and_type(bx.tcx())
}require_simd!(in_ty, SimdFirst);
2514        let (out_len, element_ty1) = {
    if !args[1].layout.ty.is_simd() {
        {
            bx.sess().dcx().emit_err(InvalidMonomorphization::SimdSecond {
                    span,
                    name,
                    ty: args[1].layout.ty,
                });
            return Err(());
        };
    };
    args[1].layout.ty.simd_size_and_type(bx.tcx())
}require_simd!(args[1].layout.ty, SimdSecond);
2515        // The element type of the third argument must be a signed integer type of any width:
2516        let (out_len2, element_ty2) = {
    if !args[2].layout.ty.is_simd() {
        {
            bx.sess().dcx().emit_err(InvalidMonomorphization::SimdThird {
                    span,
                    name,
                    ty: args[2].layout.ty,
                });
            return Err(());
        };
    };
    args[2].layout.ty.simd_size_and_type(bx.tcx())
}require_simd!(args[2].layout.ty, SimdThird);
2517        {
    if !ret_ty.is_simd() {
        {
            bx.sess().dcx().emit_err(InvalidMonomorphization::SimdReturn {
                    span,
                    name,
                    ty: ret_ty,
                });
            return Err(());
        };
    };
    ret_ty.simd_size_and_type(bx.tcx())
};require_simd!(ret_ty, SimdReturn);
2518
2519        // Of the same length:
2520        if !(in_len == out_len) {
    {
        bx.sess().dcx().emit_err(InvalidMonomorphization::SecondArgumentLength {
                span,
                name,
                in_len,
                in_ty,
                arg_ty: args[1].layout.ty,
                out_len,
            });
        return Err(());
    };
};require!(
2521            in_len == out_len,
2522            InvalidMonomorphization::SecondArgumentLength {
2523                span,
2524                name,
2525                in_len,
2526                in_ty,
2527                arg_ty: args[1].layout.ty,
2528                out_len
2529            }
2530        );
2531        if !(in_len == out_len2) {
    {
        bx.sess().dcx().emit_err(InvalidMonomorphization::ThirdArgumentLength {
                span,
                name,
                in_len,
                in_ty,
                arg_ty: args[2].layout.ty,
                out_len: out_len2,
            });
        return Err(());
    };
};require!(
2532            in_len == out_len2,
2533            InvalidMonomorphization::ThirdArgumentLength {
2534                span,
2535                name,
2536                in_len,
2537                in_ty,
2538                arg_ty: args[2].layout.ty,
2539                out_len: out_len2
2540            }
2541        );
2542
2543        // The return type must match the first argument type
2544        if !(ret_ty == in_ty) {
    {
        bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedReturnType {
                span,
                name,
                in_ty,
                ret_ty,
            });
        return Err(());
    };
};require!(
2545            ret_ty == in_ty,
2546            InvalidMonomorphization::ExpectedReturnType { span, name, in_ty, ret_ty }
2547        );
2548
2549        if !#[allow(non_exhaustive_omitted_patterns)] match *element_ty1.kind() {
            ty::RawPtr(p_ty, _) if
                p_ty == in_elem && p_ty.kind() == element_ty0.kind() => true,
            _ => false,
        } {
    {
        bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedElementType {
                span,
                name,
                expected_element: element_ty1,
                second_arg: args[1].layout.ty,
                in_elem,
                in_ty,
                mutability: ExpectedPointerMutability::Not,
            });
        return Err(());
    };
};require!(
2550            matches!(
2551                *element_ty1.kind(),
2552                ty::RawPtr(p_ty, _) if p_ty == in_elem && p_ty.kind() == element_ty0.kind()
2553            ),
2554            InvalidMonomorphization::ExpectedElementType {
2555                span,
2556                name,
2557                expected_element: element_ty1,
2558                second_arg: args[1].layout.ty,
2559                in_elem,
2560                in_ty,
2561                mutability: ExpectedPointerMutability::Not,
2562            }
2563        );
2564
2565        let mask_elem_bitwidth = match element_ty2.kind() {
    ty::Int(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    ty::Uint(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    _ => {
        {
            bx.sess().dcx().emit_err(InvalidMonomorphization::MaskWrongElementType {
                    span,
                    name,
                    ty: element_ty2,
                });
            return Err(());
        };
    }
}require_int_or_uint_ty!(
2566            element_ty2.kind(),
2567            InvalidMonomorphization::MaskWrongElementType { span, name, ty: element_ty2 }
2568        );
2569
2570        // Alignment of T, must be a constant integer value:
2571        let alignment = bx.align_of(in_elem).bytes();
2572
2573        // Truncate the mask vector to a vector of i1s:
2574        let mask = vector_mask_to_bitmask(bx, args[2].immediate(), mask_elem_bitwidth, in_len);
2575
2576        // Type of the vector of pointers:
2577        let llvm_pointer_vec_ty = llvm_vector_ty(bx, element_ty1, in_len);
2578
2579        // Type of the vector of elements:
2580        let llvm_elem_vec_ty = llvm_vector_ty(bx, element_ty0, in_len);
2581
2582        let args: &[&'ll Value] = if llvm_version < (22, 0, 0) {
2583            let alignment = bx.const_i32(alignment as i32);
2584            &[args[1].immediate(), alignment, mask, args[0].immediate()]
2585        } else {
2586            &[args[1].immediate(), mask, args[0].immediate()]
2587        };
2588
2589        let call =
2590            bx.call_intrinsic("llvm.masked.gather", &[llvm_elem_vec_ty, llvm_pointer_vec_ty], args);
2591        if llvm_version >= (22, 0, 0) {
2592            crate::attributes::apply_to_callsite(
2593                call,
2594                crate::llvm::AttributePlace::Argument(0),
2595                &[crate::llvm::CreateAlignmentAttr(bx.llcx, alignment)],
2596            )
2597        }
2598        return Ok(call);
2599    }
2600
2601    fn llvm_alignment<'ll, 'tcx>(
2602        bx: &mut Builder<'_, 'll, 'tcx>,
2603        alignment: SimdAlign,
2604        vector_ty: Ty<'tcx>,
2605        element_ty: Ty<'tcx>,
2606    ) -> u64 {
2607        match alignment {
2608            SimdAlign::Unaligned => 1,
2609            SimdAlign::Element => bx.align_of(element_ty).bytes(),
2610            SimdAlign::Vector => bx.align_of(vector_ty).bytes(),
2611        }
2612    }
2613
2614    if name == sym::simd_masked_load {
2615        // simd_masked_load<_, _, _, const ALIGN: SimdAlign>(mask: <N x i{M}>, pointer: *_ T, values: <N x T>) -> <N x T>
2616        // * N: number of elements in the input vectors
2617        // * T: type of the element to load
2618        // * M: any integer width is supported, will be truncated to i1
2619        // Loads contiguous elements from memory behind `pointer`, but only for
2620        // those lanes whose `mask` bit is enabled.
2621        // The memory addresses corresponding to the “off” lanes are not accessed.
2622
2623        let alignment = fn_args[3].expect_const().to_branch()[0].to_leaf().to_simd_alignment();
2624
2625        // The element type of the "mask" argument must be a signed integer type of any width
2626        let mask_ty = in_ty;
2627        let (mask_len, mask_elem) = (in_len, in_elem);
2628
2629        // The second argument must be a pointer matching the element type
2630        let pointer_ty = args[1].layout.ty;
2631
2632        // The last argument is a passthrough vector providing values for disabled lanes
2633        let values_ty = args[2].layout.ty;
2634        let (values_len, values_elem) = {
    if !values_ty.is_simd() {
        {
            bx.sess().dcx().emit_err(InvalidMonomorphization::SimdThird {
                    span,
                    name,
                    ty: values_ty,
                });
            return Err(());
        };
    };
    values_ty.simd_size_and_type(bx.tcx())
}require_simd!(values_ty, SimdThird);
2635
2636        {
    if !ret_ty.is_simd() {
        {
            bx.sess().dcx().emit_err(InvalidMonomorphization::SimdReturn {
                    span,
                    name,
                    ty: ret_ty,
                });
            return Err(());
        };
    };
    ret_ty.simd_size_and_type(bx.tcx())
};require_simd!(ret_ty, SimdReturn);
2637
2638        // Of the same length:
2639        if !(values_len == mask_len) {
    {
        bx.sess().dcx().emit_err(InvalidMonomorphization::ThirdArgumentLength {
                span,
                name,
                in_len: mask_len,
                in_ty: mask_ty,
                arg_ty: values_ty,
                out_len: values_len,
            });
        return Err(());
    };
};require!(
2640            values_len == mask_len,
2641            InvalidMonomorphization::ThirdArgumentLength {
2642                span,
2643                name,
2644                in_len: mask_len,
2645                in_ty: mask_ty,
2646                arg_ty: values_ty,
2647                out_len: values_len
2648            }
2649        );
2650
2651        // The return type must match the last argument type
2652        if !(ret_ty == values_ty) {
    {
        bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedReturnType {
                span,
                name,
                in_ty: values_ty,
                ret_ty,
            });
        return Err(());
    };
};require!(
2653            ret_ty == values_ty,
2654            InvalidMonomorphization::ExpectedReturnType { span, name, in_ty: values_ty, ret_ty }
2655        );
2656
2657        if !#[allow(non_exhaustive_omitted_patterns)] match *pointer_ty.kind() {
            ty::RawPtr(p_ty, _) if
                p_ty == values_elem && p_ty.kind() == values_elem.kind() =>
                true,
            _ => false,
        } {
    {
        bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedElementType {
                span,
                name,
                expected_element: values_elem,
                second_arg: pointer_ty,
                in_elem: values_elem,
                in_ty: values_ty,
                mutability: ExpectedPointerMutability::Not,
            });
        return Err(());
    };
};require!(
2658            matches!(
2659                *pointer_ty.kind(),
2660                ty::RawPtr(p_ty, _) if p_ty == values_elem && p_ty.kind() == values_elem.kind()
2661            ),
2662            InvalidMonomorphization::ExpectedElementType {
2663                span,
2664                name,
2665                expected_element: values_elem,
2666                second_arg: pointer_ty,
2667                in_elem: values_elem,
2668                in_ty: values_ty,
2669                mutability: ExpectedPointerMutability::Not,
2670            }
2671        );
2672
2673        let m_elem_bitwidth = match mask_elem.kind() {
    ty::Int(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    ty::Uint(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    _ => {
        {
            bx.sess().dcx().emit_err(InvalidMonomorphization::MaskWrongElementType {
                    span,
                    name,
                    ty: mask_elem,
                });
            return Err(());
        };
    }
}require_int_or_uint_ty!(
2674            mask_elem.kind(),
2675            InvalidMonomorphization::MaskWrongElementType { span, name, ty: mask_elem }
2676        );
2677
2678        let mask = vector_mask_to_bitmask(bx, args[0].immediate(), m_elem_bitwidth, mask_len);
2679
2680        // Alignment of T, must be a constant integer value:
2681        let alignment = llvm_alignment(bx, alignment, values_ty, values_elem);
2682
2683        let llvm_pointer = bx.type_ptr();
2684
2685        // Type of the vector of elements:
2686        let llvm_elem_vec_ty = llvm_vector_ty(bx, values_elem, values_len);
2687
2688        let args: &[&'ll Value] = if llvm_version < (22, 0, 0) {
2689            let alignment = bx.const_i32(alignment as i32);
2690
2691            &[args[1].immediate(), alignment, mask, args[2].immediate()]
2692        } else {
2693            &[args[1].immediate(), mask, args[2].immediate()]
2694        };
2695
2696        let call = bx.call_intrinsic("llvm.masked.load", &[llvm_elem_vec_ty, llvm_pointer], args);
2697        if llvm_version >= (22, 0, 0) {
2698            crate::attributes::apply_to_callsite(
2699                call,
2700                crate::llvm::AttributePlace::Argument(0),
2701                &[crate::llvm::CreateAlignmentAttr(bx.llcx, alignment)],
2702            )
2703        }
2704        return Ok(call);
2705    }
2706
2707    if name == sym::simd_masked_store {
2708        // simd_masked_store<_, _, _, const ALIGN: SimdAlign>(mask: <N x i{M}>, pointer: *mut T, values: <N x T>) -> ()
2709        // * N: number of elements in the input vectors
2710        // * T: type of the element to load
2711        // * M: any integer width is supported, will be truncated to i1
2712        // Stores contiguous elements to memory behind `pointer`, but only for
2713        // those lanes whose `mask` bit is enabled.
2714        // The memory addresses corresponding to the “off” lanes are not accessed.
2715
2716        let alignment = fn_args[3].expect_const().to_branch()[0].to_leaf().to_simd_alignment();
2717
2718        // The element type of the "mask" argument must be a signed integer type of any width
2719        let mask_ty = in_ty;
2720        let (mask_len, mask_elem) = (in_len, in_elem);
2721
2722        // The second argument must be a pointer matching the element type
2723        let pointer_ty = args[1].layout.ty;
2724
2725        // The last argument specifies the values to store to memory
2726        let values_ty = args[2].layout.ty;
2727        let (values_len, values_elem) = {
    if !values_ty.is_simd() {
        {
            bx.sess().dcx().emit_err(InvalidMonomorphization::SimdThird {
                    span,
                    name,
                    ty: values_ty,
                });
            return Err(());
        };
    };
    values_ty.simd_size_and_type(bx.tcx())
}require_simd!(values_ty, SimdThird);
2728
2729        // Of the same length:
2730        if !(values_len == mask_len) {
    {
        bx.sess().dcx().emit_err(InvalidMonomorphization::ThirdArgumentLength {
                span,
                name,
                in_len: mask_len,
                in_ty: mask_ty,
                arg_ty: values_ty,
                out_len: values_len,
            });
        return Err(());
    };
};require!(
2731            values_len == mask_len,
2732            InvalidMonomorphization::ThirdArgumentLength {
2733                span,
2734                name,
2735                in_len: mask_len,
2736                in_ty: mask_ty,
2737                arg_ty: values_ty,
2738                out_len: values_len
2739            }
2740        );
2741
2742        // The second argument must be a mutable pointer type matching the element type
2743        if !#[allow(non_exhaustive_omitted_patterns)] match *pointer_ty.kind() {
            ty::RawPtr(p_ty, p_mutbl) if
                p_ty == values_elem && p_ty.kind() == values_elem.kind() &&
                    p_mutbl.is_mut() => true,
            _ => false,
        } {
    {
        bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedElementType {
                span,
                name,
                expected_element: values_elem,
                second_arg: pointer_ty,
                in_elem: values_elem,
                in_ty: values_ty,
                mutability: ExpectedPointerMutability::Mut,
            });
        return Err(());
    };
};require!(
2744            matches!(
2745                *pointer_ty.kind(),
2746                ty::RawPtr(p_ty, p_mutbl)
2747                    if p_ty == values_elem && p_ty.kind() == values_elem.kind() && p_mutbl.is_mut()
2748            ),
2749            InvalidMonomorphization::ExpectedElementType {
2750                span,
2751                name,
2752                expected_element: values_elem,
2753                second_arg: pointer_ty,
2754                in_elem: values_elem,
2755                in_ty: values_ty,
2756                mutability: ExpectedPointerMutability::Mut,
2757            }
2758        );
2759
2760        let m_elem_bitwidth = match mask_elem.kind() {
    ty::Int(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    ty::Uint(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    _ => {
        {
            bx.sess().dcx().emit_err(InvalidMonomorphization::MaskWrongElementType {
                    span,
                    name,
                    ty: mask_elem,
                });
            return Err(());
        };
    }
}require_int_or_uint_ty!(
2761            mask_elem.kind(),
2762            InvalidMonomorphization::MaskWrongElementType { span, name, ty: mask_elem }
2763        );
2764
2765        let mask = vector_mask_to_bitmask(bx, args[0].immediate(), m_elem_bitwidth, mask_len);
2766
2767        // Alignment of T, must be a constant integer value:
2768        let alignment = llvm_alignment(bx, alignment, values_ty, values_elem);
2769
2770        let llvm_pointer = bx.type_ptr();
2771
2772        // Type of the vector of elements:
2773        let llvm_elem_vec_ty = llvm_vector_ty(bx, values_elem, values_len);
2774
2775        let args: &[&'ll Value] = if llvm_version < (22, 0, 0) {
2776            let alignment = bx.const_i32(alignment as i32);
2777            &[args[2].immediate(), args[1].immediate(), alignment, mask]
2778        } else {
2779            &[args[2].immediate(), args[1].immediate(), mask]
2780        };
2781
2782        let call = bx.call_intrinsic("llvm.masked.store", &[llvm_elem_vec_ty, llvm_pointer], args);
2783        if llvm_version >= (22, 0, 0) {
2784            crate::attributes::apply_to_callsite(
2785                call,
2786                crate::llvm::AttributePlace::Argument(1),
2787                &[crate::llvm::CreateAlignmentAttr(bx.llcx, alignment)],
2788            )
2789        }
2790        return Ok(call);
2791    }
2792
2793    if name == sym::simd_scatter {
2794        // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
2795        //             mask: <N x i{M}>) -> ()
2796        // * N: number of elements in the input vectors
2797        // * T: type of the element to load
2798        // * M: any integer width is supported, will be truncated to i1
2799
2800        // All types must be simd vector types
2801        // The second argument must be a simd vector with an element type that's a pointer
2802        // to the element type of the first argument
2803        let (_, element_ty0) = {
    if !in_ty.is_simd() {
        {
            bx.sess().dcx().emit_err(InvalidMonomorphization::SimdFirst {
                    span,
                    name,
                    ty: in_ty,
                });
            return Err(());
        };
    };
    in_ty.simd_size_and_type(bx.tcx())
}require_simd!(in_ty, SimdFirst);
2804        let (element_len1, element_ty1) = {
    if !args[1].layout.ty.is_simd() {
        {
            bx.sess().dcx().emit_err(InvalidMonomorphization::SimdSecond {
                    span,
                    name,
                    ty: args[1].layout.ty,
                });
            return Err(());
        };
    };
    args[1].layout.ty.simd_size_and_type(bx.tcx())
}require_simd!(args[1].layout.ty, SimdSecond);
2805        let (element_len2, element_ty2) = {
    if !args[2].layout.ty.is_simd() {
        {
            bx.sess().dcx().emit_err(InvalidMonomorphization::SimdThird {
                    span,
                    name,
                    ty: args[2].layout.ty,
                });
            return Err(());
        };
    };
    args[2].layout.ty.simd_size_and_type(bx.tcx())
}require_simd!(args[2].layout.ty, SimdThird);
2806
2807        // Of the same length:
2808        if !(in_len == element_len1) {
    {
        bx.sess().dcx().emit_err(InvalidMonomorphization::SecondArgumentLength {
                span,
                name,
                in_len,
                in_ty,
                arg_ty: args[1].layout.ty,
                out_len: element_len1,
            });
        return Err(());
    };
};require!(
2809            in_len == element_len1,
2810            InvalidMonomorphization::SecondArgumentLength {
2811                span,
2812                name,
2813                in_len,
2814                in_ty,
2815                arg_ty: args[1].layout.ty,
2816                out_len: element_len1
2817            }
2818        );
2819        if !(in_len == element_len2) {
    {
        bx.sess().dcx().emit_err(InvalidMonomorphization::ThirdArgumentLength {
                span,
                name,
                in_len,
                in_ty,
                arg_ty: args[2].layout.ty,
                out_len: element_len2,
            });
        return Err(());
    };
};require!(
2820            in_len == element_len2,
2821            InvalidMonomorphization::ThirdArgumentLength {
2822                span,
2823                name,
2824                in_len,
2825                in_ty,
2826                arg_ty: args[2].layout.ty,
2827                out_len: element_len2
2828            }
2829        );
2830
2831        if !#[allow(non_exhaustive_omitted_patterns)] match *element_ty1.kind() {
            ty::RawPtr(p_ty, p_mutbl) if
                p_ty == in_elem && p_mutbl.is_mut() &&
                    p_ty.kind() == element_ty0.kind() => true,
            _ => false,
        } {
    {
        bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedElementType {
                span,
                name,
                expected_element: element_ty1,
                second_arg: args[1].layout.ty,
                in_elem,
                in_ty,
                mutability: ExpectedPointerMutability::Mut,
            });
        return Err(());
    };
};require!(
2832            matches!(
2833                *element_ty1.kind(),
2834                ty::RawPtr(p_ty, p_mutbl)
2835                    if p_ty == in_elem && p_mutbl.is_mut() && p_ty.kind() == element_ty0.kind()
2836            ),
2837            InvalidMonomorphization::ExpectedElementType {
2838                span,
2839                name,
2840                expected_element: element_ty1,
2841                second_arg: args[1].layout.ty,
2842                in_elem,
2843                in_ty,
2844                mutability: ExpectedPointerMutability::Mut,
2845            }
2846        );
2847
2848        // The element type of the third argument must be an integer type of any width:
2849        let mask_elem_bitwidth = match element_ty2.kind() {
    ty::Int(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    ty::Uint(i) => {
        i.bit_width().unwrap_or_else(||
                bx.data_layout().pointer_size().bits())
    }
    _ => {
        {
            bx.sess().dcx().emit_err(InvalidMonomorphization::MaskWrongElementType {
                    span,
                    name,
                    ty: element_ty2,
                });
            return Err(());
        };
    }
}require_int_or_uint_ty!(
2850            element_ty2.kind(),
2851            InvalidMonomorphization::MaskWrongElementType { span, name, ty: element_ty2 }
2852        );
2853
2854        // Alignment of T, must be a constant integer value:
2855        let alignment = bx.align_of(in_elem).bytes();
2856
2857        // Truncate the mask vector to a vector of i1s:
2858        let mask = vector_mask_to_bitmask(bx, args[2].immediate(), mask_elem_bitwidth, in_len);
2859
2860        // Type of the vector of pointers:
2861        let llvm_pointer_vec_ty = llvm_vector_ty(bx, element_ty1, in_len);
2862
2863        // Type of the vector of elements:
2864        let llvm_elem_vec_ty = llvm_vector_ty(bx, element_ty0, in_len);
2865        let args: &[&'ll Value] = if llvm_version < (22, 0, 0) {
2866            let alignment = bx.const_i32(alignment as i32);
2867            &[args[0].immediate(), args[1].immediate(), alignment, mask]
2868        } else {
2869            &[args[0].immediate(), args[1].immediate(), mask]
2870        };
2871        let call = bx.call_intrinsic(
2872            "llvm.masked.scatter",
2873            &[llvm_elem_vec_ty, llvm_pointer_vec_ty],
2874            args,
2875        );
2876        if llvm_version >= (22, 0, 0) {
2877            crate::attributes::apply_to_callsite(
2878                call,
2879                crate::llvm::AttributePlace::Argument(1),
2880                &[crate::llvm::CreateAlignmentAttr(bx.llcx, alignment)],
2881            )
2882        }
2883        return Ok(call);
2884    }
2885
2886    macro_rules! arith_red {
2887        ($name:ident : $integer_reduce:ident, $float_reduce:ident, $ordered:expr, $op:ident,
2888         $identity:expr) => {
2889            if name == sym::$name {
2890                require!(
2891                    ret_ty == in_elem,
2892                    InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty }
2893                );
2894                return match in_elem.kind() {
2895                    ty::Int(_) | ty::Uint(_) => {
2896                        let r = bx.$integer_reduce(args[0].immediate());
2897                        if $ordered {
2898                            // if overflow occurs, the result is the
2899                            // mathematical result modulo 2^n:
2900                            Ok(bx.$op(args[1].immediate(), r))
2901                        } else {
2902                            Ok(bx.$integer_reduce(args[0].immediate()))
2903                        }
2904                    }
2905                    ty::Float(f) => {
2906                        let acc = if $ordered {
2907                            // ordered arithmetic reductions take an accumulator
2908                            args[1].immediate()
2909                        } else {
2910                            // unordered arithmetic reductions use the identity accumulator
2911                            match f.bit_width() {
2912                                32 => bx.const_real(bx.type_f32(), $identity),
2913                                64 => bx.const_real(bx.type_f64(), $identity),
2914                                v => return_error!(
2915                                    InvalidMonomorphization::UnsupportedSymbolOfSize {
2916                                        span,
2917                                        name,
2918                                        symbol: sym::$name,
2919                                        in_ty,
2920                                        in_elem,
2921                                        size: v,
2922                                        ret_ty
2923                                    }
2924                                ),
2925                            }
2926                        };
2927                        Ok(bx.$float_reduce(acc, args[0].immediate()))
2928                    }
2929                    _ => return_error!(InvalidMonomorphization::UnsupportedSymbol {
2930                        span,
2931                        name,
2932                        symbol: sym::$name,
2933                        in_ty,
2934                        in_elem,
2935                        ret_ty
2936                    }),
2937                };
2938            }
2939        };
2940    }
2941
2942    if name == sym::simd_reduce_add_ordered {
    if !(ret_ty == in_elem) {
        {
            bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                    span,
                    name,
                    in_elem,
                    in_ty,
                    ret_ty,
                });
            return Err(());
        };
    };
    return match in_elem.kind() {
            ty::Int(_) | ty::Uint(_) => {
                let r = bx.vector_reduce_add(args[0].immediate());
                if true {
                    Ok(bx.add(args[1].immediate(), r))
                } else { Ok(bx.vector_reduce_add(args[0].immediate())) }
            }
            ty::Float(f) => {
                let acc =
                    if true {
                        args[1].immediate()
                    } else {
                        match f.bit_width() {
                            32 => bx.const_real(bx.type_f32(), -0.0),
                            64 => bx.const_real(bx.type_f64(), -0.0),
                            v => {
                                bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbolOfSize {
                                        span,
                                        name,
                                        symbol: sym::simd_reduce_add_ordered,
                                        in_ty,
                                        in_elem,
                                        size: v,
                                        ret_ty,
                                    });
                                return Err(());
                            }
                        }
                    };
                Ok(bx.vector_reduce_fadd(acc, args[0].immediate()))
            }
            _ => {
                bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                        span,
                        name,
                        symbol: sym::simd_reduce_add_ordered,
                        in_ty,
                        in_elem,
                        ret_ty,
                    });
                return Err(());
            }
        };
};arith_red!(simd_reduce_add_ordered: vector_reduce_add, vector_reduce_fadd, true, add, -0.0);
2943    if name == sym::simd_reduce_mul_ordered {
    if !(ret_ty == in_elem) {
        {
            bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                    span,
                    name,
                    in_elem,
                    in_ty,
                    ret_ty,
                });
            return Err(());
        };
    };
    return match in_elem.kind() {
            ty::Int(_) | ty::Uint(_) => {
                let r = bx.vector_reduce_mul(args[0].immediate());
                if true {
                    Ok(bx.mul(args[1].immediate(), r))
                } else { Ok(bx.vector_reduce_mul(args[0].immediate())) }
            }
            ty::Float(f) => {
                let acc =
                    if true {
                        args[1].immediate()
                    } else {
                        match f.bit_width() {
                            32 => bx.const_real(bx.type_f32(), 1.0),
                            64 => bx.const_real(bx.type_f64(), 1.0),
                            v => {
                                bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbolOfSize {
                                        span,
                                        name,
                                        symbol: sym::simd_reduce_mul_ordered,
                                        in_ty,
                                        in_elem,
                                        size: v,
                                        ret_ty,
                                    });
                                return Err(());
                            }
                        }
                    };
                Ok(bx.vector_reduce_fmul(acc, args[0].immediate()))
            }
            _ => {
                bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                        span,
                        name,
                        symbol: sym::simd_reduce_mul_ordered,
                        in_ty,
                        in_elem,
                        ret_ty,
                    });
                return Err(());
            }
        };
};arith_red!(simd_reduce_mul_ordered: vector_reduce_mul, vector_reduce_fmul, true, mul, 1.0);
2944    if name == sym::simd_reduce_add_unordered {
    if !(ret_ty == in_elem) {
        {
            bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                    span,
                    name,
                    in_elem,
                    in_ty,
                    ret_ty,
                });
            return Err(());
        };
    };
    return match in_elem.kind() {
            ty::Int(_) | ty::Uint(_) => {
                let r = bx.vector_reduce_add(args[0].immediate());
                if false {
                    Ok(bx.add(args[1].immediate(), r))
                } else { Ok(bx.vector_reduce_add(args[0].immediate())) }
            }
            ty::Float(f) => {
                let acc =
                    if false {
                        args[1].immediate()
                    } else {
                        match f.bit_width() {
                            32 => bx.const_real(bx.type_f32(), -0.0),
                            64 => bx.const_real(bx.type_f64(), -0.0),
                            v => {
                                bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbolOfSize {
                                        span,
                                        name,
                                        symbol: sym::simd_reduce_add_unordered,
                                        in_ty,
                                        in_elem,
                                        size: v,
                                        ret_ty,
                                    });
                                return Err(());
                            }
                        }
                    };
                Ok(bx.vector_reduce_fadd_reassoc(acc, args[0].immediate()))
            }
            _ => {
                bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                        span,
                        name,
                        symbol: sym::simd_reduce_add_unordered,
                        in_ty,
                        in_elem,
                        ret_ty,
                    });
                return Err(());
            }
        };
};arith_red!(
2945        simd_reduce_add_unordered: vector_reduce_add,
2946        vector_reduce_fadd_reassoc,
2947        false,
2948        add,
2949        -0.0
2950    );
2951    if name == sym::simd_reduce_mul_unordered {
    if !(ret_ty == in_elem) {
        {
            bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                    span,
                    name,
                    in_elem,
                    in_ty,
                    ret_ty,
                });
            return Err(());
        };
    };
    return match in_elem.kind() {
            ty::Int(_) | ty::Uint(_) => {
                let r = bx.vector_reduce_mul(args[0].immediate());
                if false {
                    Ok(bx.mul(args[1].immediate(), r))
                } else { Ok(bx.vector_reduce_mul(args[0].immediate())) }
            }
            ty::Float(f) => {
                let acc =
                    if false {
                        args[1].immediate()
                    } else {
                        match f.bit_width() {
                            32 => bx.const_real(bx.type_f32(), 1.0),
                            64 => bx.const_real(bx.type_f64(), 1.0),
                            v => {
                                bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbolOfSize {
                                        span,
                                        name,
                                        symbol: sym::simd_reduce_mul_unordered,
                                        in_ty,
                                        in_elem,
                                        size: v,
                                        ret_ty,
                                    });
                                return Err(());
                            }
                        }
                    };
                Ok(bx.vector_reduce_fmul_reassoc(acc, args[0].immediate()))
            }
            _ => {
                bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                        span,
                        name,
                        symbol: sym::simd_reduce_mul_unordered,
                        in_ty,
                        in_elem,
                        ret_ty,
                    });
                return Err(());
            }
        };
};arith_red!(
2952        simd_reduce_mul_unordered: vector_reduce_mul,
2953        vector_reduce_fmul_reassoc,
2954        false,
2955        mul,
2956        1.0
2957    );
2958
2959    macro_rules! minmax_red {
2960        ($name:ident: $int_red:ident) => {
2961            if name == sym::$name {
2962                require!(
2963                    ret_ty == in_elem,
2964                    InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty }
2965                );
2966                return match in_elem.kind() {
2967                    ty::Int(_i) => Ok(bx.$int_red(args[0].immediate(), true)),
2968                    ty::Uint(_u) => Ok(bx.$int_red(args[0].immediate(), false)),
2969                    _ => return_error!(InvalidMonomorphization::UnsupportedSymbol {
2970                        span,
2971                        name,
2972                        symbol: sym::$name,
2973                        in_ty,
2974                        in_elem,
2975                        ret_ty
2976                    }),
2977                };
2978            }
2979        };
2980    }
2981
2982    // Currently no support for float due to <https://github.com/llvm/llvm-project/issues/185827>.
2983    if name == sym::simd_reduce_min {
    if !(ret_ty == in_elem) {
        {
            bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                    span,
                    name,
                    in_elem,
                    in_ty,
                    ret_ty,
                });
            return Err(());
        };
    };
    return match in_elem.kind() {
            ty::Int(_i) =>
                Ok(bx.vector_reduce_min(args[0].immediate(), true)),
            ty::Uint(_u) =>
                Ok(bx.vector_reduce_min(args[0].immediate(), false)),
            _ => {
                bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                        span,
                        name,
                        symbol: sym::simd_reduce_min,
                        in_ty,
                        in_elem,
                        ret_ty,
                    });
                return Err(());
            }
        };
};minmax_red!(simd_reduce_min: vector_reduce_min);
2984    if name == sym::simd_reduce_max {
    if !(ret_ty == in_elem) {
        {
            bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                    span,
                    name,
                    in_elem,
                    in_ty,
                    ret_ty,
                });
            return Err(());
        };
    };
    return match in_elem.kind() {
            ty::Int(_i) =>
                Ok(bx.vector_reduce_max(args[0].immediate(), true)),
            ty::Uint(_u) =>
                Ok(bx.vector_reduce_max(args[0].immediate(), false)),
            _ => {
                bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                        span,
                        name,
                        symbol: sym::simd_reduce_max,
                        in_ty,
                        in_elem,
                        ret_ty,
                    });
                return Err(());
            }
        };
};minmax_red!(simd_reduce_max: vector_reduce_max);
2985
2986    macro_rules! bitwise_red {
2987        ($name:ident : $red:ident, $boolean:expr) => {
2988            if name == sym::$name {
2989                let input = if !$boolean {
2990                    require!(
2991                        ret_ty == in_elem,
2992                        InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty }
2993                    );
2994                    args[0].immediate()
2995                } else {
2996                    let bitwidth = match in_elem.kind() {
2997                        ty::Int(i) => {
2998                            i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size().bits())
2999                        }
3000                        ty::Uint(i) => {
3001                            i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size().bits())
3002                        }
3003                        _ => return_error!(InvalidMonomorphization::UnsupportedSymbol {
3004                            span,
3005                            name,
3006                            symbol: sym::$name,
3007                            in_ty,
3008                            in_elem,
3009                            ret_ty
3010                        }),
3011                    };
3012
3013                    vector_mask_to_bitmask(bx, args[0].immediate(), bitwidth, in_len as _)
3014                };
3015                return match in_elem.kind() {
3016                    ty::Int(_) | ty::Uint(_) => {
3017                        let r = bx.$red(input);
3018                        Ok(if !$boolean { r } else { bx.zext(r, bx.type_bool()) })
3019                    }
3020                    _ => return_error!(InvalidMonomorphization::UnsupportedSymbol {
3021                        span,
3022                        name,
3023                        symbol: sym::$name,
3024                        in_ty,
3025                        in_elem,
3026                        ret_ty
3027                    }),
3028                };
3029            }
3030        };
3031    }
3032
3033    if name == sym::simd_reduce_and {
    let input =
        if !false {
            if !(ret_ty == in_elem) {
                {
                    bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                            span,
                            name,
                            in_elem,
                            in_ty,
                            ret_ty,
                        });
                    return Err(());
                };
            };
            args[0].immediate()
        } else {
            let bitwidth =
                match in_elem.kind() {
                    ty::Int(i) => {
                        i.bit_width().unwrap_or_else(||
                                bx.data_layout().pointer_size().bits())
                    }
                    ty::Uint(i) => {
                        i.bit_width().unwrap_or_else(||
                                bx.data_layout().pointer_size().bits())
                    }
                    _ => {
                        bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                                span,
                                name,
                                symbol: sym::simd_reduce_and,
                                in_ty,
                                in_elem,
                                ret_ty,
                            });
                        return Err(());
                    }
                };
            vector_mask_to_bitmask(bx, args[0].immediate(), bitwidth,
                in_len as _)
        };
    return match in_elem.kind() {
            ty::Int(_) | ty::Uint(_) => {
                let r = bx.vector_reduce_and(input);
                Ok(if !false { r } else { bx.zext(r, bx.type_bool()) })
            }
            _ => {
                bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                        span,
                        name,
                        symbol: sym::simd_reduce_and,
                        in_ty,
                        in_elem,
                        ret_ty,
                    });
                return Err(());
            }
        };
};bitwise_red!(simd_reduce_and: vector_reduce_and, false);
3034    if name == sym::simd_reduce_or {
    let input =
        if !false {
            if !(ret_ty == in_elem) {
                {
                    bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                            span,
                            name,
                            in_elem,
                            in_ty,
                            ret_ty,
                        });
                    return Err(());
                };
            };
            args[0].immediate()
        } else {
            let bitwidth =
                match in_elem.kind() {
                    ty::Int(i) => {
                        i.bit_width().unwrap_or_else(||
                                bx.data_layout().pointer_size().bits())
                    }
                    ty::Uint(i) => {
                        i.bit_width().unwrap_or_else(||
                                bx.data_layout().pointer_size().bits())
                    }
                    _ => {
                        bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                                span,
                                name,
                                symbol: sym::simd_reduce_or,
                                in_ty,
                                in_elem,
                                ret_ty,
                            });
                        return Err(());
                    }
                };
            vector_mask_to_bitmask(bx, args[0].immediate(), bitwidth,
                in_len as _)
        };
    return match in_elem.kind() {
            ty::Int(_) | ty::Uint(_) => {
                let r = bx.vector_reduce_or(input);
                Ok(if !false { r } else { bx.zext(r, bx.type_bool()) })
            }
            _ => {
                bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                        span,
                        name,
                        symbol: sym::simd_reduce_or,
                        in_ty,
                        in_elem,
                        ret_ty,
                    });
                return Err(());
            }
        };
};bitwise_red!(simd_reduce_or: vector_reduce_or, false);
3035    if name == sym::simd_reduce_xor {
    let input =
        if !false {
            if !(ret_ty == in_elem) {
                {
                    bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                            span,
                            name,
                            in_elem,
                            in_ty,
                            ret_ty,
                        });
                    return Err(());
                };
            };
            args[0].immediate()
        } else {
            let bitwidth =
                match in_elem.kind() {
                    ty::Int(i) => {
                        i.bit_width().unwrap_or_else(||
                                bx.data_layout().pointer_size().bits())
                    }
                    ty::Uint(i) => {
                        i.bit_width().unwrap_or_else(||
                                bx.data_layout().pointer_size().bits())
                    }
                    _ => {
                        bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                                span,
                                name,
                                symbol: sym::simd_reduce_xor,
                                in_ty,
                                in_elem,
                                ret_ty,
                            });
                        return Err(());
                    }
                };
            vector_mask_to_bitmask(bx, args[0].immediate(), bitwidth,
                in_len as _)
        };
    return match in_elem.kind() {
            ty::Int(_) | ty::Uint(_) => {
                let r = bx.vector_reduce_xor(input);
                Ok(if !false { r } else { bx.zext(r, bx.type_bool()) })
            }
            _ => {
                bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                        span,
                        name,
                        symbol: sym::simd_reduce_xor,
                        in_ty,
                        in_elem,
                        ret_ty,
                    });
                return Err(());
            }
        };
};bitwise_red!(simd_reduce_xor: vector_reduce_xor, false);
3036    if name == sym::simd_reduce_all {
    let input =
        if !true {
            if !(ret_ty == in_elem) {
                {
                    bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                            span,
                            name,
                            in_elem,
                            in_ty,
                            ret_ty,
                        });
                    return Err(());
                };
            };
            args[0].immediate()
        } else {
            let bitwidth =
                match in_elem.kind() {
                    ty::Int(i) => {
                        i.bit_width().unwrap_or_else(||
                                bx.data_layout().pointer_size().bits())
                    }
                    ty::Uint(i) => {
                        i.bit_width().unwrap_or_else(||
                                bx.data_layout().pointer_size().bits())
                    }
                    _ => {
                        bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                                span,
                                name,
                                symbol: sym::simd_reduce_all,
                                in_ty,
                                in_elem,
                                ret_ty,
                            });
                        return Err(());
                    }
                };
            vector_mask_to_bitmask(bx, args[0].immediate(), bitwidth,
                in_len as _)
        };
    return match in_elem.kind() {
            ty::Int(_) | ty::Uint(_) => {
                let r = bx.vector_reduce_and(input);
                Ok(if !true { r } else { bx.zext(r, bx.type_bool()) })
            }
            _ => {
                bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                        span,
                        name,
                        symbol: sym::simd_reduce_all,
                        in_ty,
                        in_elem,
                        ret_ty,
                    });
                return Err(());
            }
        };
};bitwise_red!(simd_reduce_all: vector_reduce_and, true);
3037    if name == sym::simd_reduce_any {
    let input =
        if !true {
            if !(ret_ty == in_elem) {
                {
                    bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnType {
                            span,
                            name,
                            in_elem,
                            in_ty,
                            ret_ty,
                        });
                    return Err(());
                };
            };
            args[0].immediate()
        } else {
            let bitwidth =
                match in_elem.kind() {
                    ty::Int(i) => {
                        i.bit_width().unwrap_or_else(||
                                bx.data_layout().pointer_size().bits())
                    }
                    ty::Uint(i) => {
                        i.bit_width().unwrap_or_else(||
                                bx.data_layout().pointer_size().bits())
                    }
                    _ => {
                        bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                                span,
                                name,
                                symbol: sym::simd_reduce_any,
                                in_ty,
                                in_elem,
                                ret_ty,
                            });
                        return Err(());
                    }
                };
            vector_mask_to_bitmask(bx, args[0].immediate(), bitwidth,
                in_len as _)
        };
    return match in_elem.kind() {
            ty::Int(_) | ty::Uint(_) => {
                let r = bx.vector_reduce_or(input);
                Ok(if !true { r } else { bx.zext(r, bx.type_bool()) })
            }
            _ => {
                bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedSymbol {
                        span,
                        name,
                        symbol: sym::simd_reduce_any,
                        in_ty,
                        in_elem,
                        ret_ty,
                    });
                return Err(());
            }
        };
};bitwise_red!(simd_reduce_any: vector_reduce_or, true);
3038
3039    if name == sym::simd_cast_ptr {
3040        let (out_len, out_elem) = {
    if !ret_ty.is_simd() {
        {
            bx.sess().dcx().emit_err(InvalidMonomorphization::SimdReturn {
                    span,
                    name,
                    ty: ret_ty,
                });
            return Err(());
        };
    };
    ret_ty.simd_size_and_type(bx.tcx())
}require_simd!(ret_ty, SimdReturn);
3041        if !(in_len == out_len) {
    {
        bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnLengthInputType {
                span,
                name,
                in_len,
                in_ty,
                ret_ty,
                out_len,
            });
        return Err(());
    };
};require!(
3042            in_len == out_len,
3043            InvalidMonomorphization::ReturnLengthInputType {
3044                span,
3045                name,
3046                in_len,
3047                in_ty,
3048                ret_ty,
3049                out_len
3050            }
3051        );
3052
3053        match in_elem.kind() {
3054            ty::RawPtr(p_ty, _) => {
3055                let metadata = p_ty.ptr_metadata_ty(bx.tcx, |ty| {
3056                    bx.tcx.normalize_erasing_regions(bx.typing_env(), Unnormalized::new_wip(ty))
3057                });
3058                if !metadata.is_unit() {
    {
        bx.sess().dcx().emit_err(InvalidMonomorphization::CastWidePointer {
                span,
                name,
                ty: in_elem,
            });
        return Err(());
    };
};require!(
3059                    metadata.is_unit(),
3060                    InvalidMonomorphization::CastWidePointer { span, name, ty: in_elem }
3061                );
3062            }
3063            _ => {
3064                {
    bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedPointer {
            span,
            name,
            ty: in_elem,
        });
    return Err(());
}return_error!(InvalidMonomorphization::ExpectedPointer { span, name, ty: in_elem })
3065            }
3066        }
3067        match out_elem.kind() {
3068            ty::RawPtr(p_ty, _) => {
3069                let metadata = p_ty.ptr_metadata_ty(bx.tcx, |ty| {
3070                    bx.tcx.normalize_erasing_regions(bx.typing_env(), Unnormalized::new_wip(ty))
3071                });
3072                if !metadata.is_unit() {
    {
        bx.sess().dcx().emit_err(InvalidMonomorphization::CastWidePointer {
                span,
                name,
                ty: out_elem,
            });
        return Err(());
    };
};require!(
3073                    metadata.is_unit(),
3074                    InvalidMonomorphization::CastWidePointer { span, name, ty: out_elem }
3075                );
3076            }
3077            _ => {
3078                {
    bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedPointer {
            span,
            name,
            ty: out_elem,
        });
    return Err(());
}return_error!(InvalidMonomorphization::ExpectedPointer { span, name, ty: out_elem })
3079            }
3080        }
3081
3082        return Ok(args[0].immediate());
3083    }
3084
3085    if name == sym::simd_expose_provenance {
3086        let (out_len, out_elem) = {
    if !ret_ty.is_simd() {
        {
            bx.sess().dcx().emit_err(InvalidMonomorphization::SimdReturn {
                    span,
                    name,
                    ty: ret_ty,
                });
            return Err(());
        };
    };
    ret_ty.simd_size_and_type(bx.tcx())
}require_simd!(ret_ty, SimdReturn);
3087        if !(in_len == out_len) {
    {
        bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnLengthInputType {
                span,
                name,
                in_len,
                in_ty,
                ret_ty,
                out_len,
            });
        return Err(());
    };
};require!(
3088            in_len == out_len,
3089            InvalidMonomorphization::ReturnLengthInputType {
3090                span,
3091                name,
3092                in_len,
3093                in_ty,
3094                ret_ty,
3095                out_len
3096            }
3097        );
3098
3099        match in_elem.kind() {
3100            ty::RawPtr(_, _) => {}
3101            _ => {
3102                {
    bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedPointer {
            span,
            name,
            ty: in_elem,
        });
    return Err(());
}return_error!(InvalidMonomorphization::ExpectedPointer { span, name, ty: in_elem })
3103            }
3104        }
3105        match out_elem.kind() {
3106            ty::Uint(ty::UintTy::Usize) => {}
3107            _ => {
    bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedUsize {
            span,
            name,
            ty: out_elem,
        });
    return Err(());
}return_error!(InvalidMonomorphization::ExpectedUsize { span, name, ty: out_elem }),
3108        }
3109
3110        return Ok(bx.ptrtoint(args[0].immediate(), llret_ty));
3111    }
3112
3113    if name == sym::simd_with_exposed_provenance {
3114        let (out_len, out_elem) = {
    if !ret_ty.is_simd() {
        {
            bx.sess().dcx().emit_err(InvalidMonomorphization::SimdReturn {
                    span,
                    name,
                    ty: ret_ty,
                });
            return Err(());
        };
    };
    ret_ty.simd_size_and_type(bx.tcx())
}require_simd!(ret_ty, SimdReturn);
3115        if !(in_len == out_len) {
    {
        bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnLengthInputType {
                span,
                name,
                in_len,
                in_ty,
                ret_ty,
                out_len,
            });
        return Err(());
    };
};require!(
3116            in_len == out_len,
3117            InvalidMonomorphization::ReturnLengthInputType {
3118                span,
3119                name,
3120                in_len,
3121                in_ty,
3122                ret_ty,
3123                out_len
3124            }
3125        );
3126
3127        match in_elem.kind() {
3128            ty::Uint(ty::UintTy::Usize) => {}
3129            _ => {
    bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedUsize {
            span,
            name,
            ty: in_elem,
        });
    return Err(());
}return_error!(InvalidMonomorphization::ExpectedUsize { span, name, ty: in_elem }),
3130        }
3131        match out_elem.kind() {
3132            ty::RawPtr(_, _) => {}
3133            _ => {
3134                {
    bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedPointer {
            span,
            name,
            ty: out_elem,
        });
    return Err(());
}return_error!(InvalidMonomorphization::ExpectedPointer { span, name, ty: out_elem })
3135            }
3136        }
3137
3138        return Ok(bx.inttoptr(args[0].immediate(), llret_ty));
3139    }
3140
3141    if name == sym::simd_cast || name == sym::simd_as {
3142        let (out_len, out_elem, out_num_vecs) = {
    if !(ret_ty.is_simd() || ret_ty.is_scalable_vector()) {
        {
            bx.sess().dcx().emit_err(InvalidMonomorphization::SimdReturn {
                    span,
                    name,
                    ty: ret_ty,
                });
            return Err(());
        };
    };
    if ret_ty.is_simd() {
        let (len, ty) = ret_ty.simd_size_and_type(bx.tcx());
        (len, ty, None)
    } else {
        let (count, ty, num_vecs) =
            ret_ty.scalable_vector_parts(bx.tcx()).expect("`is_scalable_vector` was wrong");
        (count as u64, ty, Some(num_vecs))
    }
}require_simd_or_scalable!(ret_ty, SimdReturn);
3143        if !(in_len == out_len) {
    {
        bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnLengthInputType {
                span,
                name,
                in_len,
                in_ty,
                ret_ty,
                out_len,
            });
        return Err(());
    };
};require!(
3144            in_len == out_len,
3145            InvalidMonomorphization::ReturnLengthInputType {
3146                span,
3147                name,
3148                in_len,
3149                in_ty,
3150                ret_ty,
3151                out_len
3152            }
3153        );
3154        if !(in_num_vecs == out_num_vecs) {
    {
        bx.sess().dcx().emit_err(InvalidMonomorphization::ReturnNumVecsInputType {
                span,
                name,
                in_num_vecs: in_num_vecs.unwrap_or(NumScalableVectors(1)),
                in_ty,
                ret_ty,
                out_num_vecs: out_num_vecs.unwrap_or(NumScalableVectors(1)),
            });
        return Err(());
    };
};require!(
3155            in_num_vecs == out_num_vecs,
3156            InvalidMonomorphization::ReturnNumVecsInputType {
3157                span,
3158                name,
3159                in_num_vecs: in_num_vecs.unwrap_or(NumScalableVectors(1)),
3160                in_ty,
3161                ret_ty,
3162                out_num_vecs: out_num_vecs.unwrap_or(NumScalableVectors(1))
3163            }
3164        );
3165
3166        // Casting cares about nominal type, not just structural type
3167        if in_elem == out_elem {
3168            return Ok(args[0].immediate());
3169        }
3170
3171        #[derive(#[automatically_derived]
impl ::core::marker::Copy for Sign { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Sign {
    #[inline]
    fn clone(&self) -> Sign { *self }
}Clone)]
3172        enum Sign {
3173            Unsigned,
3174            Signed,
3175        }
3176        use Sign::*;
3177
3178        enum Style {
3179            Float,
3180            Int(Sign),
3181            Unsupported,
3182        }
3183
3184        let (in_style, in_width) = match in_elem.kind() {
3185            // vectors of pointer-sized integers should've been
3186            // disallowed before here, so this unwrap is safe.
3187            ty::Int(i) => (
3188                Style::Int(Signed),
3189                i.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
3190            ),
3191            ty::Uint(u) => (
3192                Style::Int(Unsigned),
3193                u.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
3194            ),
3195            ty::Float(f) => (Style::Float, f.bit_width()),
3196            _ => (Style::Unsupported, 0),
3197        };
3198        let (out_style, out_width) = match out_elem.kind() {
3199            ty::Int(i) => (
3200                Style::Int(Signed),
3201                i.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
3202            ),
3203            ty::Uint(u) => (
3204                Style::Int(Unsigned),
3205                u.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
3206            ),
3207            ty::Float(f) => (Style::Float, f.bit_width()),
3208            _ => (Style::Unsupported, 0),
3209        };
3210
3211        match (in_style, out_style) {
3212            (Style::Int(sign), Style::Int(_)) => {
3213                return Ok(match in_width.cmp(&out_width) {
3214                    Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
3215                    Ordering::Equal => args[0].immediate(),
3216                    Ordering::Less => match sign {
3217                        Sign::Signed => bx.sext(args[0].immediate(), llret_ty),
3218                        Sign::Unsigned => bx.zext(args[0].immediate(), llret_ty),
3219                    },
3220                });
3221            }
3222            (Style::Int(Sign::Signed), Style::Float) => {
3223                return Ok(bx.sitofp(args[0].immediate(), llret_ty));
3224            }
3225            (Style::Int(Sign::Unsigned), Style::Float) => {
3226                return Ok(bx.uitofp(args[0].immediate(), llret_ty));
3227            }
3228            (Style::Float, Style::Int(sign)) => {
3229                return Ok(match (sign, name == sym::simd_as) {
3230                    (Sign::Unsigned, false) => bx.fptoui(args[0].immediate(), llret_ty),
3231                    (Sign::Signed, false) => bx.fptosi(args[0].immediate(), llret_ty),
3232                    (_, true) => bx.cast_float_to_int(
3233                        #[allow(non_exhaustive_omitted_patterns)] match sign {
    Sign::Signed => true,
    _ => false,
}matches!(sign, Sign::Signed),
3234                        args[0].immediate(),
3235                        llret_ty,
3236                    ),
3237                });
3238            }
3239            (Style::Float, Style::Float) => {
3240                return Ok(match in_width.cmp(&out_width) {
3241                    Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
3242                    Ordering::Equal => args[0].immediate(),
3243                    Ordering::Less => bx.fpext(args[0].immediate(), llret_ty),
3244                });
3245            }
3246            _ => {
    bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedCast {
            span,
            name,
            in_ty,
            in_elem,
            ret_ty,
            out_elem,
        });
    return Err(());
}return_error!(InvalidMonomorphization::UnsupportedCast {
3247                span,
3248                name,
3249                in_ty,
3250                in_elem,
3251                ret_ty,
3252                out_elem
3253            }),
3254        }
3255    }
3256    macro_rules! arith_binary {
3257        ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
3258            $(if name == sym::$name {
3259                match in_elem.kind() {
3260                    $($(ty::$p(_))|* => {
3261                        return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
3262                    })*
3263                    _ => {},
3264                }
3265                return_error!(
3266                    InvalidMonomorphization::UnsupportedOperation { span, name, in_ty, in_elem }
3267                );
3268            })*
3269        }
3270    }
3271    if name == sym::simd_minimum_number_nsz {
    match in_elem.kind() {
        ty::Float(_) => {
            return Ok(bx.minimum_number_nsz(args[0].immediate(),
                        args[1].immediate()))
        }
        _ => {}
    }
    {
        bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedOperation {
                span,
                name,
                in_ty,
                in_elem,
            });
        return Err(());
    };
}arith_binary! {
3272        simd_add: Uint, Int => add, Float => fadd;
3273        simd_sub: Uint, Int => sub, Float => fsub;
3274        simd_mul: Uint, Int => mul, Float => fmul;
3275        simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
3276        simd_rem: Uint => urem, Int => srem, Float => frem;
3277        simd_shl: Uint, Int => shl;
3278        simd_shr: Uint => lshr, Int => ashr;
3279        simd_and: Uint, Int => and;
3280        simd_or: Uint, Int => or;
3281        simd_xor: Uint, Int => xor;
3282        simd_maximum_number_nsz: Float => maximum_number_nsz;
3283        simd_minimum_number_nsz: Float => minimum_number_nsz;
3284
3285    }
3286    macro_rules! arith_unary {
3287        ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
3288            $(if name == sym::$name {
3289                match in_elem.kind() {
3290                    $($(ty::$p(_))|* => {
3291                        return Ok(bx.$call(args[0].immediate()))
3292                    })*
3293                    _ => {},
3294                }
3295                return_error!(
3296                    InvalidMonomorphization::UnsupportedOperation { span, name, in_ty, in_elem }
3297                );
3298            })*
3299        }
3300    }
3301    if name == sym::simd_neg {
    match in_elem.kind() {
        ty::Int(_) => { return Ok(bx.neg(args[0].immediate())) }
        ty::Float(_) => { return Ok(bx.fneg(args[0].immediate())) }
        _ => {}
    }
    {
        bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedOperation {
                span,
                name,
                in_ty,
                in_elem,
            });
        return Err(());
    };
}arith_unary! {
3302        simd_neg: Int => neg, Float => fneg;
3303    }
3304
3305    // Unary integer intrinsics
3306    if #[allow(non_exhaustive_omitted_patterns)] match name {
    sym::simd_bswap | sym::simd_bitreverse | sym::simd_ctlz | sym::simd_ctpop
        | sym::simd_cttz | sym::simd_carryless_mul | sym::simd_funnel_shl |
        sym::simd_funnel_shr => true,
    _ => false,
}matches!(
3307        name,
3308        sym::simd_bswap
3309            | sym::simd_bitreverse
3310            | sym::simd_ctlz
3311            | sym::simd_ctpop
3312            | sym::simd_cttz
3313            | sym::simd_carryless_mul
3314            | sym::simd_funnel_shl
3315            | sym::simd_funnel_shr
3316    ) {
3317        let vec_ty = bx.cx.type_vector(
3318            match *in_elem.kind() {
3319                ty::Int(i) => bx.cx.type_int_from_ty(i),
3320                ty::Uint(i) => bx.cx.type_uint_from_ty(i),
3321                _ => {
    bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedOperation {
            span,
            name,
            in_ty,
            in_elem,
        });
    return Err(());
}return_error!(InvalidMonomorphization::UnsupportedOperation {
3322                    span,
3323                    name,
3324                    in_ty,
3325                    in_elem
3326                }),
3327            },
3328            in_len as u64,
3329        );
3330        let llvm_intrinsic = match name {
3331            sym::simd_bswap => "llvm.bswap",
3332            sym::simd_bitreverse => "llvm.bitreverse",
3333            sym::simd_ctlz => "llvm.ctlz",
3334            sym::simd_ctpop => "llvm.ctpop",
3335            sym::simd_cttz => "llvm.cttz",
3336            sym::simd_funnel_shl => "llvm.fshl",
3337            sym::simd_funnel_shr => "llvm.fshr",
3338            sym::simd_carryless_mul => "llvm.clmul",
3339            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
3340        };
3341        let int_size = in_elem.int_size_and_signed(bx.tcx()).0.bits();
3342
3343        return match name {
3344            // byte swap is no-op for i8/u8
3345            sym::simd_bswap if int_size == 8 => Ok(args[0].immediate()),
3346            sym::simd_ctlz | sym::simd_cttz => {
3347                // for the (int, i1 immediate) pair, the second arg adds `(0, true) => poison`
3348                let dont_poison_on_zero = bx.const_int(bx.type_i1(), 0);
3349                Ok(bx.call_intrinsic(
3350                    llvm_intrinsic,
3351                    &[vec_ty],
3352                    &[args[0].immediate(), dont_poison_on_zero],
3353                ))
3354            }
3355            sym::simd_bswap | sym::simd_bitreverse | sym::simd_ctpop => {
3356                // simple unary argument cases
3357                Ok(bx.call_intrinsic(llvm_intrinsic, &[vec_ty], &[args[0].immediate()]))
3358            }
3359            sym::simd_funnel_shl | sym::simd_funnel_shr => Ok(bx.call_intrinsic(
3360                llvm_intrinsic,
3361                &[vec_ty],
3362                &[args[0].immediate(), args[1].immediate(), args[2].immediate()],
3363            )),
3364            sym::simd_carryless_mul => {
3365                if crate::llvm_util::get_version() >= (22, 0, 0) {
3366                    Ok(bx.call_intrinsic(
3367                        llvm_intrinsic,
3368                        &[vec_ty],
3369                        &[args[0].immediate(), args[1].immediate()],
3370                    ))
3371                } else {
3372                    ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("`simd_carryless_mul` needs LLVM 22 or higher"));span_bug!(span, "`simd_carryless_mul` needs LLVM 22 or higher");
3373                }
3374            }
3375            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
3376        };
3377    }
3378
3379    if name == sym::simd_arith_offset {
3380        // This also checks that the first operand is a ptr type.
3381        let pointee = in_elem.builtin_deref(true).unwrap_or_else(|| {
3382            ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("must be called with a vector of pointer types as first argument"))span_bug!(span, "must be called with a vector of pointer types as first argument")
3383        });
3384        let layout = bx.layout_of(pointee);
3385        let ptrs = args[0].immediate();
3386        // The second argument must be a ptr-sized integer.
3387        // (We don't care about the signedness, this is wrapping anyway.)
3388        let (_offsets_len, offsets_elem) = args[1].layout.ty.simd_size_and_type(bx.tcx());
3389        if !#[allow(non_exhaustive_omitted_patterns)] match offsets_elem.kind() {
    ty::Int(ty::IntTy::Isize) | ty::Uint(ty::UintTy::Usize) => true,
    _ => false,
}matches!(offsets_elem.kind(), ty::Int(ty::IntTy::Isize) | ty::Uint(ty::UintTy::Usize)) {
3390            ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("must be called with a vector of pointer-sized integers as second argument"));span_bug!(
3391                span,
3392                "must be called with a vector of pointer-sized integers as second argument"
3393            );
3394        }
3395        let offsets = args[1].immediate();
3396
3397        return Ok(bx.gep(bx.backend_type(layout), ptrs, &[offsets]));
3398    }
3399
3400    if name == sym::simd_saturating_add || name == sym::simd_saturating_sub {
3401        let lhs = args[0].immediate();
3402        let rhs = args[1].immediate();
3403        let is_add = name == sym::simd_saturating_add;
3404        let (signed, elem_ty) = match *in_elem.kind() {
3405            ty::Int(i) => (true, bx.cx.type_int_from_ty(i)),
3406            ty::Uint(i) => (false, bx.cx.type_uint_from_ty(i)),
3407            _ => {
3408                {
    bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedVectorElementType {
            span,
            name,
            expected_element: args[0].layout.ty.simd_size_and_type(bx.tcx()).1,
            vector_type: args[0].layout.ty,
        });
    return Err(());
};return_error!(InvalidMonomorphization::ExpectedVectorElementType {
3409                    span,
3410                    name,
3411                    expected_element: args[0].layout.ty.simd_size_and_type(bx.tcx()).1,
3412                    vector_type: args[0].layout.ty
3413                });
3414            }
3415        };
3416        let llvm_intrinsic = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("llvm.{0}{1}.sat",
                if signed { 's' } else { 'u' },
                if is_add { "add" } else { "sub" }))
    })format!(
3417            "llvm.{}{}.sat",
3418            if signed { 's' } else { 'u' },
3419            if is_add { "add" } else { "sub" },
3420        );
3421        let vec_ty = bx.cx.type_vector(elem_ty, in_len as u64);
3422
3423        return Ok(bx.call_intrinsic(llvm_intrinsic, &[vec_ty], &[lhs, rhs]));
3424    }
3425
3426    ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("unknown SIMD intrinsic"));span_bug!(span, "unknown SIMD intrinsic");
3427}