Skip to main content

rustc_codegen_llvm/
intrinsic.rs

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