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