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, Os};
32use tracing::debug;
33
34use crate::abi::FnAbiLlvmExt;
35use crate::builder::Builder;
36use crate::builder::autodiff::{adjust_activity_to_abi, generate_enzyme_call};
37use crate::builder::gpu_offload::{
38    OffloadKernelDims, gen_call_handling, gen_define_handling, register_offload,
39};
40use crate::context::CodegenCx;
41use crate::declare::declare_raw_fn;
42use crate::errors::{
43    AutoDiffWithoutEnable, AutoDiffWithoutLto, IntrinsicSignatureMismatch, IntrinsicWrongArch,
44    OffloadWithoutEnable, OffloadWithoutFatLTO, UnknownIntrinsic,
45};
46use crate::llvm::{self, Type, Value};
47use crate::type_of::LayoutLlvmExt;
48use crate::va_arg::emit_va_arg;
49
50fn call_simple_intrinsic<'ll, 'tcx>(
51    bx: &mut Builder<'_, 'll, 'tcx>,
52    name: Symbol,
53    args: &[OperandRef<'tcx, &'ll Value>],
54) -> Option<&'ll Value> {
55    let (base_name, type_params): (&'static str, &[&'ll Type]) = match name {
56        sym::sqrtf16 => ("llvm.sqrt", &[bx.type_f16()]),
57        sym::sqrtf32 => ("llvm.sqrt", &[bx.type_f32()]),
58        sym::sqrtf64 => ("llvm.sqrt", &[bx.type_f64()]),
59        sym::sqrtf128 => ("llvm.sqrt", &[bx.type_f128()]),
60
61        sym::powif16 => ("llvm.powi", &[bx.type_f16(), bx.type_i32()]),
62        sym::powif32 => ("llvm.powi", &[bx.type_f32(), bx.type_i32()]),
63        sym::powif64 => ("llvm.powi", &[bx.type_f64(), bx.type_i32()]),
64        sym::powif128 => ("llvm.powi", &[bx.type_f128(), bx.type_i32()]),
65
66        sym::sinf16 => ("llvm.sin", &[bx.type_f16()]),
67        sym::sinf32 => ("llvm.sin", &[bx.type_f32()]),
68        sym::sinf64 => ("llvm.sin", &[bx.type_f64()]),
69        sym::sinf128 => ("llvm.sin", &[bx.type_f128()]),
70
71        sym::cosf16 => ("llvm.cos", &[bx.type_f16()]),
72        sym::cosf32 => ("llvm.cos", &[bx.type_f32()]),
73        sym::cosf64 => ("llvm.cos", &[bx.type_f64()]),
74        sym::cosf128 => ("llvm.cos", &[bx.type_f128()]),
75
76        sym::powf16 => ("llvm.pow", &[bx.type_f16()]),
77        sym::powf32 => ("llvm.pow", &[bx.type_f32()]),
78        sym::powf64 => ("llvm.pow", &[bx.type_f64()]),
79        sym::powf128 => ("llvm.pow", &[bx.type_f128()]),
80
81        sym::expf16 => ("llvm.exp", &[bx.type_f16()]),
82        sym::expf32 => ("llvm.exp", &[bx.type_f32()]),
83        sym::expf64 => ("llvm.exp", &[bx.type_f64()]),
84        sym::expf128 => ("llvm.exp", &[bx.type_f128()]),
85
86        sym::exp2f16 => ("llvm.exp2", &[bx.type_f16()]),
87        sym::exp2f32 => ("llvm.exp2", &[bx.type_f32()]),
88        sym::exp2f64 => ("llvm.exp2", &[bx.type_f64()]),
89        sym::exp2f128 => ("llvm.exp2", &[bx.type_f128()]),
90
91        sym::logf16 => ("llvm.log", &[bx.type_f16()]),
92        sym::logf32 => ("llvm.log", &[bx.type_f32()]),
93        sym::logf64 => ("llvm.log", &[bx.type_f64()]),
94        sym::logf128 => ("llvm.log", &[bx.type_f128()]),
95
96        sym::log10f16 => ("llvm.log10", &[bx.type_f16()]),
97        sym::log10f32 => ("llvm.log10", &[bx.type_f32()]),
98        sym::log10f64 => ("llvm.log10", &[bx.type_f64()]),
99        sym::log10f128 => ("llvm.log10", &[bx.type_f128()]),
100
101        sym::log2f16 => ("llvm.log2", &[bx.type_f16()]),
102        sym::log2f32 => ("llvm.log2", &[bx.type_f32()]),
103        sym::log2f64 => ("llvm.log2", &[bx.type_f64()]),
104        sym::log2f128 => ("llvm.log2", &[bx.type_f128()]),
105
106        sym::fmaf16 => ("llvm.fma", &[bx.type_f16()]),
107        sym::fmaf32 => ("llvm.fma", &[bx.type_f32()]),
108        sym::fmaf64 => ("llvm.fma", &[bx.type_f64()]),
109        sym::fmaf128 => ("llvm.fma", &[bx.type_f128()]),
110
111        sym::fmuladdf16 => ("llvm.fmuladd", &[bx.type_f16()]),
112        sym::fmuladdf32 => ("llvm.fmuladd", &[bx.type_f32()]),
113        sym::fmuladdf64 => ("llvm.fmuladd", &[bx.type_f64()]),
114        sym::fmuladdf128 => ("llvm.fmuladd", &[bx.type_f128()]),
115
116        // FIXME: LLVM currently mis-compile those intrinsics, re-enable them
117        // when llvm/llvm-project#{139380,139381,140445} are fixed.
118        //sym::minimumf16 => ("llvm.minimum", &[bx.type_f16()]),
119        //sym::minimumf32 => ("llvm.minimum", &[bx.type_f32()]),
120        //sym::minimumf64 => ("llvm.minimum", &[bx.type_f64()]),
121        //sym::minimumf128 => ("llvm.minimum", &[cx.type_f128()]),
122        //
123        // FIXME: LLVM currently mis-compile those intrinsics, re-enable them
124        // when llvm/llvm-project#{139380,139381,140445} are fixed.
125        //sym::maximumf16 => ("llvm.maximum", &[bx.type_f16()]),
126        //sym::maximumf32 => ("llvm.maximum", &[bx.type_f32()]),
127        //sym::maximumf64 => ("llvm.maximum", &[bx.type_f64()]),
128        //sym::maximumf128 => ("llvm.maximum", &[cx.type_f128()]),
129        //
130        sym::copysignf16 => ("llvm.copysign", &[bx.type_f16()]),
131        sym::copysignf32 => ("llvm.copysign", &[bx.type_f32()]),
132        sym::copysignf64 => ("llvm.copysign", &[bx.type_f64()]),
133        sym::copysignf128 => ("llvm.copysign", &[bx.type_f128()]),
134
135        sym::floorf16 => ("llvm.floor", &[bx.type_f16()]),
136        sym::floorf32 => ("llvm.floor", &[bx.type_f32()]),
137        sym::floorf64 => ("llvm.floor", &[bx.type_f64()]),
138        sym::floorf128 => ("llvm.floor", &[bx.type_f128()]),
139
140        sym::ceilf16 => ("llvm.ceil", &[bx.type_f16()]),
141        sym::ceilf32 => ("llvm.ceil", &[bx.type_f32()]),
142        sym::ceilf64 => ("llvm.ceil", &[bx.type_f64()]),
143        sym::ceilf128 => ("llvm.ceil", &[bx.type_f128()]),
144
145        sym::truncf16 => ("llvm.trunc", &[bx.type_f16()]),
146        sym::truncf32 => ("llvm.trunc", &[bx.type_f32()]),
147        sym::truncf64 => ("llvm.trunc", &[bx.type_f64()]),
148        sym::truncf128 => ("llvm.trunc", &[bx.type_f128()]),
149
150        // We could use any of `rint`, `nearbyint`, or `roundeven`
151        // for this -- they are all identical in semantics when
152        // assuming the default FP environment.
153        // `rint` is what we used for $forever.
154        sym::round_ties_even_f16 => ("llvm.rint", &[bx.type_f16()]),
155        sym::round_ties_even_f32 => ("llvm.rint", &[bx.type_f32()]),
156        sym::round_ties_even_f64 => ("llvm.rint", &[bx.type_f64()]),
157        sym::round_ties_even_f128 => ("llvm.rint", &[bx.type_f128()]),
158
159        sym::roundf16 => ("llvm.round", &[bx.type_f16()]),
160        sym::roundf32 => ("llvm.round", &[bx.type_f32()]),
161        sym::roundf64 => ("llvm.round", &[bx.type_f64()]),
162        sym::roundf128 => ("llvm.round", &[bx.type_f128()]),
163
164        _ => return None,
165    };
166    Some(bx.call_intrinsic(
167        base_name,
168        type_params,
169        &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
170    ))
171}
172
173impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
174    fn codegen_intrinsic_call(
175        &mut self,
176        instance: ty::Instance<'tcx>,
177        args: &[OperandRef<'tcx, &'ll Value>],
178        result_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 va_end(&mut self, va_list: &'ll Value) {
1074        self.call_intrinsic("llvm.va_end", &[self.val_ty(va_list)], &[va_list]);
1075    }
1076
1077    fn retag_reg(&mut self, ptr: Self::Value, info: &RetagInfo<Self::Value>) -> Self::Value {
1078        codegen_retag_inner(self, "__rust_retag_reg", ptr, info)
1079    }
1080
1081    fn retag_mem(&mut self, ptr: Self::Value, info: &RetagInfo<Self::Value>) {
1082        codegen_retag_inner(self, "__rust_retag_mem", ptr, info);
1083    }
1084}
1085
1086fn llvm_arch_for(rust_arch: &Arch) -> Option<&'static str> {
1087    Some(match rust_arch {
1088        Arch::AArch64 | Arch::Arm64EC => "aarch64",
1089        Arch::AmdGpu => "amdgcn",
1090        Arch::Arm => "arm",
1091        Arch::Bpf => "bpf",
1092        Arch::Hexagon => "hexagon",
1093        Arch::LoongArch32 | Arch::LoongArch64 => "loongarch",
1094        Arch::Mips | Arch::Mips32r6 | Arch::Mips64 | Arch::Mips64r6 => "mips",
1095        Arch::Nvptx64 => "nvvm",
1096        Arch::PowerPC | Arch::PowerPC64 => "ppc",
1097        Arch::RiscV32 | Arch::RiscV64 => "riscv",
1098        Arch::S390x => "s390",
1099        Arch::SpirV => "spv",
1100        Arch::Wasm32 | Arch::Wasm64 => "wasm",
1101        Arch::X86 | Arch::X86_64 => "x86",
1102        _ => return None, // fallback for unknown archs
1103    })
1104}
1105
1106fn can_autocast<'ll>(cx: &CodegenCx<'ll, '_>, rust_ty: &'ll Type, llvm_ty: &'ll Type) -> bool {
1107    if rust_ty == llvm_ty {
1108        return true;
1109    }
1110
1111    match cx.type_kind(llvm_ty) {
1112        // Some LLVM intrinsics return **non-packed** structs, but they can't be mimicked from Rust
1113        // due to auto field-alignment in non-packed structs (packed structs are represented in LLVM
1114        // as, well, packed structs, so they won't match with those either)
1115        TypeKind::Struct if cx.type_kind(rust_ty) == TypeKind::Struct => {
1116            let rust_element_tys = cx.struct_element_types(rust_ty);
1117            let llvm_element_tys = cx.struct_element_types(llvm_ty);
1118
1119            if rust_element_tys.len() != llvm_element_tys.len() {
1120                return false;
1121            }
1122
1123            iter::zip(rust_element_tys, llvm_element_tys).all(
1124                |(rust_element_ty, llvm_element_ty)| {
1125                    can_autocast(cx, rust_element_ty, llvm_element_ty)
1126                },
1127            )
1128        }
1129        TypeKind::Vector => {
1130            let llvm_element_ty = cx.element_type(llvm_ty);
1131            let element_count = cx.vector_length(llvm_ty) as u64;
1132
1133            if llvm_element_ty == cx.type_bf16() {
1134                rust_ty == cx.type_vector(cx.type_i16(), element_count)
1135            } else if llvm_element_ty == cx.type_i1() {
1136                let int_width = element_count.next_power_of_two().max(8);
1137                rust_ty == cx.type_ix(int_width)
1138            } else {
1139                false
1140            }
1141        }
1142        TypeKind::BFloat => rust_ty == cx.type_i16(),
1143        TypeKind::X86_AMX if cx.type_kind(rust_ty) == TypeKind::Vector => {
1144            let element_ty = cx.element_type(rust_ty);
1145            let element_count = cx.vector_length(rust_ty) as u64;
1146
1147            let element_size_bits = match cx.type_kind(element_ty) {
1148                TypeKind::Half => 16,
1149                TypeKind::Float => 32,
1150                TypeKind::Double => 64,
1151                TypeKind::FP128 => 128,
1152                TypeKind::Integer => cx.int_width(element_ty),
1153                TypeKind::Pointer => cx.int_width(cx.isize_ty),
1154                _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Vector element type `{0:?}` not one of integer, float or pointer",
        element_ty))bug!(
1155                    "Vector element type `{element_ty:?}` not one of integer, float or pointer"
1156                ),
1157            };
1158
1159            element_size_bits * element_count == 8192
1160        }
1161        _ => false,
1162    }
1163}
1164
1165fn autocast<'ll>(
1166    bx: &mut Builder<'_, 'll, '_>,
1167    val: &'ll Value,
1168    src_ty: &'ll Type,
1169    dest_ty: &'ll Type,
1170) -> &'ll Value {
1171    if src_ty == dest_ty {
1172        return val;
1173    }
1174    match (bx.type_kind(src_ty), bx.type_kind(dest_ty)) {
1175        // re-pack structs
1176        (TypeKind::Struct, TypeKind::Struct) => {
1177            let mut ret = bx.const_poison(dest_ty);
1178            for (idx, (src_element_ty, dest_element_ty)) in
1179                iter::zip(bx.struct_element_types(src_ty), bx.struct_element_types(dest_ty))
1180                    .enumerate()
1181            {
1182                let elt = bx.extract_value(val, idx as u64);
1183                let casted_elt = autocast(bx, elt, src_element_ty, dest_element_ty);
1184                ret = bx.insert_value(ret, casted_elt, idx as u64);
1185            }
1186            ret
1187        }
1188        // cast from the i1xN vector type to the primitive type
1189        (TypeKind::Vector, TypeKind::Integer) if bx.element_type(src_ty) == bx.type_i1() => {
1190            let vector_length = bx.vector_length(src_ty) as u64;
1191            let int_width = vector_length.next_power_of_two().max(8);
1192
1193            let val = if vector_length == int_width {
1194                val
1195            } else {
1196                // zero-extends vector
1197                let shuffle_indices = match vector_length {
1198                    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"),
1199                    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],
1200                    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],
1201                    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],
1202                    4.. => (0..int_width as i32).collect(),
1203                };
1204                let shuffle_mask =
1205                    shuffle_indices.into_iter().map(|i| bx.const_i32(i)).collect::<Vec<_>>();
1206                bx.shuffle_vector(val, bx.const_null(src_ty), bx.const_vector(&shuffle_mask))
1207            };
1208            bx.bitcast(val, dest_ty)
1209        }
1210        // cast from the primitive type to the i1xN vector type
1211        (TypeKind::Integer, TypeKind::Vector) if bx.element_type(dest_ty) == bx.type_i1() => {
1212            let vector_length = bx.vector_length(dest_ty) as u64;
1213            let int_width = vector_length.next_power_of_two().max(8);
1214
1215            let intermediate_ty = bx.type_vector(bx.type_i1(), int_width);
1216            let intermediate = bx.bitcast(val, intermediate_ty);
1217
1218            if vector_length == int_width {
1219                intermediate
1220            } else {
1221                let shuffle_mask: Vec<_> =
1222                    (0..vector_length).map(|i| bx.const_i32(i as i32)).collect();
1223                bx.shuffle_vector(
1224                    intermediate,
1225                    bx.const_poison(intermediate_ty),
1226                    bx.const_vector(&shuffle_mask),
1227                )
1228            }
1229        }
1230        (TypeKind::Vector, TypeKind::X86_AMX) => {
1231            bx.call_intrinsic("llvm.x86.cast.vector.to.tile", &[src_ty], &[val])
1232        }
1233        (TypeKind::X86_AMX, TypeKind::Vector) => {
1234            bx.call_intrinsic("llvm.x86.cast.tile.to.vector", &[dest_ty], &[val])
1235        }
1236        _ => bx.bitcast(val, dest_ty), // for `bf16(xN)` <-> `u16(xN)`
1237    }
1238}
1239
1240fn intrinsic_fn<'ll, 'tcx>(
1241    bx: &Builder<'_, 'll, 'tcx>,
1242    name: &str,
1243    rust_return_ty: &'ll Type,
1244    rust_argument_tys: Vec<&'ll Type>,
1245    instance: ty::Instance<'tcx>,
1246) -> &'ll Value {
1247    let tcx = bx.tcx;
1248
1249    let rust_fn_ty = bx.type_func(&rust_argument_tys, rust_return_ty);
1250
1251    let intrinsic = llvm::Intrinsic::lookup(name.as_bytes());
1252
1253    if let Some(intrinsic) = intrinsic
1254        && intrinsic.is_target_specific()
1255    {
1256        let (llvm_arch, _) = name[5..].split_once('.').unwrap();
1257        let rust_arch = &tcx.sess.target.arch;
1258
1259        if let Some(correct_llvm_arch) = llvm_arch_for(rust_arch)
1260            && llvm_arch != correct_llvm_arch
1261        {
1262            tcx.dcx().emit_fatal(IntrinsicWrongArch {
1263                name,
1264                target_arch: rust_arch.desc(),
1265                span: tcx.def_span(instance.def_id()),
1266            });
1267        }
1268    }
1269
1270    if let Some(intrinsic) = intrinsic
1271        && !intrinsic.is_overloaded()
1272    {
1273        // FIXME: also do this for overloaded intrinsics
1274        let llfn = intrinsic.get_declaration(bx.llmod, &[]);
1275        let llvm_fn_ty = bx.get_type_of_global(llfn);
1276
1277        let llvm_return_ty = bx.get_return_type(llvm_fn_ty);
1278        let llvm_argument_tys = bx.func_params_types(llvm_fn_ty);
1279        let llvm_is_variadic = bx.func_is_variadic(llvm_fn_ty);
1280
1281        let is_correct_signature = !llvm_is_variadic
1282            && rust_argument_tys.len() == llvm_argument_tys.len()
1283            && iter::once((rust_return_ty, llvm_return_ty))
1284                .chain(iter::zip(rust_argument_tys, llvm_argument_tys))
1285                .all(|(rust_ty, llvm_ty)| can_autocast(bx, rust_ty, llvm_ty));
1286
1287        if !is_correct_signature {
1288            tcx.dcx().emit_fatal(IntrinsicSignatureMismatch {
1289                name,
1290                llvm_fn_ty: &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", llvm_fn_ty))
    })format!("{llvm_fn_ty:?}"),
1291                rust_fn_ty: &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", rust_fn_ty))
    })format!("{rust_fn_ty:?}"),
1292                span: tcx.def_span(instance.def_id()),
1293            });
1294        }
1295
1296        return llfn;
1297    }
1298
1299    // Function addresses in Rust are never significant, allowing functions to be merged.
1300    let llfn = declare_raw_fn(
1301        bx,
1302        name,
1303        llvm::CCallConv,
1304        llvm::UnnamedAddr::Global,
1305        llvm::Visibility::Default,
1306        rust_fn_ty,
1307    );
1308
1309    if intrinsic.is_none() {
1310        let mut new_llfn = None;
1311        let can_upgrade = unsafe { llvm::LLVMRustUpgradeIntrinsicFunction(llfn, &mut new_llfn) };
1312
1313        if !can_upgrade {
1314            // This is either plain wrong, or this can be caused by incompatible LLVM versions
1315            tcx.dcx().emit_fatal(UnknownIntrinsic { name, span: tcx.def_span(instance.def_id()) });
1316        } else if let Some(def_id) = instance.def_id().as_local() {
1317            // we can emit diagnostics only for local crates
1318            let hir_id = tcx.local_def_id_to_hir_id(def_id);
1319
1320            // not all intrinsics are upgraded to some other intrinsics, most are upgraded to instruction sequences
1321            let msg = if let Some(new_llfn) = new_llfn {
1322                ::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!(
1323                    "using deprecated intrinsic `{name}`, `{}` can be used instead",
1324                    str::from_utf8(&llvm::get_value_name(new_llfn)).unwrap()
1325                )
1326            } else {
1327                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("using deprecated intrinsic `{0}`",
                name))
    })format!("using deprecated intrinsic `{name}`")
1328            };
1329
1330            tcx.emit_node_lint(
1331                DEPRECATED_LLVM_INTRINSIC,
1332                hir_id,
1333                rustc_errors::DiagDecorator(|d| {
1334                    d.primary_message(msg).span(tcx.hir_span(hir_id));
1335                }),
1336            );
1337        }
1338    }
1339
1340    llfn
1341}
1342
1343fn catch_unwind_intrinsic<'ll, 'tcx>(
1344    bx: &mut Builder<'_, 'll, 'tcx>,
1345    try_func: &'ll Value,
1346    data: &'ll Value,
1347    catch_func: &'ll Value,
1348) -> &'ll Value {
1349    if !bx.sess().panic_strategy().unwinds() {
1350        let try_func_ty = bx.type_func(&[bx.type_ptr()], bx.type_void());
1351        bx.call(try_func_ty, None, None, try_func, &[data], None, None);
1352        // Return 0 unconditionally from the intrinsic call;
1353        // we can never unwind.
1354        bx.const_bool(false)
1355    } else if wants_msvc_seh(bx.sess()) {
1356        codegen_msvc_try(bx, try_func, data, catch_func)
1357    } else if wants_wasm_eh(bx.sess()) {
1358        codegen_wasm_try(bx, try_func, data, catch_func)
1359    } else if bx.sess().target.os == Os::Emscripten {
1360        codegen_emcc_try(bx, try_func, data, catch_func)
1361    } else {
1362        codegen_gnu_try(bx, try_func, data, catch_func)
1363    }
1364}
1365
1366// MSVC's definition of the `rust_try` function.
1367//
1368// This implementation uses the new exception handling instructions in LLVM
1369// which have support in LLVM for SEH on MSVC targets. Although these
1370// instructions are meant to work for all targets, as of the time of this
1371// writing, however, LLVM does not recommend the usage of these new instructions
1372// as the old ones are still more optimized.
1373fn codegen_msvc_try<'ll, 'tcx>(
1374    bx: &mut Builder<'_, 'll, 'tcx>,
1375    try_func: &'ll Value,
1376    data: &'ll Value,
1377    catch_func: &'ll Value,
1378) -> &'ll Value {
1379    let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
1380        bx.set_personality_fn(bx.eh_personality());
1381
1382        let normal = bx.append_sibling_block("normal");
1383        let catchswitch = bx.append_sibling_block("catchswitch");
1384        let catchpad_rust = bx.append_sibling_block("catchpad_rust");
1385        let catchpad_foreign = bx.append_sibling_block("catchpad_foreign");
1386        let caught = bx.append_sibling_block("caught");
1387
1388        let try_func = llvm::get_param(bx.llfn(), 0);
1389        let data = llvm::get_param(bx.llfn(), 1);
1390        let catch_func = llvm::get_param(bx.llfn(), 2);
1391
1392        // We're generating an IR snippet that looks like:
1393        //
1394        //   declare bool @rust_try(%try_func, %data, %catch_func) {
1395        //      %slot = alloca i8*
1396        //      invoke %try_func(%data) to label %normal unwind label %catchswitch
1397        //
1398        //   normal:
1399        //      ret i1 false
1400        //
1401        //   catchswitch:
1402        //      %cs = catchswitch within none [%catchpad_rust, %catchpad_foreign] unwind to caller
1403        //
1404        //   catchpad_rust:
1405        //      %tok = catchpad within %cs [%type_descriptor, 8, %slot]
1406        //      %ptr = load %slot
1407        //      call %catch_func(%data, %ptr)
1408        //      catchret from %tok to label %caught
1409        //
1410        //   catchpad_foreign:
1411        //      %tok = catchpad within %cs [null, 64, null]
1412        //      call %catch_func(%data, null)
1413        //      catchret from %tok to label %caught
1414        //
1415        //   caught:
1416        //      ret i1 true
1417        //   }
1418        //
1419        // This structure follows the basic usage of throw/try/catch in LLVM.
1420        // For example, compile this C++ snippet to see what LLVM generates:
1421        //
1422        //      struct rust_panic {
1423        //          rust_panic(const rust_panic&);
1424        //          ~rust_panic();
1425        //
1426        //          void* x[2];
1427        //      };
1428        //
1429        //      int __rust_try(
1430        //          void (*try_func)(void*),
1431        //          void *data,
1432        //          void (*catch_func)(void*, void*) noexcept
1433        //      ) {
1434        //          try {
1435        //              try_func(data);
1436        //              return 0;
1437        //          } catch(rust_panic& a) {
1438        //              catch_func(data, &a);
1439        //              return 1;
1440        //          } catch(...) {
1441        //              catch_func(data, NULL);
1442        //              return 1;
1443        //          }
1444        //      }
1445        //
1446        // More information can be found in libstd's seh.rs implementation.
1447        let ptr_size = bx.tcx().data_layout.pointer_size();
1448        let ptr_align = bx.tcx().data_layout.pointer_align().abi;
1449        let slot = bx.alloca(ptr_size, ptr_align);
1450        let try_func_ty = bx.type_func(&[bx.type_ptr()], bx.type_void());
1451        bx.invoke(try_func_ty, None, None, try_func, &[data], normal, catchswitch, None, None);
1452
1453        bx.switch_to_block(normal);
1454        bx.ret(bx.const_bool(false));
1455
1456        bx.switch_to_block(catchswitch);
1457        let cs = bx.catch_switch(None, None, &[catchpad_rust, catchpad_foreign]);
1458
1459        // We can't use the TypeDescriptor defined in libpanic_unwind because it
1460        // might be in another DLL and the SEH encoding only supports specifying
1461        // a TypeDescriptor from the current module.
1462        //
1463        // However this isn't an issue since the MSVC runtime uses string
1464        // comparison on the type name to match TypeDescriptors rather than
1465        // pointer equality.
1466        //
1467        // So instead we generate a new TypeDescriptor in each module that uses
1468        // `try` and let the linker merge duplicate definitions in the same
1469        // module.
1470        //
1471        // When modifying, make sure that the type_name string exactly matches
1472        // the one used in library/panic_unwind/src/seh.rs.
1473        let type_info_vtable = bx.declare_global("??_7type_info@@6B@", bx.type_ptr());
1474        let type_name = bx.const_bytes(b"rust_panic\0");
1475        let type_info =
1476            bx.const_struct(&[type_info_vtable, bx.const_null(bx.type_ptr()), type_name], false);
1477        let tydesc = bx.declare_global(
1478            &mangle_internal_symbol(bx.tcx, "__rust_panic_type_info"),
1479            bx.val_ty(type_info),
1480        );
1481
1482        llvm::set_linkage(tydesc, llvm::Linkage::LinkOnceODRLinkage);
1483        if bx.cx.tcx.sess.target.supports_comdat() {
1484            llvm::SetUniqueComdat(bx.llmod, tydesc);
1485        }
1486        llvm::set_initializer(tydesc, type_info);
1487
1488        // The flag value of 8 indicates that we are catching the exception by
1489        // reference instead of by value. We can't use catch by value because
1490        // that requires copying the exception object, which we don't support
1491        // since our exception object effectively contains a Box.
1492        //
1493        // Source: MicrosoftCXXABI::getAddrOfCXXCatchHandlerType in clang
1494        bx.switch_to_block(catchpad_rust);
1495        let flags = bx.const_i32(8);
1496        let funclet = bx.catch_pad(cs, &[tydesc, flags, slot]);
1497        let ptr = bx.load(bx.type_ptr(), slot, ptr_align);
1498        let catch_ty = bx.type_func(&[bx.type_ptr(), bx.type_ptr()], bx.type_void());
1499        bx.call(catch_ty, None, None, catch_func, &[data, ptr], Some(&funclet), None);
1500        bx.catch_ret(&funclet, caught);
1501
1502        // The flag value of 64 indicates a "catch-all".
1503        bx.switch_to_block(catchpad_foreign);
1504        let flags = bx.const_i32(64);
1505        let null = bx.const_null(bx.type_ptr());
1506        let funclet = bx.catch_pad(cs, &[null, flags, null]);
1507        bx.call(catch_ty, None, None, catch_func, &[data, null], Some(&funclet), None);
1508        bx.catch_ret(&funclet, caught);
1509
1510        bx.switch_to_block(caught);
1511        bx.ret(bx.const_bool(true));
1512    });
1513
1514    // Note that no invoke is used here because by definition this function
1515    // can't panic (that's what it's catching).
1516    let ret = bx.call(llty, None, None, llfn, &[try_func, data, catch_func], None, None);
1517    ret
1518}
1519
1520// WASM's definition of the `rust_try` function.
1521fn codegen_wasm_try<'ll, 'tcx>(
1522    bx: &mut Builder<'_, 'll, 'tcx>,
1523    try_func: &'ll Value,
1524    data: &'ll Value,
1525    catch_func: &'ll Value,
1526) -> &'ll Value {
1527    let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
1528        bx.set_personality_fn(bx.eh_personality());
1529
1530        let normal = bx.append_sibling_block("normal");
1531        let catchswitch = bx.append_sibling_block("catchswitch");
1532        let catchpad = bx.append_sibling_block("catchpad");
1533        let caught = bx.append_sibling_block("caught");
1534
1535        let try_func = llvm::get_param(bx.llfn(), 0);
1536        let data = llvm::get_param(bx.llfn(), 1);
1537        let catch_func = llvm::get_param(bx.llfn(), 2);
1538
1539        // We're generating an IR snippet that looks like:
1540        //
1541        //   declare i1 @rust_try(%try_func, %data, %catch_func) {
1542        //      %slot = alloca i8*
1543        //      invoke %try_func(%data) to label %normal unwind label %catchswitch
1544        //
1545        //   normal:
1546        //      ret i1 false
1547        //
1548        //   catchswitch:
1549        //      %cs = catchswitch within none [%catchpad] unwind to caller
1550        //
1551        //   catchpad:
1552        //      %tok = catchpad within %cs [null]
1553        //      %ptr = call @llvm.wasm.get.exception(token %tok)
1554        //      %sel = call @llvm.wasm.get.ehselector(token %tok)
1555        //      call %catch_func(%data, %ptr)
1556        //      catchret from %tok to label %caught
1557        //
1558        //   caught:
1559        //      ret i1 true
1560        //   }
1561        //
1562        let try_func_ty = bx.type_func(&[bx.type_ptr()], bx.type_void());
1563        bx.invoke(try_func_ty, None, None, try_func, &[data], normal, catchswitch, None, None);
1564
1565        bx.switch_to_block(normal);
1566        bx.ret(bx.const_bool(false));
1567
1568        bx.switch_to_block(catchswitch);
1569        let cs = bx.catch_switch(None, None, &[catchpad]);
1570
1571        bx.switch_to_block(catchpad);
1572        let null = bx.const_null(bx.type_ptr());
1573        let funclet = bx.catch_pad(cs, &[null]);
1574
1575        let ptr = bx.call_intrinsic("llvm.wasm.get.exception", &[], &[funclet.cleanuppad()]);
1576        let _sel = bx.call_intrinsic("llvm.wasm.get.ehselector", &[], &[funclet.cleanuppad()]);
1577
1578        let catch_ty = bx.type_func(&[bx.type_ptr(), bx.type_ptr()], bx.type_void());
1579        bx.call(catch_ty, None, None, catch_func, &[data, ptr], Some(&funclet), None);
1580        bx.catch_ret(&funclet, caught);
1581
1582        bx.switch_to_block(caught);
1583        bx.ret(bx.const_bool(true));
1584    });
1585
1586    // Note that no invoke is used here because by definition this function
1587    // can't panic (that's what it's catching).
1588    let ret = bx.call(llty, None, None, llfn, &[try_func, data, catch_func], None, None);
1589    ret
1590}
1591
1592// Definition of the standard `try` function for Rust using the GNU-like model
1593// of exceptions (e.g., the normal semantics of LLVM's `landingpad` and `invoke`
1594// instructions).
1595//
1596// This codegen is a little surprising because we always call a shim
1597// function instead of inlining the call to `invoke` manually here. This is done
1598// because in LLVM we're only allowed to have one personality per function
1599// definition. The call to the `try` intrinsic is being inlined into the
1600// function calling it, and that function may already have other personality
1601// functions in play. By calling a shim we're guaranteed that our shim will have
1602// the right personality function.
1603fn codegen_gnu_try<'ll, 'tcx>(
1604    bx: &mut Builder<'_, 'll, 'tcx>,
1605    try_func: &'ll Value,
1606    data: &'ll Value,
1607    catch_func: &'ll Value,
1608) -> &'ll Value {
1609    let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
1610        // Codegens the shims described above:
1611        //
1612        //   bx:
1613        //      invoke %try_func(%data) normal %normal unwind %catch
1614        //
1615        //   normal:
1616        //      ret 0
1617        //
1618        //   catch:
1619        //      (%ptr, _) = landingpad
1620        //      call %catch_func(%data, %ptr)
1621        //      ret 1
1622        let then = bx.append_sibling_block("then");
1623        let catch = bx.append_sibling_block("catch");
1624
1625        let try_func = llvm::get_param(bx.llfn(), 0);
1626        let data = llvm::get_param(bx.llfn(), 1);
1627        let catch_func = llvm::get_param(bx.llfn(), 2);
1628        let try_func_ty = bx.type_func(&[bx.type_ptr()], bx.type_void());
1629        bx.invoke(try_func_ty, None, None, try_func, &[data], then, catch, None, None);
1630
1631        bx.switch_to_block(then);
1632        bx.ret(bx.const_bool(false));
1633
1634        // Type indicator for the exception being thrown.
1635        //
1636        // The first value in this tuple is a pointer to the exception object
1637        // being thrown. The second value is a "selector" indicating which of
1638        // the landing pad clauses the exception's type had been matched to.
1639        // rust_try ignores the selector.
1640        bx.switch_to_block(catch);
1641        let lpad_ty = bx.type_struct(&[bx.type_ptr(), bx.type_i32()], false);
1642        let vals = bx.landing_pad(lpad_ty, bx.eh_personality(), 1);
1643        let tydesc = bx.const_null(bx.type_ptr());
1644        bx.add_clause(vals, tydesc);
1645        let ptr = bx.extract_value(vals, 0);
1646        let catch_ty = bx.type_func(&[bx.type_ptr(), bx.type_ptr()], bx.type_void());
1647        bx.call(catch_ty, None, None, catch_func, &[data, ptr], None, None);
1648        bx.ret(bx.const_bool(true));
1649    });
1650
1651    // Note that no invoke is used here because by definition this function
1652    // can't panic (that's what it's catching).
1653    let ret = bx.call(llty, None, None, llfn, &[try_func, data, catch_func], None, None);
1654    ret
1655}
1656
1657// Variant of codegen_gnu_try used for emscripten where Rust panics are
1658// implemented using C++ exceptions. Here we use exceptions of a specific type
1659// (`struct rust_panic`) to represent Rust panics.
1660fn codegen_emcc_try<'ll, 'tcx>(
1661    bx: &mut Builder<'_, 'll, 'tcx>,
1662    try_func: &'ll Value,
1663    data: &'ll Value,
1664    catch_func: &'ll Value,
1665) -> &'ll Value {
1666    let (llty, llfn) = get_rust_try_fn(bx, &mut |mut bx| {
1667        // Codegens the shims described above:
1668        //
1669        //   bx:
1670        //      invoke %try_func(%data) normal %normal unwind %catch
1671        //
1672        //   normal:
1673        //      ret 0
1674        //
1675        //   catch:
1676        //      (%ptr, %selector) = landingpad
1677        //      %rust_typeid = @llvm.eh.typeid.for(@_ZTI10rust_panic)
1678        //      %is_rust_panic = %selector == %rust_typeid
1679        //      %catch_data = alloca { i8*, i8 }
1680        //      %catch_data[0] = %ptr
1681        //      %catch_data[1] = %is_rust_panic
1682        //      call %catch_func(%data, %catch_data)
1683        //      ret 1
1684        let then = bx.append_sibling_block("then");
1685        let catch = bx.append_sibling_block("catch");
1686
1687        let try_func = llvm::get_param(bx.llfn(), 0);
1688        let data = llvm::get_param(bx.llfn(), 1);
1689        let catch_func = llvm::get_param(bx.llfn(), 2);
1690        let try_func_ty = bx.type_func(&[bx.type_ptr()], bx.type_void());
1691        bx.invoke(try_func_ty, None, None, try_func, &[data], then, catch, None, None);
1692
1693        bx.switch_to_block(then);
1694        bx.ret(bx.const_bool(false));
1695
1696        // Type indicator for the exception being thrown.
1697        //
1698        // The first value in this tuple is a pointer to the exception object
1699        // being thrown. The second value is a "selector" indicating which of
1700        // the landing pad clauses the exception's type had been matched to.
1701        bx.switch_to_block(catch);
1702        let tydesc = bx.eh_catch_typeinfo();
1703        let lpad_ty = bx.type_struct(&[bx.type_ptr(), bx.type_i32()], false);
1704        let vals = bx.landing_pad(lpad_ty, bx.eh_personality(), 2);
1705        bx.add_clause(vals, tydesc);
1706        bx.add_clause(vals, bx.const_null(bx.type_ptr()));
1707        let ptr = bx.extract_value(vals, 0);
1708        let selector = bx.extract_value(vals, 1);
1709
1710        // Check if the typeid we got is the one for a Rust panic.
1711        let rust_typeid = bx.call_intrinsic("llvm.eh.typeid.for", &[bx.val_ty(tydesc)], &[tydesc]);
1712        let is_rust_panic = bx.icmp(IntPredicate::IntEQ, selector, rust_typeid);
1713        let is_rust_panic = bx.zext(is_rust_panic, bx.type_bool());
1714
1715        // We need to pass two values to catch_func (ptr and is_rust_panic), so
1716        // create an alloca and pass a pointer to that.
1717        let ptr_size = bx.tcx().data_layout.pointer_size();
1718        let ptr_align = bx.tcx().data_layout.pointer_align().abi;
1719        let i8_align = bx.tcx().data_layout.i8_align;
1720        // Required in order for there to be no padding between the fields.
1721        if !(i8_align <= ptr_align) {
    ::core::panicking::panic("assertion failed: i8_align <= ptr_align")
};assert!(i8_align <= ptr_align);
1722        let catch_data = bx.alloca(2 * ptr_size, ptr_align);
1723        bx.store(ptr, catch_data, ptr_align);
1724        let catch_data_1 = bx.inbounds_ptradd(catch_data, bx.const_usize(ptr_size.bytes()));
1725        bx.store(is_rust_panic, catch_data_1, i8_align);
1726
1727        let catch_ty = bx.type_func(&[bx.type_ptr(), bx.type_ptr()], bx.type_void());
1728        bx.call(catch_ty, None, None, catch_func, &[data, catch_data], None, None);
1729        bx.ret(bx.const_bool(true));
1730    });
1731
1732    // Note that no invoke is used here because by definition this function
1733    // can't panic (that's what it's catching).
1734    let ret = bx.call(llty, None, None, llfn, &[try_func, data, catch_func], None, None);
1735    ret
1736}
1737
1738// Helper function to give a Block to a closure to codegen a shim function.
1739// This is currently primarily used for the `try` intrinsic functions above.
1740fn gen_fn<'a, 'll, 'tcx>(
1741    cx: &'a CodegenCx<'ll, 'tcx>,
1742    name: &str,
1743    rust_fn_sig: ty::PolyFnSig<'tcx>,
1744    codegen: &mut dyn FnMut(Builder<'a, 'll, 'tcx>),
1745) -> (&'ll Type, &'ll Value) {
1746    let fn_abi = cx.fn_abi_of_fn_ptr(rust_fn_sig, ty::List::empty());
1747    let llty = fn_abi.llvm_type(cx);
1748    let llfn = cx.declare_fn(name, fn_abi, None);
1749    cx.set_frame_pointer_type(llfn);
1750    cx.apply_target_cpu_attr(llfn);
1751    // FIXME(eddyb) find a nicer way to do this.
1752    llvm::set_linkage(llfn, llvm::Linkage::InternalLinkage);
1753    let llbb = Builder::append_block(cx, llfn, "entry-block");
1754    let bx = Builder::build(cx, llbb);
1755    codegen(bx);
1756    (llty, llfn)
1757}
1758
1759// Helper function used to get a handle to the `__rust_try` function used to
1760// catch exceptions.
1761//
1762// This function is only generated once and is then cached.
1763fn get_rust_try_fn<'a, 'll, 'tcx>(
1764    cx: &'a CodegenCx<'ll, 'tcx>,
1765    codegen: &mut dyn FnMut(Builder<'a, 'll, 'tcx>),
1766) -> (&'ll Type, &'ll Value) {
1767    if let Some(llfn) = cx.rust_try_fn.get() {
1768        return llfn;
1769    }
1770
1771    // Define the type up front for the signature of the rust_try function.
1772    let tcx = cx.tcx;
1773    let i8p = Ty::new_mut_ptr(tcx, tcx.types.i8);
1774    // `unsafe fn(*mut Data) -> ()`
1775    let try_fn_ty = Ty::new_fn_ptr(
1776        tcx,
1777        ty::Binder::dummy(tcx.mk_fn_sig_rust_abi([i8p], tcx.types.unit, hir::Safety::Unsafe)),
1778    );
1779    // `unsafe fn(*mut Data, *mut i8) -> ()`
1780    let catch_fn_ty = Ty::new_fn_ptr(
1781        tcx,
1782        ty::Binder::dummy(tcx.mk_fn_sig_rust_abi([i8p, i8p], tcx.types.unit, hir::Safety::Unsafe)),
1783    );
1784    // `unsafe fn(unsafe fn(*mut Data) -> (), *mut Data, unsafe fn(*mut Data, *mut i8) -> ()) -> bool`
1785    let rust_fn_sig = ty::Binder::dummy(cx.tcx.mk_fn_sig_rust_abi(
1786        [try_fn_ty, i8p, catch_fn_ty],
1787        tcx.types.bool,
1788        hir::Safety::Unsafe,
1789    ));
1790    let rust_try = gen_fn(cx, "__rust_try", rust_fn_sig, codegen);
1791    cx.rust_try_fn.set(Some(rust_try));
1792    rust_try
1793}
1794
1795fn codegen_retag_inner<'ll, 'tcx>(
1796    bx: &mut Builder<'_, 'll, 'tcx>,
1797    name: &'static str,
1798    ptr: &'ll Value,
1799    info: &RetagInfo<&'ll Value>,
1800) -> &'ll Value {
1801    let size = bx.const_usize(info.size.bytes());
1802    let perms = bx.const_u8(info.flags.bits());
1803
1804    bx.call_intrinsic(
1805        name,
1806        // Retag intrinsics have special handling within `CodegenCx::declare_intrinsic`
1807        // to ensure that each form has the correct return type.
1808        &[bx.type_ptr(), bx.val_ty(size), bx.type_i8(), bx.type_ptr(), bx.type_ptr()],
1809        &[ptr, size, perms, info.im_layout, info.pin_layout],
1810    )
1811}
1812
1813fn codegen_autodiff<'ll, 'tcx>(
1814    bx: &mut Builder<'_, 'll, 'tcx>,
1815    tcx: TyCtxt<'tcx>,
1816    instance: ty::Instance<'tcx>,
1817    args: &[OperandRef<'tcx, &'ll Value>],
1818    result: PlaceRef<'tcx, &'ll Value>,
1819) {
1820    if !tcx.sess.opts.unstable_opts.autodiff.contains(&rustc_session::config::AutoDiff::Enable) {
1821        let _ = tcx.dcx().emit_almost_fatal(AutoDiffWithoutEnable);
1822    }
1823
1824    let ct = tcx.crate_types();
1825    let lto = tcx.sess.lto();
1826    if ct.len() == 1 && ct.contains(&CrateType::Executable) {
1827        if lto != rustc_session::config::Lto::Fat {
1828            let _ = tcx.dcx().emit_almost_fatal(AutoDiffWithoutLto);
1829        }
1830    } else {
1831        if lto != rustc_session::config::Lto::Fat && !tcx.sess.opts.cg.linker_plugin_lto.enabled() {
1832            let _ = tcx.dcx().emit_almost_fatal(AutoDiffWithoutLto);
1833        }
1834    }
1835
1836    let fn_args = instance.args;
1837    let callee_ty = instance.ty(tcx, bx.typing_env());
1838
1839    let sig = callee_ty.fn_sig(tcx).skip_binder();
1840
1841    let ret_ty = sig.output();
1842    let llret_ty = bx.layout_of(ret_ty).llvm_type(bx);
1843
1844    let source_fn_ptr_ty = fn_args.into_type_list(tcx)[0];
1845    let fn_to_diff = args[0].immediate();
1846
1847    let (diff_id, diff_args) = match fn_args.into_type_list(tcx)[1].kind() {
1848        ty::FnDef(def_id, diff_args) => (def_id, diff_args),
1849        _ => ::rustc_middle::util::bug::bug_fmt(format_args!("invalid args"))bug!("invalid args"),
1850    };
1851
1852    let fn_diff = match Instance::try_resolve(tcx, bx.cx.typing_env(), *diff_id, diff_args) {
1853        Ok(Some(instance)) => instance,
1854        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!(
1855            "could not resolve ({:?}, {:?}) to a specific autodiff instance",
1856            diff_id,
1857            diff_args
1858        ),
1859        Err(_) => {
1860            // An error has already been emitted
1861            return;
1862        }
1863    };
1864
1865    let val_arr = get_args_from_tuple(bx, args[2], fn_diff);
1866    let diff_symbol = symbol_name_for_instance_in_crate(tcx, fn_diff.clone(), LOCAL_CRATE);
1867
1868    let Some(Some(mut diff_attrs)) =
1869        {
    {
        '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())
1870    else {
1871        ::rustc_middle::util::bug::bug_fmt(format_args!("could not find autodiff attrs"))bug!("could not find autodiff attrs")
1872    };
1873
1874    adjust_activity_to_abi(
1875        tcx,
1876        source_fn_ptr_ty,
1877        TypingEnv::fully_monomorphized(),
1878        &mut diff_attrs.input_activity,
1879    );
1880
1881    let fnc_tree = rustc_middle::ty::fnc_typetrees(tcx, source_fn_ptr_ty);
1882
1883    // Build body
1884    generate_enzyme_call(
1885        bx,
1886        bx.cx,
1887        fn_to_diff,
1888        &diff_symbol,
1889        llret_ty,
1890        &val_arr,
1891        &diff_attrs,
1892        result,
1893        fnc_tree,
1894    );
1895}
1896
1897// Generates the LLVM code to offload a Rust function to a target device (e.g., GPU).
1898// For each kernel call, it generates the necessary globals (including metadata such as
1899// size and pass mode), manages memory mapping to and from the device, handles all
1900// data transfers, and launches the kernel on the target device.
1901fn codegen_offload<'ll, 'tcx>(
1902    bx: &mut Builder<'_, 'll, 'tcx>,
1903    tcx: TyCtxt<'tcx>,
1904    instance: ty::Instance<'tcx>,
1905    args: &[OperandRef<'tcx, &'ll Value>],
1906) {
1907    let cx = bx.cx;
1908    let fn_args = instance.args;
1909
1910    let (target_id, target_args) = match fn_args.into_type_list(tcx)[0].kind() {
1911        ty::FnDef(def_id, params) => (def_id, params),
1912        _ => ::rustc_middle::util::bug::bug_fmt(format_args!("invalid offload intrinsic arg"))bug!("invalid offload intrinsic arg"),
1913    };
1914
1915    let fn_target = match Instance::try_resolve(tcx, cx.typing_env(), *target_id, target_args) {
1916        Ok(Some(instance)) => instance,
1917        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!(
1918            "could not resolve ({:?}, {:?}) to a specific offload instance",
1919            target_id,
1920            target_args
1921        ),
1922        Err(_) => {
1923            // An error has already been emitted
1924            return;
1925        }
1926    };
1927
1928    let offload_dims = OffloadKernelDims::from_operands(bx, &args[1], &args[2]);
1929    let dyn_cache = match args[3].val {
1930        OperandValue::Immediate(val) => val,
1931        _ => { ::core::panicking::panic_fmt(format_args!("unparsable")); }panic!("unparsable"),
1932    };
1933    let args = get_args_from_tuple(bx, args[4], fn_target);
1934    let target_symbol = symbol_name_for_instance_in_crate(tcx, fn_target, LOCAL_CRATE);
1935
1936    let sig = tcx.fn_sig(fn_target.def_id()).skip_binder();
1937    let sig = tcx.instantiate_bound_regions_with_erased(sig);
1938    let inputs = sig.inputs();
1939
1940    let fn_abi = cx.fn_abi_of_instance(fn_target, ty::List::empty());
1941
1942    let mut metadata = Vec::new();
1943    let mut types = Vec::new();
1944
1945    for (i, arg_abi) in fn_abi.args.iter().enumerate() {
1946        let ty = inputs[i];
1947        let decomposed = OffloadMetadata::handle_abi(cx, tcx, ty, arg_abi);
1948
1949        for (meta, entry_ty) in decomposed {
1950            metadata.push(meta);
1951            types.push(bx.cx.layout_of(entry_ty).llvm_type(bx.cx));
1952        }
1953    }
1954
1955    let offload_globals_ref = cx.offload_globals.borrow();
1956    let offload_globals = match offload_globals_ref.as_ref() {
1957        Some(globals) => globals,
1958        None => {
1959            // Offload is not initialized, cannot continue
1960            return;
1961        }
1962    };
1963    register_offload(cx);
1964    let offload_data = gen_define_handling(&cx, &metadata, target_symbol, offload_globals);
1965    gen_call_handling(
1966        bx,
1967        &offload_data,
1968        &args,
1969        &types,
1970        &metadata,
1971        offload_globals,
1972        &offload_dims,
1973        &dyn_cache,
1974    );
1975}
1976
1977fn get_args_from_tuple<'ll, 'tcx>(
1978    bx: &mut Builder<'_, 'll, 'tcx>,
1979    tuple_op: OperandRef<'tcx, &'ll Value>,
1980    fn_instance: Instance<'tcx>,
1981) -> Vec<&'ll Value> {
1982    let cx = bx.cx;
1983    let fn_abi = cx.fn_abi_of_instance(fn_instance, ty::List::empty());
1984
1985    match tuple_op.val {
1986        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],
1987        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],
1988        OperandValue::Ref(ptr) => {
1989            let tuple_place = PlaceRef { val: ptr, layout: tuple_op.layout };
1990
1991            let mut result = Vec::with_capacity(fn_abi.args.len());
1992            let mut tuple_index = 0;
1993
1994            for arg in &fn_abi.args {
1995                match arg.mode {
1996                    PassMode::Ignore => {}
1997                    PassMode::Direct(_) | PassMode::Cast { .. } => {
1998                        let field = tuple_place.project_field(bx, tuple_index);
1999                        let llvm_ty = field.layout.llvm_type(bx.cx);
2000                        let val = bx.load(llvm_ty, field.val.llval, field.val.align);
2001                        result.push(val);
2002                        tuple_index += 1;
2003                    }
2004                    PassMode::Pair(_, _) => {
2005                        let field = tuple_place.project_field(bx, tuple_index);
2006                        let llvm_ty = field.layout.llvm_type(bx.cx);
2007                        let pair_val = bx.load(llvm_ty, field.val.llval, field.val.align);
2008                        result.push(bx.extract_value(pair_val, 0));
2009                        result.push(bx.extract_value(pair_val, 1));
2010                        tuple_index += 1;
2011                    }
2012                    PassMode::Indirect { .. } => {
2013                        let field = tuple_place.project_field(bx, tuple_index);
2014                        result.push(field.val.llval);
2015                        tuple_index += 1;
2016                    }
2017                }
2018            }
2019
2020            result
2021        }
2022
2023        OperandValue::ZeroSized => ::alloc::vec::Vec::new()vec![],
2024    }
2025}
2026
2027fn generic_simd_intrinsic<'ll, 'tcx>(
2028    bx: &mut Builder<'_, 'll, 'tcx>,
2029    name: Symbol,
2030    fn_args: GenericArgsRef<'tcx>,
2031    args: &[OperandRef<'tcx, &'ll Value>],
2032    ret_ty: Ty<'tcx>,
2033    llret_ty: &'ll Type,
2034    span: Span,
2035) -> Result<&'ll Value, ErrorGuaranteed> {
2036    macro_rules! return_error {
2037        ($diag: expr) => {{
2038            let err = bx.sess().dcx().emit_err($diag);
2039            return Err(err);
2040        }};
2041    }
2042
2043    macro_rules! require {
2044        ($cond: expr, $diag: expr) => {
2045            if !$cond {
2046                return_error!($diag);
2047            }
2048        };
2049    }
2050
2051    macro_rules! require_simd {
2052        ($ty: expr, $variant:ident) => {{
2053            require!($ty.is_simd(), InvalidMonomorphization::$variant { span, name, ty: $ty });
2054            $ty.simd_size_and_type(bx.tcx())
2055        }};
2056    }
2057
2058    macro_rules! require_simd_or_scalable {
2059        ($ty: expr, $variant:ident) => {{
2060            require!(
2061                $ty.is_simd() || $ty.is_scalable_vector(),
2062                InvalidMonomorphization::$variant { span, name, ty: $ty }
2063            );
2064            if $ty.is_simd() {
2065                let (len, ty) = $ty.simd_size_and_type(bx.tcx());
2066                (len, ty, None)
2067            } else {
2068                let (count, ty, num_vecs) =
2069                    $ty.scalable_vector_parts(bx.tcx()).expect("`is_scalable_vector` was wrong");
2070                (count as u64, ty, Some(num_vecs))
2071            }
2072        }};
2073    }
2074
2075    /// Returns the bitwidth of the `$ty` argument if it is an `Int` or `Uint` type.
2076    macro_rules! require_int_or_uint_ty {
2077        ($ty: expr, $diag: expr) => {
2078            match $ty {
2079                ty::Int(i) => {
2080                    i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size().bits())
2081                }
2082                ty::Uint(i) => {
2083                    i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size().bits())
2084                }
2085                _ => {
2086                    return_error!($diag);
2087                }
2088            }
2089        };
2090    }
2091
2092    let llvm_version = crate::llvm_util::get_version();
2093
2094    /// Converts a vector mask, where each element has a bit width equal to the data elements it is used with,
2095    /// down to an i1 based mask that can be used by llvm intrinsics.
2096    ///
2097    /// The rust simd semantics are that each element should either consist of all ones or all zeroes,
2098    /// but this information is not available to llvm. Truncating the vector effectively uses the lowest bit,
2099    /// but codegen for several targets is better if we consider the highest bit by shifting.
2100    ///
2101    /// For x86 SSE/AVX targets this is beneficial since most instructions with mask parameters only consider the highest bit.
2102    /// So even though on llvm level we have an additional shift, in the final assembly there is no shift or truncate and
2103    /// instead the mask can be used as is.
2104    ///
2105    /// For aarch64 and other targets there is a benefit because a mask from the sign bit can be more
2106    /// efficiently converted to an all ones / all zeroes mask by comparing whether each element is negative.
2107    fn vector_mask_to_bitmask<'a, 'll, 'tcx>(
2108        bx: &mut Builder<'a, 'll, 'tcx>,
2109        i_xn: &'ll Value,
2110        in_elem_bitwidth: u64,
2111        in_len: u64,
2112    ) -> &'ll Value {
2113        // Shift the MSB to the right by "in_elem_bitwidth - 1" into the first bit position.
2114        let shift_idx = bx.cx.const_int(bx.type_ix(in_elem_bitwidth), (in_elem_bitwidth - 1) as _);
2115        let shift_indices = ::alloc::vec::from_elem(shift_idx, in_len as _)vec![shift_idx; in_len as _];
2116        let i_xn_msb = bx.lshr(i_xn, bx.const_vector(shift_indices.as_slice()));
2117        // Truncate vector to an <i1 x N>
2118        bx.trunc(i_xn_msb, bx.type_vector(bx.type_i1(), in_len))
2119    }
2120
2121    // Sanity-check: all vector arguments must be immediates.
2122    if truecfg!(debug_assertions) {
2123        for arg in args {
2124            if arg.layout.ty.is_simd() {
2125                {
    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(_));
2126            }
2127        }
2128    }
2129
2130    if name == sym::simd_select_bitmask {
2131        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);
2132
2133        let expected_int_bits = len.max(8).next_power_of_two();
2134        let expected_bytes = len.div_ceil(8);
2135
2136        let mask_ty = args[0].layout.ty;
2137        let mask = match mask_ty.kind() {
2138            ty::Int(i) if i.bit_width() == Some(expected_int_bits) => args[0].immediate(),
2139            ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => args[0].immediate(),
2140            ty::Array(elem, len)
2141                if #[allow(non_exhaustive_omitted_patterns)] match elem.kind() {
    ty::Uint(ty::UintTy::U8) => true,
    _ => false,
}matches!(elem.kind(), ty::Uint(ty::UintTy::U8))
2142                    && len
2143                        .try_to_target_usize(bx.tcx)
2144                        .expect("expected monomorphic const in codegen")
2145                        == expected_bytes =>
2146            {
2147                let place = PlaceRef::alloca(bx, args[0].layout);
2148                args[0].val.store(bx, place);
2149                let int_ty = bx.type_ix(expected_bytes * 8);
2150                bx.load(int_ty, place.val.llval, Align::ONE)
2151            }
2152            _ => {
    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 {
2153                span,
2154                name,
2155                mask_ty,
2156                expected_int_bits,
2157                expected_bytes
2158            }),
2159        };
2160
2161        let i1 = bx.type_i1();
2162        let im = bx.type_ix(len);
2163        let i1xn = bx.type_vector(i1, len);
2164        let m_im = bx.trunc(mask, im);
2165        let m_i1s = bx.bitcast(m_im, i1xn);
2166        return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
2167    }
2168
2169    if name == sym::simd_splat {
2170        let (out_len, out_ty) = {
    if !ret_ty.is_simd() {
        {
            let err =
                bx.sess().dcx().emit_err(InvalidMonomorphization::SimdReturn {
                        span,
                        name,
                        ty: ret_ty,
                    });
            return Err(err);
        };
    };
    ret_ty.simd_size_and_type(bx.tcx())
}require_simd!(ret_ty, SimdReturn);
2171
2172        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!(
2173            args[0].layout.ty == out_ty,
2174            InvalidMonomorphization::ExpectedVectorElementType {
2175                span,
2176                name,
2177                expected_element: out_ty,
2178                vector_type: ret_ty,
2179            }
2180        );
2181
2182        // `insertelement <N x elem> poison, elem %x, i32 0`
2183        let poison_vec = bx.const_poison(llret_ty);
2184        let idx0 = bx.const_i32(0);
2185        let v0 = bx.insert_element(poison_vec, args[0].immediate(), idx0);
2186
2187        // `shufflevector <N x elem> v0, <N x elem> poison, <N x i32> zeroinitializer`
2188        // The masks is all zeros, so this splats lane 0 (which has our element in it).
2189        let mask_ty = bx.type_vector(bx.type_i32(), out_len);
2190        let splat = bx.shuffle_vector(v0, poison_vec, bx.const_null(mask_ty));
2191
2192        return Ok(splat);
2193    }
2194
2195    let supports_scalable = match name {
2196        sym::simd_cast | sym::simd_select => true,
2197        _ => false,
2198    };
2199
2200    // Every intrinsic below takes a SIMD vector as its first argument. Some intrinsics also accept
2201    // scalable vectors. `require_simd_or_scalable` is used regardless as it'll do the right thing
2202    // for non-scalable vectors, and an additional check to prohibit scalable vectors for those
2203    // intrinsics that do not support them is added.
2204    if !supports_scalable {
2205        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);
2206    }
2207    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);
2208    let in_ty = args[0].layout.ty;
2209
2210    let comparison = match name {
2211        sym::simd_eq => Some(BinOp::Eq),
2212        sym::simd_ne => Some(BinOp::Ne),
2213        sym::simd_lt => Some(BinOp::Lt),
2214        sym::simd_le => Some(BinOp::Le),
2215        sym::simd_gt => Some(BinOp::Gt),
2216        sym::simd_ge => Some(BinOp::Ge),
2217        _ => None,
2218    };
2219
2220    if let Some(cmp_op) = comparison {
2221        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);
2222
2223        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!(
2224            in_len == out_len,
2225            InvalidMonomorphization::ReturnLengthInputType {
2226                span,
2227                name,
2228                in_len,
2229                in_ty,
2230                ret_ty,
2231                out_len
2232            }
2233        );
2234        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!(
2235            bx.type_kind(bx.element_type(llret_ty)) == TypeKind::Integer,
2236            InvalidMonomorphization::ReturnIntegerType { span, name, ret_ty, out_ty }
2237        );
2238
2239        return Ok(compare_simd_types(
2240            bx,
2241            args[0].immediate(),
2242            args[1].immediate(),
2243            in_elem,
2244            llret_ty,
2245            cmp_op,
2246        ));
2247    }
2248
2249    if name == sym::simd_shuffle_const_generic {
2250        let idx = fn_args[2].expect_const().to_branch();
2251        let n = idx.len() as u64;
2252
2253        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);
2254        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!(
2255            out_len == n,
2256            InvalidMonomorphization::ReturnLength { span, name, in_len: n, ret_ty, out_len }
2257        );
2258        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!(
2259            in_elem == out_ty,
2260            InvalidMonomorphization::ReturnElement { span, name, in_elem, in_ty, ret_ty, out_ty }
2261        );
2262
2263        let total_len = in_len * 2;
2264
2265        let indices: Option<Vec<_>> = idx
2266            .iter()
2267            .enumerate()
2268            .map(|(arg_idx, val)| {
2269                let idx = val.to_leaf().to_i32();
2270                if idx >= i32::try_from(total_len).unwrap() {
2271                    bx.sess().dcx().emit_err(InvalidMonomorphization::SimdIndexOutOfBounds {
2272                        span,
2273                        name,
2274                        arg_idx: arg_idx as u64,
2275                        total_len: total_len.into(),
2276                    });
2277                    None
2278                } else {
2279                    Some(bx.const_i32(idx))
2280                }
2281            })
2282            .collect();
2283        let Some(indices) = indices else {
2284            return Ok(bx.const_null(llret_ty));
2285        };
2286
2287        return Ok(bx.shuffle_vector(
2288            args[0].immediate(),
2289            args[1].immediate(),
2290            bx.const_vector(&indices),
2291        ));
2292    }
2293
2294    if name == sym::simd_shuffle {
2295        // Make sure this is actually a SIMD vector.
2296        let idx_ty = args[2].layout.ty;
2297        let n: u64 = if idx_ty.is_simd()
2298            && #[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))
2299        {
2300            idx_ty.simd_size_and_type(bx.cx.tcx).0
2301        } else {
2302            {
    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 })
2303        };
2304
2305        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);
2306        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!(
2307            out_len == n,
2308            InvalidMonomorphization::ReturnLength { span, name, in_len: n, ret_ty, out_len }
2309        );
2310        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!(
2311            in_elem == out_ty,
2312            InvalidMonomorphization::ReturnElement { span, name, in_elem, in_ty, ret_ty, out_ty }
2313        );
2314
2315        let total_len = u128::from(in_len) * 2;
2316
2317        // Check that the indices are in-bounds.
2318        let indices = args[2].immediate();
2319        for i in 0..n {
2320            let val = bx.const_get_elt(indices, i as u64);
2321            let idx = bx
2322                .const_to_opt_u128(val, true)
2323                .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"));
2324            if idx >= total_len {
2325                {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::SimdIndexOutOfBounds {
                span,
                name,
                arg_idx: i,
                total_len,
            });
    return Err(err);
};return_error!(InvalidMonomorphization::SimdIndexOutOfBounds {
2326                    span,
2327                    name,
2328                    arg_idx: i,
2329                    total_len,
2330                });
2331            }
2332        }
2333
2334        return Ok(bx.shuffle_vector(args[0].immediate(), args[1].immediate(), indices));
2335    }
2336
2337    if name == sym::simd_insert || name == sym::simd_insert_dyn {
2338        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!(
2339            in_elem == args[2].layout.ty,
2340            InvalidMonomorphization::InsertedType {
2341                span,
2342                name,
2343                in_elem,
2344                in_ty,
2345                out_ty: args[2].layout.ty
2346            }
2347        );
2348
2349        let index_imm = if name == sym::simd_insert {
2350            let idx = bx
2351                .const_to_opt_u128(args[1].immediate(), false)
2352                .expect("typeck should have ensure that this is a const");
2353            if idx >= in_len.into() {
2354                {
    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 {
2355                    span,
2356                    name,
2357                    arg_idx: 1,
2358                    total_len: in_len.into(),
2359                });
2360            }
2361            bx.const_i32(idx as i32)
2362        } else {
2363            args[1].immediate()
2364        };
2365
2366        return Ok(bx.insert_element(args[0].immediate(), args[2].immediate(), index_imm));
2367    }
2368    if name == sym::simd_extract || name == sym::simd_extract_dyn {
2369        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!(
2370            ret_ty == in_elem,
2371            InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty }
2372        );
2373        let index_imm = if name == sym::simd_extract {
2374            let idx = bx
2375                .const_to_opt_u128(args[1].immediate(), false)
2376                .expect("typeck should have ensure that this is a const");
2377            if idx >= in_len.into() {
2378                {
    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 {
2379                    span,
2380                    name,
2381                    arg_idx: 1,
2382                    total_len: in_len.into(),
2383                });
2384            }
2385            bx.const_i32(idx as i32)
2386        } else {
2387            args[1].immediate()
2388        };
2389
2390        return Ok(bx.extract_element(args[0].immediate(), index_imm));
2391    }
2392
2393    if name == sym::simd_select {
2394        let m_elem_ty = in_elem;
2395        let m_len = in_len;
2396        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);
2397        if !(m_len == v_len) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::MismatchedLengths {
                    span,
                    name,
                    m_len,
                    v_len,
                });
        return Err(err);
    };
};require!(
2398            m_len == v_len,
2399            InvalidMonomorphization::MismatchedLengths { span, name, m_len, v_len }
2400        );
2401
2402        let m_i1s = if args[1].layout.ty.is_scalable_vector() {
2403            match m_elem_ty.kind() {
2404                ty::Bool => {}
2405                _ => {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::MaskWrongElementType {
                span,
                name,
                ty: m_elem_ty,
            });
    return Err(err);
}return_error!(InvalidMonomorphization::MaskWrongElementType {
2406                    span,
2407                    name,
2408                    ty: m_elem_ty
2409                }),
2410            };
2411            let i1 = bx.type_i1();
2412            let i1xn = bx.type_scalable_vector(i1, m_len as u64);
2413            bx.trunc(args[0].immediate(), i1xn)
2414        } else {
2415            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!(
2416                m_elem_ty.kind(),
2417                InvalidMonomorphization::MaskWrongElementType { span, name, ty: m_elem_ty }
2418            );
2419            vector_mask_to_bitmask(bx, args[0].immediate(), in_elem_bitwidth, m_len)
2420        };
2421
2422        return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
2423    }
2424
2425    if name == sym::simd_bitmask {
2426        // The `fn simd_bitmask(vector) -> unsigned integer` intrinsic takes a vector mask and
2427        // returns one bit for each lane (which must all be `0` or `!0`) in the form of either:
2428        // * an unsigned integer
2429        // * an array of `u8`
2430        // If the vector has less than 8 lanes, a u8 is returned with zeroed trailing bits.
2431        //
2432        // The bit order of the result depends on the byte endianness, LSB-first for little
2433        // endian and MSB-first for big endian.
2434        let expected_int_bits = in_len.max(8).next_power_of_two();
2435        let expected_bytes = in_len.div_ceil(8);
2436
2437        // Integer vector <i{in_bitwidth} x in_len>:
2438        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!(
2439            in_elem.kind(),
2440            InvalidMonomorphization::MaskWrongElementType { span, name, ty: in_elem }
2441        );
2442
2443        let i1xn = vector_mask_to_bitmask(bx, args[0].immediate(), in_elem_bitwidth, in_len);
2444        // Bitcast <i1 x N> to iN:
2445        let i_ = bx.bitcast(i1xn, bx.type_ix(in_len));
2446
2447        match ret_ty.kind() {
2448            ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => {
2449                // Zero-extend iN to the bitmask type:
2450                return Ok(bx.zext(i_, bx.type_ix(expected_int_bits)));
2451            }
2452            ty::Array(elem, len)
2453                if #[allow(non_exhaustive_omitted_patterns)] match elem.kind() {
    ty::Uint(ty::UintTy::U8) => true,
    _ => false,
}matches!(elem.kind(), ty::Uint(ty::UintTy::U8))
2454                    && len
2455                        .try_to_target_usize(bx.tcx)
2456                        .expect("expected monomorphic const in codegen")
2457                        == expected_bytes =>
2458            {
2459                // Zero-extend iN to the array length:
2460                let ze = bx.zext(i_, bx.type_ix(expected_bytes * 8));
2461
2462                // Convert the integer to a byte array
2463                let ptr = bx.alloca(Size::from_bytes(expected_bytes), Align::ONE);
2464                bx.store(ze, ptr, Align::ONE);
2465                let array_ty = bx.type_array(bx.type_i8(), expected_bytes);
2466                return Ok(bx.load(array_ty, ptr, Align::ONE));
2467            }
2468            _ => {
    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 {
2469                span,
2470                name,
2471                ret_ty,
2472                expected_int_bits,
2473                expected_bytes
2474            }),
2475        }
2476    }
2477
2478    fn simd_simple_float_intrinsic<'ll, 'tcx>(
2479        name: Symbol,
2480        in_elem: Ty<'_>,
2481        in_ty: Ty<'_>,
2482        in_len: u64,
2483        bx: &mut Builder<'_, 'll, 'tcx>,
2484        span: Span,
2485        args: &[OperandRef<'tcx, &'ll Value>],
2486    ) -> Result<&'ll Value, ErrorGuaranteed> {
2487        macro_rules! return_error {
2488            ($diag: expr) => {{
2489                let err = bx.sess().dcx().emit_err($diag);
2490                return Err(err);
2491            }};
2492        }
2493
2494        let ty::Float(f) = in_elem.kind() else {
2495            {
    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 });
2496        };
2497        let elem_ty = bx.cx.type_float_from_ty(*f);
2498
2499        let vec_ty = bx.type_vector(elem_ty, in_len);
2500
2501        let intr_name = match name {
2502            sym::simd_ceil => "llvm.ceil",
2503            sym::simd_fabs => "llvm.fabs",
2504            sym::simd_fcos => "llvm.cos",
2505            sym::simd_fexp2 => "llvm.exp2",
2506            sym::simd_fexp => "llvm.exp",
2507            sym::simd_flog10 => "llvm.log10",
2508            sym::simd_flog2 => "llvm.log2",
2509            sym::simd_flog => "llvm.log",
2510            sym::simd_floor => "llvm.floor",
2511            sym::simd_fma => "llvm.fma",
2512            sym::simd_relaxed_fma => "llvm.fmuladd",
2513            sym::simd_fsin => "llvm.sin",
2514            sym::simd_fsqrt => "llvm.sqrt",
2515            sym::simd_round => "llvm.round",
2516            sym::simd_round_ties_even => "llvm.rint",
2517            sym::simd_trunc => "llvm.trunc",
2518            _ => {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::UnrecognizedIntrinsic {
                span,
                name,
            });
    return Err(err);
}return_error!(InvalidMonomorphization::UnrecognizedIntrinsic { span, name }),
2519        };
2520        Ok(bx.call_intrinsic(
2521            intr_name,
2522            &[vec_ty],
2523            &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
2524        ))
2525    }
2526
2527    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!(
2528        name,
2529        sym::simd_ceil
2530            | sym::simd_fabs
2531            | sym::simd_fcos
2532            | sym::simd_fexp2
2533            | sym::simd_fexp
2534            | sym::simd_flog10
2535            | sym::simd_flog2
2536            | sym::simd_flog
2537            | sym::simd_floor
2538            | sym::simd_fma
2539            | sym::simd_fsin
2540            | sym::simd_fsqrt
2541            | sym::simd_relaxed_fma
2542            | sym::simd_round
2543            | sym::simd_round_ties_even
2544            | sym::simd_trunc
2545    ) {
2546        return simd_simple_float_intrinsic(name, in_elem, in_ty, in_len, bx, span, args);
2547    }
2548
2549    fn llvm_vector_ty<'ll>(cx: &CodegenCx<'ll, '_>, elem_ty: Ty<'_>, vec_len: u64) -> &'ll Type {
2550        let elem_ty = match *elem_ty.kind() {
2551            ty::Int(v) => cx.type_int_from_ty(v),
2552            ty::Uint(v) => cx.type_uint_from_ty(v),
2553            ty::Float(v) => cx.type_float_from_ty(v),
2554            ty::RawPtr(_, _) => cx.type_ptr(),
2555            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
2556        };
2557        cx.type_vector(elem_ty, vec_len)
2558    }
2559
2560    if name == sym::simd_gather {
2561        // simd_gather(values: <N x T>, pointers: <N x *_ T>,
2562        //             mask: <N x i{M}>) -> <N x T>
2563        // * N: number of elements in the input vectors
2564        // * T: type of the element to load
2565        // * M: any integer width is supported, will be truncated to i1
2566
2567        // All types must be simd vector types
2568
2569        // The second argument must be a simd vector with an element type that's a pointer
2570        // to the element type of the first argument
2571        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);
2572        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);
2573        // The element type of the third argument must be a signed integer type of any width:
2574        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);
2575        {
    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);
2576
2577        // Of the same length:
2578        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!(
2579            in_len == out_len,
2580            InvalidMonomorphization::SecondArgumentLength {
2581                span,
2582                name,
2583                in_len,
2584                in_ty,
2585                arg_ty: args[1].layout.ty,
2586                out_len
2587            }
2588        );
2589        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!(
2590            in_len == out_len2,
2591            InvalidMonomorphization::ThirdArgumentLength {
2592                span,
2593                name,
2594                in_len,
2595                in_ty,
2596                arg_ty: args[2].layout.ty,
2597                out_len: out_len2
2598            }
2599        );
2600
2601        // The return type must match the first argument type
2602        if !(ret_ty == in_ty) {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::ExpectedReturnType {
                    span,
                    name,
                    in_ty,
                    ret_ty,
                });
        return Err(err);
    };
};require!(
2603            ret_ty == in_ty,
2604            InvalidMonomorphization::ExpectedReturnType { span, name, in_ty, ret_ty }
2605        );
2606
2607        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!(
2608            matches!(
2609                *element_ty1.kind(),
2610                ty::RawPtr(p_ty, _) if p_ty == in_elem && p_ty.kind() == element_ty0.kind()
2611            ),
2612            InvalidMonomorphization::ExpectedElementType {
2613                span,
2614                name,
2615                expected_element: element_ty1,
2616                second_arg: args[1].layout.ty,
2617                in_elem,
2618                in_ty,
2619                mutability: ExpectedPointerMutability::Not,
2620            }
2621        );
2622
2623        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!(
2624            element_ty2.kind(),
2625            InvalidMonomorphization::MaskWrongElementType { span, name, ty: element_ty2 }
2626        );
2627
2628        // Alignment of T, must be a constant integer value:
2629        let alignment = bx.align_of(in_elem).bytes();
2630
2631        // Truncate the mask vector to a vector of i1s:
2632        let mask = vector_mask_to_bitmask(bx, args[2].immediate(), mask_elem_bitwidth, in_len);
2633
2634        // Type of the vector of pointers:
2635        let llvm_pointer_vec_ty = llvm_vector_ty(bx, element_ty1, in_len);
2636
2637        // Type of the vector of elements:
2638        let llvm_elem_vec_ty = llvm_vector_ty(bx, element_ty0, in_len);
2639
2640        let args: &[&'ll Value] = if llvm_version < (22, 0, 0) {
2641            let alignment = bx.const_i32(alignment as i32);
2642            &[args[1].immediate(), alignment, mask, args[0].immediate()]
2643        } else {
2644            &[args[1].immediate(), mask, args[0].immediate()]
2645        };
2646
2647        let call =
2648            bx.call_intrinsic("llvm.masked.gather", &[llvm_elem_vec_ty, llvm_pointer_vec_ty], args);
2649        if llvm_version >= (22, 0, 0) {
2650            crate::attributes::apply_to_callsite(
2651                call,
2652                crate::llvm::AttributePlace::Argument(0),
2653                &[crate::llvm::CreateAlignmentAttr(bx.llcx, alignment)],
2654            )
2655        }
2656        return Ok(call);
2657    }
2658
2659    fn llvm_alignment<'ll, 'tcx>(
2660        bx: &mut Builder<'_, 'll, 'tcx>,
2661        alignment: SimdAlign,
2662        vector_ty: Ty<'tcx>,
2663        element_ty: Ty<'tcx>,
2664    ) -> u64 {
2665        match alignment {
2666            SimdAlign::Unaligned => 1,
2667            SimdAlign::Element => bx.align_of(element_ty).bytes(),
2668            SimdAlign::Vector => bx.align_of(vector_ty).bytes(),
2669        }
2670    }
2671
2672    if name == sym::simd_masked_load {
2673        // simd_masked_load<_, _, _, const ALIGN: SimdAlign>(mask: <N x i{M}>, pointer: *_ T, values: <N x T>) -> <N x T>
2674        // * N: number of elements in the input vectors
2675        // * T: type of the element to load
2676        // * M: any integer width is supported, will be truncated to i1
2677        // Loads contiguous elements from memory behind `pointer`, but only for
2678        // those lanes whose `mask` bit is enabled.
2679        // The memory addresses corresponding to the “off” lanes are not accessed.
2680
2681        let alignment = fn_args[3].expect_const().to_branch()[0].to_leaf().to_simd_alignment();
2682
2683        // The element type of the "mask" argument must be a signed integer type of any width
2684        let mask_ty = in_ty;
2685        let (mask_len, mask_elem) = (in_len, in_elem);
2686
2687        // The second argument must be a pointer matching the element type
2688        let pointer_ty = args[1].layout.ty;
2689
2690        // The last argument is a passthrough vector providing values for disabled lanes
2691        let values_ty = args[2].layout.ty;
2692        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);
2693
2694        {
    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);
2695
2696        // Of the same length:
2697        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!(
2698            values_len == mask_len,
2699            InvalidMonomorphization::ThirdArgumentLength {
2700                span,
2701                name,
2702                in_len: mask_len,
2703                in_ty: mask_ty,
2704                arg_ty: values_ty,
2705                out_len: values_len
2706            }
2707        );
2708
2709        // The return type must match the last argument type
2710        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!(
2711            ret_ty == values_ty,
2712            InvalidMonomorphization::ExpectedReturnType { span, name, in_ty: values_ty, ret_ty }
2713        );
2714
2715        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!(
2716            matches!(
2717                *pointer_ty.kind(),
2718                ty::RawPtr(p_ty, _) if p_ty == values_elem && p_ty.kind() == values_elem.kind()
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::Not,
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
2749            &[args[1].immediate(), alignment, mask, args[2].immediate()]
2750        } else {
2751            &[args[1].immediate(), mask, args[2].immediate()]
2752        };
2753
2754        let call = bx.call_intrinsic("llvm.masked.load", &[llvm_elem_vec_ty, llvm_pointer], args);
2755        if llvm_version >= (22, 0, 0) {
2756            crate::attributes::apply_to_callsite(
2757                call,
2758                crate::llvm::AttributePlace::Argument(0),
2759                &[crate::llvm::CreateAlignmentAttr(bx.llcx, alignment)],
2760            )
2761        }
2762        return Ok(call);
2763    }
2764
2765    if name == sym::simd_masked_store {
2766        // simd_masked_store<_, _, _, const ALIGN: SimdAlign>(mask: <N x i{M}>, pointer: *mut T, values: <N x T>) -> ()
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        // Stores contiguous elements to memory behind `pointer`, but only for
2771        // those lanes whose `mask` bit is enabled.
2772        // The memory addresses corresponding to the “off” lanes are not accessed.
2773
2774        let alignment = fn_args[3].expect_const().to_branch()[0].to_leaf().to_simd_alignment();
2775
2776        // The element type of the "mask" argument must be a signed integer type of any width
2777        let mask_ty = in_ty;
2778        let (mask_len, mask_elem) = (in_len, in_elem);
2779
2780        // The second argument must be a pointer matching the element type
2781        let pointer_ty = args[1].layout.ty;
2782
2783        // The last argument specifies the values to store to memory
2784        let values_ty = args[2].layout.ty;
2785        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);
2786
2787        // Of the same length:
2788        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!(
2789            values_len == mask_len,
2790            InvalidMonomorphization::ThirdArgumentLength {
2791                span,
2792                name,
2793                in_len: mask_len,
2794                in_ty: mask_ty,
2795                arg_ty: values_ty,
2796                out_len: values_len
2797            }
2798        );
2799
2800        // The second argument must be a mutable pointer type matching the element type
2801        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!(
2802            matches!(
2803                *pointer_ty.kind(),
2804                ty::RawPtr(p_ty, p_mutbl)
2805                    if p_ty == values_elem && p_ty.kind() == values_elem.kind() && p_mutbl.is_mut()
2806            ),
2807            InvalidMonomorphization::ExpectedElementType {
2808                span,
2809                name,
2810                expected_element: values_elem,
2811                second_arg: pointer_ty,
2812                in_elem: values_elem,
2813                in_ty: values_ty,
2814                mutability: ExpectedPointerMutability::Mut,
2815            }
2816        );
2817
2818        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!(
2819            mask_elem.kind(),
2820            InvalidMonomorphization::MaskWrongElementType { span, name, ty: mask_elem }
2821        );
2822
2823        let mask = vector_mask_to_bitmask(bx, args[0].immediate(), m_elem_bitwidth, mask_len);
2824
2825        // Alignment of T, must be a constant integer value:
2826        let alignment = llvm_alignment(bx, alignment, values_ty, values_elem);
2827
2828        let llvm_pointer = bx.type_ptr();
2829
2830        // Type of the vector of elements:
2831        let llvm_elem_vec_ty = llvm_vector_ty(bx, values_elem, values_len);
2832
2833        let args: &[&'ll Value] = if llvm_version < (22, 0, 0) {
2834            let alignment = bx.const_i32(alignment as i32);
2835            &[args[2].immediate(), args[1].immediate(), alignment, mask]
2836        } else {
2837            &[args[2].immediate(), args[1].immediate(), mask]
2838        };
2839
2840        let call = bx.call_intrinsic("llvm.masked.store", &[llvm_elem_vec_ty, llvm_pointer], args);
2841        if llvm_version >= (22, 0, 0) {
2842            crate::attributes::apply_to_callsite(
2843                call,
2844                crate::llvm::AttributePlace::Argument(1),
2845                &[crate::llvm::CreateAlignmentAttr(bx.llcx, alignment)],
2846            )
2847        }
2848        return Ok(call);
2849    }
2850
2851    if name == sym::simd_scatter {
2852        // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
2853        //             mask: <N x i{M}>) -> ()
2854        // * N: number of elements in the input vectors
2855        // * T: type of the element to load
2856        // * M: any integer width is supported, will be truncated to i1
2857
2858        // All types must be simd vector types
2859        // The second argument must be a simd vector with an element type that's a pointer
2860        // to the element type of the first argument
2861        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);
2862        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);
2863        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);
2864
2865        // Of the same length:
2866        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!(
2867            in_len == element_len1,
2868            InvalidMonomorphization::SecondArgumentLength {
2869                span,
2870                name,
2871                in_len,
2872                in_ty,
2873                arg_ty: args[1].layout.ty,
2874                out_len: element_len1
2875            }
2876        );
2877        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!(
2878            in_len == element_len2,
2879            InvalidMonomorphization::ThirdArgumentLength {
2880                span,
2881                name,
2882                in_len,
2883                in_ty,
2884                arg_ty: args[2].layout.ty,
2885                out_len: element_len2
2886            }
2887        );
2888
2889        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!(
2890            matches!(
2891                *element_ty1.kind(),
2892                ty::RawPtr(p_ty, p_mutbl)
2893                    if p_ty == in_elem && p_mutbl.is_mut() && p_ty.kind() == element_ty0.kind()
2894            ),
2895            InvalidMonomorphization::ExpectedElementType {
2896                span,
2897                name,
2898                expected_element: element_ty1,
2899                second_arg: args[1].layout.ty,
2900                in_elem,
2901                in_ty,
2902                mutability: ExpectedPointerMutability::Mut,
2903            }
2904        );
2905
2906        // The element type of the third argument must be an integer type of any width:
2907        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!(
2908            element_ty2.kind(),
2909            InvalidMonomorphization::MaskWrongElementType { span, name, ty: element_ty2 }
2910        );
2911
2912        // Alignment of T, must be a constant integer value:
2913        let alignment = bx.align_of(in_elem).bytes();
2914
2915        // Truncate the mask vector to a vector of i1s:
2916        let mask = vector_mask_to_bitmask(bx, args[2].immediate(), mask_elem_bitwidth, in_len);
2917
2918        // Type of the vector of pointers:
2919        let llvm_pointer_vec_ty = llvm_vector_ty(bx, element_ty1, in_len);
2920
2921        // Type of the vector of elements:
2922        let llvm_elem_vec_ty = llvm_vector_ty(bx, element_ty0, in_len);
2923        let args: &[&'ll Value] = if llvm_version < (22, 0, 0) {
2924            let alignment = bx.const_i32(alignment as i32);
2925            &[args[0].immediate(), args[1].immediate(), alignment, mask]
2926        } else {
2927            &[args[0].immediate(), args[1].immediate(), mask]
2928        };
2929        let call = bx.call_intrinsic(
2930            "llvm.masked.scatter",
2931            &[llvm_elem_vec_ty, llvm_pointer_vec_ty],
2932            args,
2933        );
2934        if llvm_version >= (22, 0, 0) {
2935            crate::attributes::apply_to_callsite(
2936                call,
2937                crate::llvm::AttributePlace::Argument(1),
2938                &[crate::llvm::CreateAlignmentAttr(bx.llcx, alignment)],
2939            )
2940        }
2941        return Ok(call);
2942    }
2943
2944    macro_rules! arith_red {
2945        ($name:ident : $integer_reduce:ident, $float_reduce:ident, $ordered:expr, $op:ident,
2946         $identity:expr) => {
2947            if name == sym::$name {
2948                require!(
2949                    ret_ty == in_elem,
2950                    InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty }
2951                );
2952                return match in_elem.kind() {
2953                    ty::Int(_) | ty::Uint(_) => {
2954                        let r = bx.$integer_reduce(args[0].immediate());
2955                        if $ordered {
2956                            // if overflow occurs, the result is the
2957                            // mathematical result modulo 2^n:
2958                            Ok(bx.$op(args[1].immediate(), r))
2959                        } else {
2960                            Ok(bx.$integer_reduce(args[0].immediate()))
2961                        }
2962                    }
2963                    ty::Float(f) => {
2964                        let acc = if $ordered {
2965                            // ordered arithmetic reductions take an accumulator
2966                            args[1].immediate()
2967                        } else {
2968                            // unordered arithmetic reductions use the identity accumulator
2969                            match f.bit_width() {
2970                                32 => bx.const_real(bx.type_f32(), $identity),
2971                                64 => bx.const_real(bx.type_f64(), $identity),
2972                                v => return_error!(
2973                                    InvalidMonomorphization::UnsupportedSymbolOfSize {
2974                                        span,
2975                                        name,
2976                                        symbol: sym::$name,
2977                                        in_ty,
2978                                        in_elem,
2979                                        size: v,
2980                                        ret_ty
2981                                    }
2982                                ),
2983                            }
2984                        };
2985                        Ok(bx.$float_reduce(acc, args[0].immediate()))
2986                    }
2987                    _ => return_error!(InvalidMonomorphization::UnsupportedSymbol {
2988                        span,
2989                        name,
2990                        symbol: sym::$name,
2991                        in_ty,
2992                        in_elem,
2993                        ret_ty
2994                    }),
2995                };
2996            }
2997        };
2998    }
2999
3000    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);
3001    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);
3002    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!(
3003        simd_reduce_add_unordered: vector_reduce_add,
3004        vector_reduce_fadd_reassoc,
3005        false,
3006        add,
3007        -0.0
3008    );
3009    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!(
3010        simd_reduce_mul_unordered: vector_reduce_mul,
3011        vector_reduce_fmul_reassoc,
3012        false,
3013        mul,
3014        1.0
3015    );
3016
3017    macro_rules! minmax_red {
3018        ($name:ident: $int_red:ident) => {
3019            if name == sym::$name {
3020                require!(
3021                    ret_ty == in_elem,
3022                    InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty }
3023                );
3024                return match in_elem.kind() {
3025                    ty::Int(_i) => Ok(bx.$int_red(args[0].immediate(), true)),
3026                    ty::Uint(_u) => Ok(bx.$int_red(args[0].immediate(), false)),
3027                    _ => return_error!(InvalidMonomorphization::UnsupportedSymbol {
3028                        span,
3029                        name,
3030                        symbol: sym::$name,
3031                        in_ty,
3032                        in_elem,
3033                        ret_ty
3034                    }),
3035                };
3036            }
3037        };
3038    }
3039
3040    // Currently no support for float due to <https://github.com/llvm/llvm-project/issues/185827>.
3041    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);
3042    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);
3043
3044    macro_rules! bitwise_red {
3045        ($name:ident : $red:ident, $boolean:expr) => {
3046            if name == sym::$name {
3047                let input = if !$boolean {
3048                    require!(
3049                        ret_ty == in_elem,
3050                        InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty }
3051                    );
3052                    args[0].immediate()
3053                } else {
3054                    let bitwidth = match in_elem.kind() {
3055                        ty::Int(i) => {
3056                            i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size().bits())
3057                        }
3058                        ty::Uint(i) => {
3059                            i.bit_width().unwrap_or_else(|| bx.data_layout().pointer_size().bits())
3060                        }
3061                        _ => return_error!(InvalidMonomorphization::UnsupportedSymbol {
3062                            span,
3063                            name,
3064                            symbol: sym::$name,
3065                            in_ty,
3066                            in_elem,
3067                            ret_ty
3068                        }),
3069                    };
3070
3071                    vector_mask_to_bitmask(bx, args[0].immediate(), bitwidth, in_len as _)
3072                };
3073                return match in_elem.kind() {
3074                    ty::Int(_) | ty::Uint(_) => {
3075                        let r = bx.$red(input);
3076                        Ok(r)
3077                    }
3078                    _ => return_error!(InvalidMonomorphization::UnsupportedSymbol {
3079                        span,
3080                        name,
3081                        symbol: sym::$name,
3082                        in_ty,
3083                        in_elem,
3084                        ret_ty
3085                    }),
3086                };
3087            }
3088        };
3089    }
3090
3091    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);
3092    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);
3093    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);
3094    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);
3095    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);
3096
3097    if name == sym::simd_cast_ptr {
3098        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);
3099        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!(
3100            in_len == out_len,
3101            InvalidMonomorphization::ReturnLengthInputType {
3102                span,
3103                name,
3104                in_len,
3105                in_ty,
3106                ret_ty,
3107                out_len
3108            }
3109        );
3110
3111        match in_elem.kind() {
3112            ty::RawPtr(p_ty, _) => {
3113                let metadata = p_ty.ptr_metadata_ty(bx.tcx, |ty| {
3114                    bx.tcx.normalize_erasing_regions(bx.typing_env(), ty)
3115                });
3116                if !metadata.is_unit() {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::CastWidePointer {
                    span,
                    name,
                    ty: in_elem,
                });
        return Err(err);
    };
};require!(
3117                    metadata.is_unit(),
3118                    InvalidMonomorphization::CastWidePointer { span, name, ty: in_elem }
3119                );
3120            }
3121            _ => {
3122                {
    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 })
3123            }
3124        }
3125        match out_elem.kind() {
3126            ty::RawPtr(p_ty, _) => {
3127                let metadata = p_ty.ptr_metadata_ty(bx.tcx, |ty| {
3128                    bx.tcx.normalize_erasing_regions(bx.typing_env(), ty)
3129                });
3130                if !metadata.is_unit() {
    {
        let err =
            bx.sess().dcx().emit_err(InvalidMonomorphization::CastWidePointer {
                    span,
                    name,
                    ty: out_elem,
                });
        return Err(err);
    };
};require!(
3131                    metadata.is_unit(),
3132                    InvalidMonomorphization::CastWidePointer { span, name, ty: out_elem }
3133                );
3134            }
3135            _ => {
3136                {
    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 })
3137            }
3138        }
3139
3140        return Ok(args[0].immediate());
3141    }
3142
3143    if name == sym::simd_expose_provenance {
3144        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);
3145        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!(
3146            in_len == out_len,
3147            InvalidMonomorphization::ReturnLengthInputType {
3148                span,
3149                name,
3150                in_len,
3151                in_ty,
3152                ret_ty,
3153                out_len
3154            }
3155        );
3156
3157        match in_elem.kind() {
3158            ty::RawPtr(_, _) => {}
3159            _ => {
3160                {
    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 })
3161            }
3162        }
3163        match out_elem.kind() {
3164            ty::Uint(ty::UintTy::Usize) => {}
3165            _ => {
    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 }),
3166        }
3167
3168        return Ok(bx.ptrtoint(args[0].immediate(), llret_ty));
3169    }
3170
3171    if name == sym::simd_with_exposed_provenance {
3172        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);
3173        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!(
3174            in_len == out_len,
3175            InvalidMonomorphization::ReturnLengthInputType {
3176                span,
3177                name,
3178                in_len,
3179                in_ty,
3180                ret_ty,
3181                out_len
3182            }
3183        );
3184
3185        match in_elem.kind() {
3186            ty::Uint(ty::UintTy::Usize) => {}
3187            _ => {
    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 }),
3188        }
3189        match out_elem.kind() {
3190            ty::RawPtr(_, _) => {}
3191            _ => {
3192                {
    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 })
3193            }
3194        }
3195
3196        return Ok(bx.inttoptr(args[0].immediate(), llret_ty));
3197    }
3198
3199    if name == sym::simd_cast || name == sym::simd_as {
3200        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);
3201        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!(
3202            in_len == out_len,
3203            InvalidMonomorphization::ReturnLengthInputType {
3204                span,
3205                name,
3206                in_len,
3207                in_ty,
3208                ret_ty,
3209                out_len
3210            }
3211        );
3212        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!(
3213            in_num_vecs == out_num_vecs,
3214            InvalidMonomorphization::ReturnNumVecsInputType {
3215                span,
3216                name,
3217                in_num_vecs: in_num_vecs.unwrap_or(NumScalableVectors(1)),
3218                in_ty,
3219                ret_ty,
3220                out_num_vecs: out_num_vecs.unwrap_or(NumScalableVectors(1))
3221            }
3222        );
3223
3224        // Casting cares about nominal type, not just structural type
3225        if in_elem == out_elem {
3226            return Ok(args[0].immediate());
3227        }
3228
3229        #[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)]
3230        enum Sign {
3231            Unsigned,
3232            Signed,
3233        }
3234        use Sign::*;
3235
3236        enum Style {
3237            Float,
3238            Int(Sign),
3239            Unsupported,
3240        }
3241
3242        let (in_style, in_width) = match in_elem.kind() {
3243            // vectors of pointer-sized integers should've been
3244            // disallowed before here, so this unwrap is safe.
3245            ty::Int(i) => (
3246                Style::Int(Signed),
3247                i.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
3248            ),
3249            ty::Uint(u) => (
3250                Style::Int(Unsigned),
3251                u.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
3252            ),
3253            ty::Float(f) => (Style::Float, f.bit_width()),
3254            _ => (Style::Unsupported, 0),
3255        };
3256        let (out_style, out_width) = match out_elem.kind() {
3257            ty::Int(i) => (
3258                Style::Int(Signed),
3259                i.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
3260            ),
3261            ty::Uint(u) => (
3262                Style::Int(Unsigned),
3263                u.normalize(bx.tcx().sess.target.pointer_width).bit_width().unwrap(),
3264            ),
3265            ty::Float(f) => (Style::Float, f.bit_width()),
3266            _ => (Style::Unsupported, 0),
3267        };
3268
3269        match (in_style, out_style) {
3270            (Style::Int(sign), Style::Int(_)) => {
3271                return Ok(match in_width.cmp(&out_width) {
3272                    Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
3273                    Ordering::Equal => args[0].immediate(),
3274                    Ordering::Less => match sign {
3275                        Sign::Signed => bx.sext(args[0].immediate(), llret_ty),
3276                        Sign::Unsigned => bx.zext(args[0].immediate(), llret_ty),
3277                    },
3278                });
3279            }
3280            (Style::Int(Sign::Signed), Style::Float) => {
3281                return Ok(bx.sitofp(args[0].immediate(), llret_ty));
3282            }
3283            (Style::Int(Sign::Unsigned), Style::Float) => {
3284                return Ok(bx.uitofp(args[0].immediate(), llret_ty));
3285            }
3286            (Style::Float, Style::Int(sign)) => {
3287                return Ok(match (sign, name == sym::simd_as) {
3288                    (Sign::Unsigned, false) => bx.fptoui(args[0].immediate(), llret_ty),
3289                    (Sign::Signed, false) => bx.fptosi(args[0].immediate(), llret_ty),
3290                    (_, true) => bx.cast_float_to_int(
3291                        #[allow(non_exhaustive_omitted_patterns)] match sign {
    Sign::Signed => true,
    _ => false,
}matches!(sign, Sign::Signed),
3292                        args[0].immediate(),
3293                        llret_ty,
3294                    ),
3295                });
3296            }
3297            (Style::Float, Style::Float) => {
3298                return Ok(match in_width.cmp(&out_width) {
3299                    Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
3300                    Ordering::Equal => args[0].immediate(),
3301                    Ordering::Less => bx.fpext(args[0].immediate(), llret_ty),
3302                });
3303            }
3304            _ => {
    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 {
3305                span,
3306                name,
3307                in_ty,
3308                in_elem,
3309                ret_ty,
3310                out_elem
3311            }),
3312        }
3313    }
3314    macro_rules! arith_binary {
3315        ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
3316            $(if name == sym::$name {
3317                match in_elem.kind() {
3318                    $($(ty::$p(_))|* => {
3319                        return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
3320                    })*
3321                    _ => {},
3322                }
3323                return_error!(
3324                    InvalidMonomorphization::UnsupportedOperation { span, name, in_ty, in_elem }
3325                );
3326            })*
3327        }
3328    }
3329    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! {
3330        simd_add: Uint, Int => add, Float => fadd;
3331        simd_sub: Uint, Int => sub, Float => fsub;
3332        simd_mul: Uint, Int => mul, Float => fmul;
3333        simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
3334        simd_rem: Uint => urem, Int => srem, Float => frem;
3335        simd_shl: Uint, Int => shl;
3336        simd_shr: Uint => lshr, Int => ashr;
3337        simd_and: Uint, Int => and;
3338        simd_or: Uint, Int => or;
3339        simd_xor: Uint, Int => xor;
3340        simd_maximum_number_nsz: Float => maximum_number_nsz;
3341        simd_minimum_number_nsz: Float => minimum_number_nsz;
3342
3343    }
3344    macro_rules! arith_unary {
3345        ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
3346            $(if name == sym::$name {
3347                match in_elem.kind() {
3348                    $($(ty::$p(_))|* => {
3349                        return Ok(bx.$call(args[0].immediate()))
3350                    })*
3351                    _ => {},
3352                }
3353                return_error!(
3354                    InvalidMonomorphization::UnsupportedOperation { span, name, in_ty, in_elem }
3355                );
3356            })*
3357        }
3358    }
3359    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! {
3360        simd_neg: Int => neg, Float => fneg;
3361    }
3362
3363    // Unary integer intrinsics
3364    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!(
3365        name,
3366        sym::simd_bswap
3367            | sym::simd_bitreverse
3368            | sym::simd_ctlz
3369            | sym::simd_ctpop
3370            | sym::simd_cttz
3371            | sym::simd_carryless_mul
3372            | sym::simd_funnel_shl
3373            | sym::simd_funnel_shr
3374    ) {
3375        let vec_ty = bx.cx.type_vector(
3376            match *in_elem.kind() {
3377                ty::Int(i) => bx.cx.type_int_from_ty(i),
3378                ty::Uint(i) => bx.cx.type_uint_from_ty(i),
3379                _ => {
    let err =
        bx.sess().dcx().emit_err(InvalidMonomorphization::UnsupportedOperation {
                span,
                name,
                in_ty,
                in_elem,
            });
    return Err(err);
}return_error!(InvalidMonomorphization::UnsupportedOperation {
3380                    span,
3381                    name,
3382                    in_ty,
3383                    in_elem
3384                }),
3385            },
3386            in_len as u64,
3387        );
3388        let llvm_intrinsic = match name {
3389            sym::simd_bswap => "llvm.bswap",
3390            sym::simd_bitreverse => "llvm.bitreverse",
3391            sym::simd_ctlz => "llvm.ctlz",
3392            sym::simd_ctpop => "llvm.ctpop",
3393            sym::simd_cttz => "llvm.cttz",
3394            sym::simd_funnel_shl => "llvm.fshl",
3395            sym::simd_funnel_shr => "llvm.fshr",
3396            sym::simd_carryless_mul => "llvm.clmul",
3397            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
3398        };
3399        let int_size = in_elem.int_size_and_signed(bx.tcx()).0.bits();
3400
3401        return match name {
3402            // byte swap is no-op for i8/u8
3403            sym::simd_bswap if int_size == 8 => Ok(args[0].immediate()),
3404            sym::simd_ctlz | sym::simd_cttz => {
3405                // for the (int, i1 immediate) pair, the second arg adds `(0, true) => poison`
3406                let dont_poison_on_zero = bx.const_int(bx.type_i1(), 0);
3407                Ok(bx.call_intrinsic(
3408                    llvm_intrinsic,
3409                    &[vec_ty],
3410                    &[args[0].immediate(), dont_poison_on_zero],
3411                ))
3412            }
3413            sym::simd_bswap | sym::simd_bitreverse | sym::simd_ctpop => {
3414                // simple unary argument cases
3415                Ok(bx.call_intrinsic(llvm_intrinsic, &[vec_ty], &[args[0].immediate()]))
3416            }
3417            sym::simd_funnel_shl | sym::simd_funnel_shr => Ok(bx.call_intrinsic(
3418                llvm_intrinsic,
3419                &[vec_ty],
3420                &[args[0].immediate(), args[1].immediate(), args[2].immediate()],
3421            )),
3422            sym::simd_carryless_mul => {
3423                if crate::llvm_util::get_version() >= (22, 0, 0) {
3424                    Ok(bx.call_intrinsic(
3425                        llvm_intrinsic,
3426                        &[vec_ty],
3427                        &[args[0].immediate(), args[1].immediate()],
3428                    ))
3429                } else {
3430                    ::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");
3431                }
3432            }
3433            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
3434        };
3435    }
3436
3437    if name == sym::simd_arith_offset {
3438        // This also checks that the first operand is a ptr type.
3439        let pointee = in_elem.builtin_deref(true).unwrap_or_else(|| {
3440            ::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")
3441        });
3442        let layout = bx.layout_of(pointee);
3443        let ptrs = args[0].immediate();
3444        // The second argument must be a ptr-sized integer.
3445        // (We don't care about the signedness, this is wrapping anyway.)
3446        let (_offsets_len, offsets_elem) = args[1].layout.ty.simd_size_and_type(bx.tcx());
3447        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)) {
3448            ::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!(
3449                span,
3450                "must be called with a vector of pointer-sized integers as second argument"
3451            );
3452        }
3453        let offsets = args[1].immediate();
3454
3455        return Ok(bx.gep(bx.backend_type(layout), ptrs, &[offsets]));
3456    }
3457
3458    if name == sym::simd_saturating_add || name == sym::simd_saturating_sub {
3459        let lhs = args[0].immediate();
3460        let rhs = args[1].immediate();
3461        let is_add = name == sym::simd_saturating_add;
3462        let (signed, elem_ty) = match *in_elem.kind() {
3463            ty::Int(i) => (true, bx.cx.type_int_from_ty(i)),
3464            ty::Uint(i) => (false, bx.cx.type_uint_from_ty(i)),
3465            _ => {
3466                {
    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 {
3467                    span,
3468                    name,
3469                    expected_element: args[0].layout.ty.simd_size_and_type(bx.tcx()).1,
3470                    vector_type: args[0].layout.ty
3471                });
3472            }
3473        };
3474        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!(
3475            "llvm.{}{}.sat",
3476            if signed { 's' } else { 'u' },
3477            if is_add { "add" } else { "sub" },
3478        );
3479        let vec_ty = bx.cx.type_vector(elem_ty, in_len as u64);
3480
3481        return Ok(bx.call_intrinsic(llvm_intrinsic, &[vec_ty], &[lhs, rhs]));
3482    }
3483
3484    ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("unknown SIMD intrinsic"));span_bug!(span, "unknown SIMD intrinsic");
3485}