Skip to main content

rustc_codegen_llvm/
intrinsic.rs

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