Skip to main content

rustc_codegen_llvm/
builder.rs

1use std::borrow::{Borrow, Cow};
2use std::ops::Deref;
3use std::{iter, ptr};
4
5use rustc_ast::expand::typetree::FncTree;
6pub(crate) mod autodiff;
7pub(crate) mod gpu_offload;
8
9use libc::{c_char, c_uint};
10use rustc_abi::{self as abi, Align, CanonAbi, Float, Size, WrappingRange};
11use rustc_attr_ir::UnrollAttr;
12use rustc_codegen_ssa::MemFlags;
13use rustc_codegen_ssa::common::{IntPredicate, RealPredicate, SynchronizationScope};
14use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
15use rustc_codegen_ssa::mir::place::PlaceRef;
16use rustc_codegen_ssa::traits::*;
17use rustc_data_structures::small_c_str::SmallCStr;
18use rustc_hir::def_id::DefId;
19use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
20use rustc_middle::ty::layout::{
21    FnAbiError, FnAbiOfHelpers, FnAbiRequest, HasTypingEnv, LayoutError, LayoutOfHelpers,
22    TyAndLayout,
23};
24use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
25use rustc_sanitizers::{cfi, kcfi};
26use rustc_session::config::OptLevel;
27use rustc_span::{Span, bug};
28use rustc_target::callconv::{FnAbi, PassMode};
29use rustc_target::spec::{Arch, HasTargetSpec, SanitizerSet, Target};
30use smallvec::SmallVec;
31use tracing::{debug, instrument};
32
33use crate::abi::FnAbiLlvmExt;
34use crate::attributes;
35use crate::common::Funclet;
36use crate::context::{CodegenCx, FullCx, GenericCx, SCx};
37use crate::llvm::{
38    self, AtomicOrdering, AtomicRmwBinOp, BasicBlock, FromGeneric, GEPNoWrapFlags, Metadata, TRUE,
39    ToLlvmBool, Type, TypeKind, Value,
40};
41use crate::type_of::LayoutLlvmExt;
42
43#[must_use]
44pub(crate) struct GenericBuilder<'a, 'll, CX: Borrow<SCx<'ll>>> {
45    /// Owning pointer that corresponds to an `LLVMBuilderRef`. Disposed on drop.
46    llbuilder_raw: ptr::NonNull<llvm::Builder<'ll>>,
47    pub cx: &'a GenericCx<'ll, CX>,
48    pub span: rustc_span::Span,
49}
50
51pub(crate) type SBuilder<'a, 'll> = GenericBuilder<'a, 'll, SCx<'ll>>;
52pub(crate) type Builder<'a, 'll, 'tcx> = GenericBuilder<'a, 'll, FullCx<'ll, 'tcx>>;
53
54impl<'a, 'll, CX: Borrow<SCx<'ll>>> Drop for GenericBuilder<'a, 'll, CX> {
55    fn drop(&mut self) {
56        unsafe { llvm::LLVMDisposeBuilder(self.llbuilder_raw) };
57    }
58}
59
60impl<'a, 'll> SBuilder<'a, 'll> {
61    pub(crate) fn call(
62        &mut self,
63        llty: Type<'ll>,
64        llfn: Value<'ll>,
65        args: &[Value<'ll>],
66        funclet: Option<&Funclet<'ll>>,
67    ) -> Value<'ll> {
68        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/builder.rs:68",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(68u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                        ::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 {0:?} with args ({1:?})",
                                                    llfn, args) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("call {:?} with args ({:?})", llfn, args);
69
70        let args = self.check_call("call", llty, llfn, args);
71        let funclet_bundle = funclet.map(|funclet| funclet.bundle());
72        let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
73        if let Some(funclet_bundle) = funclet_bundle {
74            bundles.push(funclet_bundle);
75        }
76
77        unsafe {
78            llvm::LLVMBuildCallWithOperandBundles(
79                self.llbuilder(),
80                llty,
81                llfn,
82                args.as_ptr(),
83                args.len() as c_uint,
84                bundles.as_ptr(),
85                bundles.len() as c_uint,
86                c"".as_ptr(),
87            )
88        }
89    }
90}
91
92impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
93    fn with_cx(scx: &'a GenericCx<'ll, CX>) -> Self {
94        // Create a fresh builder from the simple context.
95        let llbuilder_raw = unsafe { llvm::LLVMCreateBuilderForModule(scx.deref().borrow().llmod) };
96        GenericBuilder { llbuilder_raw, cx: scx, span: rustc_span::DUMMY_SP }
97    }
98
99    pub(crate) fn append_block(
100        cx: &'a GenericCx<'ll, CX>,
101        llfn: Value<'ll>,
102        name: &str,
103    ) -> &'ll BasicBlock {
104        unsafe {
105            let name = SmallCStr::new(name);
106            llvm::LLVMAppendBasicBlockInContext(cx.llcx(), llfn, name.as_ptr())
107        }
108    }
109
110    /// Returns a reference to this builder's underlying [`llvm::Builder`],
111    /// tied to the lifetime of self.
112    pub(crate) fn llbuilder<'s>(&'s self) -> &'s llvm::Builder<'ll> {
113        // SAFETY: We own this builder, and the reference lifetime is tied to `&self`
114        // (not to 'll), so it won't be disposed by our Drop while the ref is live.
115        unsafe { self.llbuilder_raw.as_ref() }
116    }
117
118    pub(crate) fn trunc(&mut self, val: Value<'ll>, dest_ty: Type<'ll>) -> Value<'ll> {
119        unsafe { llvm::LLVMBuildTrunc(self.llbuilder(), val, dest_ty, UNNAMED) }
120    }
121
122    pub(crate) fn bitcast(&mut self, val: Value<'ll>, dest_ty: Type<'ll>) -> Value<'ll> {
123        unsafe { llvm::LLVMBuildBitCast(self.llbuilder(), val, dest_ty, UNNAMED) }
124    }
125
126    pub(crate) fn ret_void(&mut self) {
127        llvm::LLVMBuildRetVoid(self.llbuilder());
128    }
129
130    pub(crate) fn ret(&mut self, v: Value<'ll>) {
131        unsafe {
132            llvm::LLVMBuildRet(self.llbuilder(), v);
133        }
134    }
135
136    pub(crate) fn build(cx: &'a GenericCx<'ll, CX>, llbb: &'ll BasicBlock) -> Self {
137        let bx = Self::with_cx(cx);
138        unsafe {
139            llvm::LLVMPositionBuilderAtEnd(bx.llbuilder(), llbb);
140        }
141        bx
142    }
143
144    // The generic builder has less functionality and thus (unlike the other alloca) we can not
145    // easily jump to the beginning of the function to place our allocas there. We trust the user
146    // to manually do that. FIXME(offload): improve the genericCx and add more llvm wrappers to
147    // handle this.
148    pub(crate) fn direct_alloca(&mut self, size: Size, align: Align, name: &str) -> Value<'ll> {
149        let ty = self.cx.type_array(self.cx.type_i8(), size.bytes());
150        let val = unsafe {
151            let alloca = llvm::LLVMBuildAlloca(self.llbuilder(), ty, UNNAMED);
152            llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
153            // Cast to default addrspace if necessary
154            llvm::LLVMBuildPointerCast(self.llbuilder(), alloca, self.cx.type_ptr(), UNNAMED)
155        };
156        if !name.is_empty() {
157            llvm::set_value_name(val, name.as_bytes());
158        }
159        val
160    }
161
162    fn build_gep(
163        &mut self,
164        stride: Size,
165        ptr: Value<'ll>,
166        index: Value<'ll>,
167        flags: GEPNoWrapFlags,
168    ) -> Value<'ll> {
169        let ty = if stride.bytes() == 1 {
170            // LLVM prefers `i8` as the canonical form for a single-byte GEP.
171            self.cx.type_i8()
172        } else {
173            self.cx.type_array(self.cx.type_i8(), stride.bytes())
174        };
175        let indices = &[index];
176        unsafe {
177            llvm::LLVMBuildGEPWithNoWrapFlags(
178                self.llbuilder(),
179                ty,
180                ptr,
181                indices.as_ptr(),
182                indices.len() as c_uint,
183                UNNAMED,
184                flags,
185            )
186        }
187    }
188
189    pub(crate) fn store(&mut self, val: Value<'ll>, ptr: Value<'ll>, align: Align) -> Value<'ll> {
190        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/builder.rs:190",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(190u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                        ::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!("Store {0:?} -> {1:?}",
                                                    val, ptr) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("Store {:?} -> {:?}", val, ptr);
191        {
    match (&self.cx.type_kind(self.cx.val_ty(ptr)), &TypeKind::Pointer) {
        (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!(self.cx.type_kind(self.cx.val_ty(ptr)), TypeKind::Pointer);
192        unsafe {
193            let store = llvm::LLVMBuildStore(self.llbuilder(), val, ptr);
194            llvm::LLVMSetAlignment(store, align.bytes() as c_uint);
195            store
196        }
197    }
198
199    pub(crate) fn load(&mut self, ty: Type<'ll>, ptr: Value<'ll>, align: Align) -> Value<'ll> {
200        unsafe {
201            let load = llvm::LLVMBuildLoad2(self.llbuilder(), ty, ptr, UNNAMED);
202            llvm::LLVMSetAlignment(load, align.bytes() as c_uint);
203            load
204        }
205    }
206}
207
208/// Empty string, to be used where LLVM expects an instruction name, indicating
209/// that the instruction is to be left unnamed (i.e. numbered, in textual IR).
210// FIXME(eddyb) pass `&CStr` directly to FFI once it's a thin pointer.
211pub(crate) const UNNAMED: *const c_char = c"".as_ptr();
212
213impl<'ll, CX: Borrow<SCx<'ll>>> BackendTypes for GenericBuilder<'_, 'll, CX> {
214    type Function = <GenericCx<'ll, CX> as BackendTypes>::Function;
215    type BasicBlock = <GenericCx<'ll, CX> as BackendTypes>::BasicBlock;
216    type Funclet = <GenericCx<'ll, CX> as BackendTypes>::Funclet;
217
218    type Value = <GenericCx<'ll, CX> as BackendTypes>::Value;
219    type Type = <GenericCx<'ll, CX> as BackendTypes>::Type;
220    type FunctionSignature = <GenericCx<'ll, CX> as BackendTypes>::FunctionSignature;
221
222    type DIScope = <GenericCx<'ll, CX> as BackendTypes>::DIScope;
223    type DILocation = <GenericCx<'ll, CX> as BackendTypes>::DILocation;
224    type DIVariable = <GenericCx<'ll, CX> as BackendTypes>::DIVariable;
225}
226
227impl abi::HasDataLayout for Builder<'_, '_, '_> {
228    fn data_layout(&self) -> &abi::TargetDataLayout {
229        self.cx.data_layout()
230    }
231}
232
233impl<'tcx> ty::layout::HasTyCtxt<'tcx> for Builder<'_, '_, 'tcx> {
234    #[inline]
235    fn tcx(&self) -> TyCtxt<'tcx> {
236        self.cx.tcx
237    }
238}
239
240impl<'tcx> ty::layout::HasTypingEnv<'tcx> for Builder<'_, '_, 'tcx> {
241    fn typing_env(&self) -> ty::TypingEnv<'tcx> {
242        self.cx.typing_env()
243    }
244}
245
246impl HasTargetSpec for Builder<'_, '_, '_> {
247    #[inline]
248    fn target_spec(&self) -> &Target {
249        self.cx.target_spec()
250    }
251}
252
253impl<'tcx> LayoutOfHelpers<'tcx> for Builder<'_, '_, 'tcx> {
254    #[inline]
255    fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
256        self.cx.handle_layout_err(err, span, ty)
257    }
258}
259
260impl<'tcx> FnAbiOfHelpers<'tcx> for Builder<'_, '_, 'tcx> {
261    #[inline]
262    fn handle_fn_abi_err(
263        &self,
264        err: FnAbiError<'tcx>,
265        span: Span,
266        fn_abi_request: FnAbiRequest<'tcx>,
267    ) -> ! {
268        self.cx.handle_fn_abi_err(err, span, fn_abi_request)
269    }
270}
271
272impl<'ll, 'tcx> Deref for Builder<'_, 'll, 'tcx> {
273    type Target = CodegenCx<'ll, 'tcx>;
274
275    #[inline]
276    fn deref(&self) -> &Self::Target {
277        self.cx
278    }
279}
280
281macro_rules! math_builder_methods {
282    ($($name:ident($($arg:ident),*) => $llvm_capi:ident),+ $(,)?) => {
283        $(fn $name(&mut self, $($arg: Value<'ll>),*) -> Value<'ll> {
284            unsafe {
285                llvm::$llvm_capi(self.llbuilder(), $($arg,)* UNNAMED)
286            }
287        })+
288    }
289}
290
291macro_rules! set_math_builder_methods {
292    ($($name:ident($($arg:ident),*) => ($llvm_capi:ident, $llvm_set_math:ident)),+ $(,)?) => {
293        $(fn $name(&mut self, $($arg: Value<'ll>),*) -> Value<'ll> {
294            unsafe {
295                let instr = llvm::$llvm_capi(self.llbuilder(), $($arg,)* UNNAMED);
296                llvm::$llvm_set_math(instr);
297                instr
298            }
299        })+
300    }
301}
302
303impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> {
304    type CodegenCx = CodegenCx<'ll, 'tcx>;
305
306    fn build(cx: &'a CodegenCx<'ll, 'tcx>, llbb: &'ll BasicBlock) -> Self {
307        let bx = Builder::with_cx(cx);
308        unsafe {
309            llvm::LLVMPositionBuilderAtEnd(bx.llbuilder(), llbb);
310        }
311        bx
312    }
313
314    fn cx(&self) -> &CodegenCx<'ll, 'tcx> {
315        self.cx
316    }
317
318    fn llbb(&self) -> &'ll BasicBlock {
319        unsafe { llvm::LLVMGetInsertBlock(self.llbuilder()) }
320    }
321
322    fn set_span(&mut self, span: rustc_span::Span) {
323        self.span = span;
324    }
325
326    fn append_block(cx: &'a CodegenCx<'ll, 'tcx>, llfn: Value<'ll>, name: &str) -> &'ll BasicBlock {
327        unsafe {
328            let name = SmallCStr::new(name);
329            llvm::LLVMAppendBasicBlockInContext(cx.llcx, llfn, name.as_ptr())
330        }
331    }
332
333    fn append_sibling_block(&mut self, name: &str) -> &'ll BasicBlock {
334        Self::append_block(self.cx, self.llfn(), name)
335    }
336
337    fn switch_to_block(&mut self, llbb: Self::BasicBlock) {
338        *self = Self::build(self.cx, llbb)
339    }
340
341    fn ret_void(&mut self) {
342        llvm::LLVMBuildRetVoid(self.llbuilder());
343    }
344
345    fn ret(&mut self, v: Value<'ll>) {
346        unsafe {
347            llvm::LLVMBuildRet(self.llbuilder(), v);
348        }
349    }
350
351    fn br(&mut self, dest: &'ll BasicBlock) {
352        unsafe {
353            llvm::LLVMBuildBr(self.llbuilder(), dest);
354        }
355    }
356
357    fn br_with_attrs(&mut self, dest: &'ll BasicBlock, loop_hint_attrs: &[UnrollAttr]) {
358        unsafe {
359            let val = llvm::LLVMBuildBr(self.llbuilder(), dest);
360
361            let mut nodes = Vec::new();
362
363            for unroll in loop_hint_attrs {
364                // UnrollAttr::Count needs a second operand, the provided count, but the other
365                // unroll hints do not.
366                let md_node = if let UnrollAttr::Count(count) = unroll {
367                    let unroll_meta = self.create_metadata("llvm.loop.unroll.count".as_bytes());
368                    let count = llvm::LLVMValueAsMetadata(self.get_const_i32(u64::from(*count)));
369                    self.md_node_in_context(&[unroll_meta, count])
370                } else {
371                    let metadata_str = match unroll {
372                        UnrollAttr::Hint => "llvm.loop.unroll.enable",
373                        UnrollAttr::Full => "llvm.loop.unroll.full",
374                        UnrollAttr::Never => "llvm.loop.unroll.disable",
375                        UnrollAttr::Count(_) => ::core::panicking::unreachable_default_msg()unreachable!(),
376                    };
377                    let unroll_meta = self.create_metadata(metadata_str.as_bytes());
378                    self.md_node_in_context(&[unroll_meta])
379                };
380                nodes.push(md_node);
381            }
382
383            if let [first, ..] = nodes[..] {
384                nodes.insert(0, first);
385
386                // Create the loop metadata node
387                let loop_meta_mdnode = self.set_metadata_node(val, llvm::MD_loop, &nodes);
388
389                // Look up the metadata node as a value
390                let loop_meta_val = llvm::LLVMGetMetadata(val, llvm::MD_loop).unwrap();
391
392                // Replace the first entry with a reference to itself
393                // This is required by LLVM. See the LangRef page for llvm.loop metadata.
394                llvm::LLVMReplaceMDNodeOperandWith(loop_meta_val, 0, loop_meta_mdnode);
395            }
396        }
397    }
398
399    fn cond_br(
400        &mut self,
401        cond: Value<'ll>,
402        then_llbb: &'ll BasicBlock,
403        else_llbb: &'ll BasicBlock,
404    ) {
405        unsafe {
406            llvm::LLVMBuildCondBr(self.llbuilder(), cond, then_llbb, else_llbb);
407        }
408    }
409
410    fn switch(
411        &mut self,
412        v: Value<'ll>,
413        else_llbb: &'ll BasicBlock,
414        cases: impl ExactSizeIterator<Item = (u128, &'ll BasicBlock)>,
415    ) {
416        let switch =
417            unsafe { llvm::LLVMBuildSwitch(self.llbuilder(), v, else_llbb, cases.len() as c_uint) };
418        for (on_val, dest) in cases {
419            let on_val = self.const_uint_big(self.val_ty(v), on_val);
420            unsafe { llvm::LLVMAddCase(switch, on_val, dest) }
421        }
422    }
423
424    fn switch_with_weights(
425        &mut self,
426        v: Self::Value,
427        else_llbb: Self::BasicBlock,
428        else_is_cold: bool,
429        cases: impl ExactSizeIterator<Item = (u128, Self::BasicBlock, bool)>,
430    ) {
431        if self.cx.sess().opts.optimize == rustc_session::config::OptLevel::No {
432            self.switch(v, else_llbb, cases.map(|(val, dest, _)| (val, dest)));
433            return;
434        }
435
436        let id = self.cx.create_metadata(b"branch_weights");
437
438        // For switch instructions with 2 targets, the `llvm.expect` intrinsic is used.
439        // This function handles switch instructions with more than 2 targets and it needs to
440        // emit branch weights metadata instead of using the intrinsic.
441        // The values 1 and 2000 are the same as the values used by the `llvm.expect` intrinsic.
442        let cold_weight = llvm::LLVMValueAsMetadata(self.cx.const_u32(1));
443        let hot_weight = llvm::LLVMValueAsMetadata(self.cx.const_u32(2000));
444        let weight =
445            |is_cold: bool| -> &Metadata { if is_cold { cold_weight } else { hot_weight } };
446
447        let mut md: SmallVec<[&Metadata; 16]> = SmallVec::with_capacity(cases.len() + 2);
448        md.push(id);
449        md.push(weight(else_is_cold));
450
451        let switch =
452            unsafe { llvm::LLVMBuildSwitch(self.llbuilder(), v, else_llbb, cases.len() as c_uint) };
453        for (on_val, dest, is_cold) in cases {
454            let on_val = self.const_uint_big(self.val_ty(v), on_val);
455            unsafe { llvm::LLVMAddCase(switch, on_val, dest) }
456            md.push(weight(is_cold));
457        }
458
459        self.cx.set_metadata_node(switch, llvm::MD_prof, &md);
460    }
461
462    fn invoke(
463        &mut self,
464        llty: Type<'ll>,
465        fn_attrs: Option<&CodegenFnAttrs>,
466        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
467        llfn: Value<'ll>,
468        return_slot: ReturnSlot<Value<'ll>>,
469        args: &[Value<'ll>],
470        then: &'ll BasicBlock,
471        catch: &'ll BasicBlock,
472        funclet: Option<&Funclet<'ll>>,
473        instance: Option<Instance<'tcx>>,
474    ) -> Value<'ll> {
475        // If this function returns indirectly (`PassMode::Indirect`),
476        // the `return_slot` should be the first argument.
477        let args = match return_slot {
478            ReturnSlot::Direct => args.to_vec(),
479            ReturnSlot::Indirect(sret_ptr) => {
480                let mut args = args.to_vec();
481                args.insert(0, sret_ptr);
482                args
483            }
484        };
485        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/builder.rs:485",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(485u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                        ::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!("invoke {0:?} with args ({1:?})",
                                                    llfn, args) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("invoke {:?} with args ({:?})", llfn, args);
486        let args = self.check_call("invoke", llty, llfn, &args);
487        let funclet_bundle = funclet.map(|funclet| funclet.bundle());
488        let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
489        if let Some(funclet_bundle) = funclet_bundle {
490            bundles.push(funclet_bundle);
491        }
492
493        // Emit CFI pointer type membership test
494        self.cfi_type_test(fn_attrs, fn_abi, instance, llfn);
495
496        // Emit KCFI operand bundle
497        let kcfi_bundle = self.kcfi_operand_bundle(fn_attrs, fn_abi, instance, llfn);
498        if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
499            bundles.push(kcfi_bundle);
500        }
501
502        let pauth = self.ptrauth_operand_bundle(llfn, fn_abi);
503        if let Some(p) = pauth.as_ref().map(|b| b.as_ref()) {
504            bundles.push(p);
505        }
506
507        let invoke = unsafe {
508            llvm::LLVMBuildInvokeWithOperandBundles(
509                self.llbuilder(),
510                llty,
511                llfn,
512                args.as_ptr(),
513                args.len() as c_uint,
514                then,
515                catch,
516                bundles.as_ptr(),
517                bundles.len() as c_uint,
518                UNNAMED,
519            )
520        };
521        if let Some(fn_abi) = fn_abi {
522            fn_abi.apply_attrs_callsite(self, invoke);
523        }
524        invoke
525    }
526
527    fn unreachable(&mut self) {
528        unsafe {
529            llvm::LLVMBuildUnreachable(self.llbuilder());
530        }
531    }
532
533    fn add(&mut self, a: Value<'ll>, b: Value<'ll>) -> Value<'ll> {
    unsafe { llvm::LLVMBuildAdd(self.llbuilder(), a, b, UNNAMED) }
}
fn fadd(&mut self, a: Value<'ll>, b: Value<'ll>) -> Value<'ll> {
    unsafe { llvm::LLVMBuildFAdd(self.llbuilder(), a, b, UNNAMED) }
}
fn sub(&mut self, a: Value<'ll>, b: Value<'ll>) -> Value<'ll> {
    unsafe { llvm::LLVMBuildSub(self.llbuilder(), a, b, UNNAMED) }
}
fn fsub(&mut self, a: Value<'ll>, b: Value<'ll>) -> Value<'ll> {
    unsafe { llvm::LLVMBuildFSub(self.llbuilder(), a, b, UNNAMED) }
}
fn mul(&mut self, a: Value<'ll>, b: Value<'ll>) -> Value<'ll> {
    unsafe { llvm::LLVMBuildMul(self.llbuilder(), a, b, UNNAMED) }
}
fn fmul(&mut self, a: Value<'ll>, b: Value<'ll>) -> Value<'ll> {
    unsafe { llvm::LLVMBuildFMul(self.llbuilder(), a, b, UNNAMED) }
}
fn udiv(&mut self, a: Value<'ll>, b: Value<'ll>) -> Value<'ll> {
    unsafe { llvm::LLVMBuildUDiv(self.llbuilder(), a, b, UNNAMED) }
}
fn exactudiv(&mut self, a: Value<'ll>, b: Value<'ll>) -> Value<'ll> {
    unsafe { llvm::LLVMBuildExactUDiv(self.llbuilder(), a, b, UNNAMED) }
}
fn sdiv(&mut self, a: Value<'ll>, b: Value<'ll>) -> Value<'ll> {
    unsafe { llvm::LLVMBuildSDiv(self.llbuilder(), a, b, UNNAMED) }
}
fn exactsdiv(&mut self, a: Value<'ll>, b: Value<'ll>) -> Value<'ll> {
    unsafe { llvm::LLVMBuildExactSDiv(self.llbuilder(), a, b, UNNAMED) }
}
fn fdiv(&mut self, a: Value<'ll>, b: Value<'ll>) -> Value<'ll> {
    unsafe { llvm::LLVMBuildFDiv(self.llbuilder(), a, b, UNNAMED) }
}
fn urem(&mut self, a: Value<'ll>, b: Value<'ll>) -> Value<'ll> {
    unsafe { llvm::LLVMBuildURem(self.llbuilder(), a, b, UNNAMED) }
}
fn srem(&mut self, a: Value<'ll>, b: Value<'ll>) -> Value<'ll> {
    unsafe { llvm::LLVMBuildSRem(self.llbuilder(), a, b, UNNAMED) }
}
fn frem(&mut self, a: Value<'ll>, b: Value<'ll>) -> Value<'ll> {
    unsafe { llvm::LLVMBuildFRem(self.llbuilder(), a, b, UNNAMED) }
}
fn shl(&mut self, a: Value<'ll>, b: Value<'ll>) -> Value<'ll> {
    unsafe { llvm::LLVMBuildShl(self.llbuilder(), a, b, UNNAMED) }
}
fn lshr(&mut self, a: Value<'ll>, b: Value<'ll>) -> Value<'ll> {
    unsafe { llvm::LLVMBuildLShr(self.llbuilder(), a, b, UNNAMED) }
}
fn ashr(&mut self, a: Value<'ll>, b: Value<'ll>) -> Value<'ll> {
    unsafe { llvm::LLVMBuildAShr(self.llbuilder(), a, b, UNNAMED) }
}
fn and(&mut self, a: Value<'ll>, b: Value<'ll>) -> Value<'ll> {
    unsafe { llvm::LLVMBuildAnd(self.llbuilder(), a, b, UNNAMED) }
}
fn or(&mut self, a: Value<'ll>, b: Value<'ll>) -> Value<'ll> {
    unsafe { llvm::LLVMBuildOr(self.llbuilder(), a, b, UNNAMED) }
}
fn xor(&mut self, a: Value<'ll>, b: Value<'ll>) -> Value<'ll> {
    unsafe { llvm::LLVMBuildXor(self.llbuilder(), a, b, UNNAMED) }
}
fn neg(&mut self, x: Value<'ll>) -> Value<'ll> {
    unsafe { llvm::LLVMBuildNeg(self.llbuilder(), x, UNNAMED) }
}
fn fneg(&mut self, x: Value<'ll>) -> Value<'ll> {
    unsafe { llvm::LLVMBuildFNeg(self.llbuilder(), x, UNNAMED) }
}
fn not(&mut self, x: Value<'ll>) -> Value<'ll> {
    unsafe { llvm::LLVMBuildNot(self.llbuilder(), x, UNNAMED) }
}
fn unchecked_sadd(&mut self, x: Value<'ll>, y: Value<'ll>) -> Value<'ll> {
    unsafe { llvm::LLVMBuildNSWAdd(self.llbuilder(), x, y, UNNAMED) }
}
fn unchecked_uadd(&mut self, x: Value<'ll>, y: Value<'ll>) -> Value<'ll> {
    unsafe { llvm::LLVMBuildNUWAdd(self.llbuilder(), x, y, UNNAMED) }
}
fn unchecked_ssub(&mut self, x: Value<'ll>, y: Value<'ll>) -> Value<'ll> {
    unsafe { llvm::LLVMBuildNSWSub(self.llbuilder(), x, y, UNNAMED) }
}
fn unchecked_usub(&mut self, x: Value<'ll>, y: Value<'ll>) -> Value<'ll> {
    unsafe { llvm::LLVMBuildNUWSub(self.llbuilder(), x, y, UNNAMED) }
}
fn unchecked_smul(&mut self, x: Value<'ll>, y: Value<'ll>) -> Value<'ll> {
    unsafe { llvm::LLVMBuildNSWMul(self.llbuilder(), x, y, UNNAMED) }
}
fn unchecked_umul(&mut self, x: Value<'ll>, y: Value<'ll>) -> Value<'ll> {
    unsafe { llvm::LLVMBuildNUWMul(self.llbuilder(), x, y, UNNAMED) }
}math_builder_methods! {
534        add(a, b) => LLVMBuildAdd,
535        fadd(a, b) => LLVMBuildFAdd,
536        sub(a, b) => LLVMBuildSub,
537        fsub(a, b) => LLVMBuildFSub,
538        mul(a, b) => LLVMBuildMul,
539        fmul(a, b) => LLVMBuildFMul,
540        udiv(a, b) => LLVMBuildUDiv,
541        exactudiv(a, b) => LLVMBuildExactUDiv,
542        sdiv(a, b) => LLVMBuildSDiv,
543        exactsdiv(a, b) => LLVMBuildExactSDiv,
544        fdiv(a, b) => LLVMBuildFDiv,
545        urem(a, b) => LLVMBuildURem,
546        srem(a, b) => LLVMBuildSRem,
547        frem(a, b) => LLVMBuildFRem,
548        shl(a, b) => LLVMBuildShl,
549        lshr(a, b) => LLVMBuildLShr,
550        ashr(a, b) => LLVMBuildAShr,
551        and(a, b) => LLVMBuildAnd,
552        or(a, b) => LLVMBuildOr,
553        xor(a, b) => LLVMBuildXor,
554        neg(x) => LLVMBuildNeg,
555        fneg(x) => LLVMBuildFNeg,
556        not(x) => LLVMBuildNot,
557        unchecked_sadd(x, y) => LLVMBuildNSWAdd,
558        unchecked_uadd(x, y) => LLVMBuildNUWAdd,
559        unchecked_ssub(x, y) => LLVMBuildNSWSub,
560        unchecked_usub(x, y) => LLVMBuildNUWSub,
561        unchecked_smul(x, y) => LLVMBuildNSWMul,
562        unchecked_umul(x, y) => LLVMBuildNUWMul,
563    }
564
565    fn unchecked_suadd(&mut self, a: Value<'ll>, b: Value<'ll>) -> Value<'ll> {
566        unsafe {
567            let add = llvm::LLVMBuildAdd(self.llbuilder(), a, b, UNNAMED);
568            if llvm::LLVMIsAInstruction(add).is_some() {
569                llvm::LLVMSetNUW(add, TRUE);
570                llvm::LLVMSetNSW(add, TRUE);
571            }
572            add
573        }
574    }
575    fn unchecked_susub(&mut self, a: Value<'ll>, b: Value<'ll>) -> Value<'ll> {
576        unsafe {
577            let sub = llvm::LLVMBuildSub(self.llbuilder(), a, b, UNNAMED);
578            if llvm::LLVMIsAInstruction(sub).is_some() {
579                llvm::LLVMSetNUW(sub, TRUE);
580                llvm::LLVMSetNSW(sub, TRUE);
581            }
582            sub
583        }
584    }
585    fn unchecked_sumul(&mut self, a: Value<'ll>, b: Value<'ll>) -> Value<'ll> {
586        unsafe {
587            let mul = llvm::LLVMBuildMul(self.llbuilder(), a, b, UNNAMED);
588            if llvm::LLVMIsAInstruction(mul).is_some() {
589                llvm::LLVMSetNUW(mul, TRUE);
590                llvm::LLVMSetNSW(mul, TRUE);
591            }
592            mul
593        }
594    }
595
596    fn or_disjoint(&mut self, a: Value<'ll>, b: Value<'ll>) -> Value<'ll> {
597        unsafe {
598            let or = llvm::LLVMBuildOr(self.llbuilder(), a, b, UNNAMED);
599
600            // If a and b are both values, then `or` is a value, rather than
601            // an instruction, so we need to check before setting the flag.
602            // (See also `LLVMBuildNUWNeg` which also needs a check.)
603            if llvm::LLVMIsAInstruction(or).is_some() {
604                llvm::LLVMSetIsDisjoint(or, TRUE);
605            }
606            or
607        }
608    }
609
610    fn fadd_fast(&mut self, x: Value<'ll>, y: Value<'ll>) -> Value<'ll> {
    unsafe {
        let instr = llvm::LLVMBuildFAdd(self.llbuilder(), x, y, UNNAMED);
        llvm::LLVMRustSetFastMath(instr);
        instr
    }
}
fn fsub_fast(&mut self, x: Value<'ll>, y: Value<'ll>) -> Value<'ll> {
    unsafe {
        let instr = llvm::LLVMBuildFSub(self.llbuilder(), x, y, UNNAMED);
        llvm::LLVMRustSetFastMath(instr);
        instr
    }
}
fn fmul_fast(&mut self, x: Value<'ll>, y: Value<'ll>) -> Value<'ll> {
    unsafe {
        let instr = llvm::LLVMBuildFMul(self.llbuilder(), x, y, UNNAMED);
        llvm::LLVMRustSetFastMath(instr);
        instr
    }
}
fn fdiv_fast(&mut self, x: Value<'ll>, y: Value<'ll>) -> Value<'ll> {
    unsafe {
        let instr = llvm::LLVMBuildFDiv(self.llbuilder(), x, y, UNNAMED);
        llvm::LLVMRustSetFastMath(instr);
        instr
    }
}
fn frem_fast(&mut self, x: Value<'ll>, y: Value<'ll>) -> Value<'ll> {
    unsafe {
        let instr = llvm::LLVMBuildFRem(self.llbuilder(), x, y, UNNAMED);
        llvm::LLVMRustSetFastMath(instr);
        instr
    }
}
fn fadd_algebraic(&mut self, x: Value<'ll>, y: Value<'ll>) -> Value<'ll> {
    unsafe {
        let instr = llvm::LLVMBuildFAdd(self.llbuilder(), x, y, UNNAMED);
        llvm::LLVMRustSetAlgebraicMath(instr);
        instr
    }
}
fn fsub_algebraic(&mut self, x: Value<'ll>, y: Value<'ll>) -> Value<'ll> {
    unsafe {
        let instr = llvm::LLVMBuildFSub(self.llbuilder(), x, y, UNNAMED);
        llvm::LLVMRustSetAlgebraicMath(instr);
        instr
    }
}
fn fmul_algebraic(&mut self, x: Value<'ll>, y: Value<'ll>) -> Value<'ll> {
    unsafe {
        let instr = llvm::LLVMBuildFMul(self.llbuilder(), x, y, UNNAMED);
        llvm::LLVMRustSetAlgebraicMath(instr);
        instr
    }
}
fn fdiv_algebraic(&mut self, x: Value<'ll>, y: Value<'ll>) -> Value<'ll> {
    unsafe {
        let instr = llvm::LLVMBuildFDiv(self.llbuilder(), x, y, UNNAMED);
        llvm::LLVMRustSetAlgebraicMath(instr);
        instr
    }
}
fn frem_algebraic(&mut self, x: Value<'ll>, y: Value<'ll>) -> Value<'ll> {
    unsafe {
        let instr = llvm::LLVMBuildFRem(self.llbuilder(), x, y, UNNAMED);
        llvm::LLVMRustSetAlgebraicMath(instr);
        instr
    }
}set_math_builder_methods! {
611        fadd_fast(x, y) => (LLVMBuildFAdd, LLVMRustSetFastMath),
612        fsub_fast(x, y) => (LLVMBuildFSub, LLVMRustSetFastMath),
613        fmul_fast(x, y) => (LLVMBuildFMul, LLVMRustSetFastMath),
614        fdiv_fast(x, y) => (LLVMBuildFDiv, LLVMRustSetFastMath),
615        frem_fast(x, y) => (LLVMBuildFRem, LLVMRustSetFastMath),
616        fadd_algebraic(x, y) => (LLVMBuildFAdd, LLVMRustSetAlgebraicMath),
617        fsub_algebraic(x, y) => (LLVMBuildFSub, LLVMRustSetAlgebraicMath),
618        fmul_algebraic(x, y) => (LLVMBuildFMul, LLVMRustSetAlgebraicMath),
619        fdiv_algebraic(x, y) => (LLVMBuildFDiv, LLVMRustSetAlgebraicMath),
620        frem_algebraic(x, y) => (LLVMBuildFRem, LLVMRustSetAlgebraicMath),
621    }
622
623    fn checked_binop(
624        &mut self,
625        oop: OverflowOp,
626        ty: Ty<'tcx>,
627        lhs: Self::Value,
628        rhs: Self::Value,
629    ) -> (Self::Value, Self::Value) {
630        let (size, signed) = ty.int_size_and_signed(self.tcx);
631        let width = size.bits();
632
633        if !signed {
634            match oop {
635                OverflowOp::Sub => {
636                    // Emit sub and icmp instead of llvm.usub.with.overflow. LLVM considers these
637                    // to be the canonical form. It will attempt to reform llvm.usub.with.overflow
638                    // in the backend if profitable.
639                    let sub = self.sub(lhs, rhs);
640                    let cmp = self.icmp(IntPredicate::IntULT, lhs, rhs);
641                    return (sub, cmp);
642                }
643                OverflowOp::Add => {
644                    // Like with sub above, using icmp is the preferred form. See
645                    // <https://rust-lang.zulipchat.com/#narrow/channel/187780-t-compiler.2Fllvm/topic/.60uadd.2Ewith.2Eoverflow.60.20.28again.29/near/533041085>
646                    let add = self.add(lhs, rhs);
647                    let cmp = self.icmp(IntPredicate::IntULT, add, lhs);
648                    return (add, cmp);
649                }
650                OverflowOp::Mul => {}
651            }
652        }
653
654        let oop_str = match oop {
655            OverflowOp::Add => "add",
656            OverflowOp::Sub => "sub",
657            OverflowOp::Mul => "mul",
658        };
659
660        let name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("llvm.{0}{1}.with.overflow",
                if signed { 's' } else { 'u' }, oop_str))
    })format!("llvm.{}{oop_str}.with.overflow", if signed { 's' } else { 'u' });
661
662        let res = self.call_intrinsic(name, &[self.type_ix(width)], &[lhs, rhs]);
663        (self.extract_value(res, 0), self.extract_value(res, 1))
664    }
665
666    fn from_immediate(&mut self, val: Self::Value) -> Self::Value {
667        if self.cx().val_ty(val) == self.cx().type_i1() {
668            self.zext(val, self.cx().type_i8())
669        } else {
670            val
671        }
672    }
673
674    fn to_immediate_scalar(&mut self, val: Self::Value, scalar: abi::Scalar) -> Self::Value {
675        if scalar.is_bool() {
676            return self.unchecked_utrunc(val, self.cx().type_i1());
677        }
678        val
679    }
680
681    fn alloca(&mut self, size: Size, align: Align) -> Value<'ll> {
682        let mut bx = Builder::with_cx(self.cx);
683        bx.position_at_start(unsafe { llvm::LLVMGetFirstBasicBlock(self.llfn()) });
684        bx.direct_alloca(size, align, "")
685    }
686
687    fn alloca_with_ty(&mut self, layout: TyAndLayout<'tcx>) -> Self::Value {
688        let mut bx = Builder::with_cx(self.cx);
689        bx.position_at_start(unsafe { llvm::LLVMGetFirstBasicBlock(self.llfn()) });
690        let scalable_vector_ty = layout.llvm_type(self.cx);
691
692        unsafe {
693            let alloca = llvm::LLVMBuildAlloca(bx.llbuilder(), scalable_vector_ty, UNNAMED);
694            llvm::LLVMSetAlignment(alloca, layout.align.bytes() as c_uint);
695            alloca
696        }
697    }
698
699    fn load(&mut self, ty: Type<'ll>, ptr: Value<'ll>, align: Align) -> Value<'ll> {
700        unsafe {
701            let load = llvm::LLVMBuildLoad2(self.llbuilder(), ty, ptr, UNNAMED);
702            let align = align.min(self.cx().tcx.sess.target.max_reliable_alignment());
703            llvm::LLVMSetAlignment(load, align.bytes() as c_uint);
704            load
705        }
706    }
707
708    fn volatile_load(&mut self, ty: Type<'ll>, ptr: Value<'ll>, align: Align) -> Value<'ll> {
709        unsafe {
710            let load = self.load(ty, ptr, align);
711            llvm::LLVMSetVolatile(load, llvm::TRUE);
712            load
713        }
714    }
715
716    fn atomic_load(
717        &mut self,
718        ty: Type<'ll>,
719        ptr: Value<'ll>,
720        order: rustc_middle::ty::AtomicOrdering,
721        volatile: bool,
722        size: Size,
723    ) -> Value<'ll> {
724        unsafe {
725            let load = llvm::LLVMBuildLoad2(self.llbuilder(), ty, ptr, UNNAMED);
726            // Set atomic ordering
727            llvm::LLVMSetOrdering(load, AtomicOrdering::from_generic(order));
728            if volatile {
729                llvm::LLVMSetVolatile(load, llvm::TRUE);
730            }
731            // LLVM requires the alignment of atomic loads to be at least the size of the type.
732            llvm::LLVMSetAlignment(load, size.bytes() as c_uint);
733            load
734        }
735    }
736
737    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("load_operand",
                                    "rustc_codegen_llvm::builder", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/builder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(737u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("place")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("place");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: OperandRef<'tcx, Value<'ll>> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            if place.layout.is_unsized() {
                let tail =
                    self.tcx.struct_tail_for_codegen(place.layout.ty,
                        self.typing_env());
                if #[allow(non_exhaustive_omitted_patterns)] match tail.kind()
                        {
                        ty::Foreign(..) => true,
                        _ => false,
                    } {
                    {
                        ::core::panicking::panic_fmt(format_args!("unsized locals must not be `extern` types"));
                    };
                }
            }
            {
                match (&place.val.llextra.is_some(),
                        &place.layout.is_unsized()) {
                    (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);
                        }
                    }
                }
            };
            if place.layout.is_zst() {
                return OperandRef::zero_sized(place.layout);
            }
            fn scalar_load_metadata<'a, 'll,
                'tcx>(bx: &mut Builder<'a, 'll, 'tcx>, load: Value<'ll>,
                scalar: abi::Scalar, layout: TyAndLayout<'tcx>,
                offset: Size) {
                {}

                #[allow(clippy :: suspicious_else_formatting)]
                {
                    let __tracing_attr_span;
                    let __tracing_attr_guard;
                    if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() ||
                            { false } {
                        __tracing_attr_span =
                            {
                                use ::tracing::__macro_support::Callsite as _;
                                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                    {
                                        static META: ::tracing::Metadata<'static> =
                                            {
                                                ::tracing_core::metadata::Metadata::new("scalar_load_metadata",
                                                    "rustc_codegen_llvm::builder", ::tracing::Level::TRACE,
                                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/builder.rs"),
                                                    ::tracing_core::__macro_support::Option::Some(754u32),
                                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                                                    ::tracing_core::field::FieldSet::new(&[{
                                                                        const NAME:
                                                                            ::tracing::__macro_support::FieldName<{
                                                                                ::tracing::__macro_support::FieldName::len("load")
                                                                            }> =
                                                                            ::tracing::__macro_support::FieldName::new("load");
                                                                        NAME.as_str()
                                                                    },
                                                                    {
                                                                        const NAME:
                                                                            ::tracing::__macro_support::FieldName<{
                                                                                ::tracing::__macro_support::FieldName::len("scalar")
                                                                            }> =
                                                                            ::tracing::__macro_support::FieldName::new("scalar");
                                                                        NAME.as_str()
                                                                    },
                                                                    {
                                                                        const NAME:
                                                                            ::tracing::__macro_support::FieldName<{
                                                                                ::tracing::__macro_support::FieldName::len("layout")
                                                                            }> =
                                                                            ::tracing::__macro_support::FieldName::new("layout");
                                                                        NAME.as_str()
                                                                    },
                                                                    {
                                                                        const NAME:
                                                                            ::tracing::__macro_support::FieldName<{
                                                                                ::tracing::__macro_support::FieldName::len("offset")
                                                                            }> =
                                                                            ::tracing::__macro_support::FieldName::new("offset");
                                                                        NAME.as_str()
                                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                    ::tracing::metadata::Kind::SPAN)
                                            };
                                        ::tracing::callsite::DefaultCallsite::new(&META)
                                    };
                                let mut interest = ::tracing::subscriber::Interest::never();
                                if ::tracing::Level::TRACE <=
                                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                ::tracing::Level::TRACE <=
                                                    ::tracing::level_filters::LevelFilter::current() &&
                                            { interest = __CALLSITE.interest(); !interest.is_never() }
                                        &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest) {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Span::new(meta,
                                        &{
                                                #[allow(unused_imports)]
                                                use ::tracing::field::{debug, display, Value};
                                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&load)
                                                                            as &dyn ::tracing::field::Value)),
                                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&scalar)
                                                                            as &dyn ::tracing::field::Value)),
                                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&layout)
                                                                            as &dyn ::tracing::field::Value)),
                                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&offset)
                                                                            as &dyn ::tracing::field::Value))])
                                            })
                                } else {
                                    let span =
                                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                                    {};
                                    span
                                }
                            };
                        __tracing_attr_guard = __tracing_attr_span.enter();
                    }

                    #[warn(clippy :: suspicious_else_formatting)]
                    {

                        #[allow(unknown_lints, unreachable_code, clippy ::
                        diverging_sub_expression, clippy :: empty_loop, clippy ::
                        let_unit_value, clippy :: let_with_type_underscore, clippy
                        :: needless_return, clippy :: unreachable)]
                        if false {
                            let __tracing_attr_fake_return: () = loop {};
                            return __tracing_attr_fake_return;
                        }
                        {
                            if bx.cx.sess().opts.optimize == OptLevel::No { return; }
                            if !scalar.is_uninit_valid() { bx.noundef_metadata(load); }
                            match scalar.primitive() {
                                abi::Primitive::Int(..) => {
                                    if !scalar.is_always_valid(bx) {
                                        bx.range_metadata(load, scalar.valid_range(bx));
                                    }
                                }
                                abi::Primitive::Pointer(_) => {
                                    if !scalar.valid_range(bx).contains(0) {
                                        bx.nonnull_metadata(load);
                                    }
                                    if let Some(pointee) = layout.pointee_info_at(bx, offset) &&
                                            pointee.align > Align::ONE {
                                        bx.align_metadata(load, pointee.align);
                                    }
                                }
                                abi::Primitive::Float(_) => {}
                            }
                        }
                    }
                }
            }
            let val =
                if let Some(_) = place.val.llextra {
                    OperandValue::Ref(place.val)
                } else if place.layout.backend_repr.is_scalar_or_simd() {
                    let mut const_llval = None;
                    let llty = place.layout.llvm_type(self);
                    if let Some(global) =
                            llvm::LLVMIsAGlobalVariable(place.val.llval) {
                        if llvm::LLVMIsGlobalConstant(global).is_true() {
                            if let Some(init) = llvm::LLVMGetInitializer(global) {
                                if self.val_ty(init) == llty { const_llval = Some(init); }
                            }
                        }
                    }
                    let llval =
                        const_llval.unwrap_or_else(||
                                {
                                    let load =
                                        self.load(llty, place.val.llval, place.val.align);
                                    if let abi::BackendRepr::Scalar(scalar) =
                                            place.layout.backend_repr {
                                        scalar_load_metadata(self, load, scalar, place.layout,
                                            Size::ZERO);
                                        self.to_immediate_scalar(load, scalar)
                                    } else { load }
                                });
                    OperandValue::Immediate(llval)
                } else if let abi::BackendRepr::ScalarPair { a, b, b_offset }
                        = place.layout.backend_repr {
                    let mut load =
                        |i, scalar: abi::Scalar, layout, align, offset|
                            {
                                let llptr =
                                    if i == 0 {
                                        place.val.llval
                                    } else {
                                        self.inbounds_ptradd(place.val.llval,
                                            self.const_usize(b_offset.bytes()))
                                    };
                                let llty =
                                    place.layout.scalar_pair_element_llvm_type(self, i, false);
                                let load = self.load(llty, llptr, align);
                                scalar_load_metadata(self, load, scalar, layout, offset);
                                self.to_immediate_scalar(load, scalar)
                            };
                    OperandValue::Pair(load(0, a, place.layout, place.val.align,
                            Size::ZERO),
                        load(1, b, place.layout,
                            place.val.align.restrict_for_offset(b_offset), b_offset))
                } else { OperandValue::Ref(place.val) };
            OperandRef { val, layout: place.layout, move_annotation: None }
        }
    }
}#[instrument(level = "trace", skip(self))]
738    fn load_operand(&mut self, place: PlaceRef<'tcx, Value<'ll>>) -> OperandRef<'tcx, Value<'ll>> {
739        if place.layout.is_unsized() {
740            let tail = self.tcx.struct_tail_for_codegen(place.layout.ty, self.typing_env());
741            if matches!(tail.kind(), ty::Foreign(..)) {
742                // Unsized locals and, at least conceptually, even unsized arguments must be copied
743                // around, which requires dynamically determining their size. Therefore, we cannot
744                // allow `extern` types here. Consult t-opsem before removing this check.
745                panic!("unsized locals must not be `extern` types");
746            }
747        }
748        assert_eq!(place.val.llextra.is_some(), place.layout.is_unsized());
749
750        if place.layout.is_zst() {
751            return OperandRef::zero_sized(place.layout);
752        }
753
754        #[instrument(level = "trace", skip(bx))]
755        fn scalar_load_metadata<'a, 'll, 'tcx>(
756            bx: &mut Builder<'a, 'll, 'tcx>,
757            load: Value<'ll>,
758            scalar: abi::Scalar,
759            layout: TyAndLayout<'tcx>,
760            offset: Size,
761        ) {
762            if bx.cx.sess().opts.optimize == OptLevel::No {
763                // Don't emit metadata we're not going to use
764                return;
765            }
766
767            if !scalar.is_uninit_valid() {
768                bx.noundef_metadata(load);
769            }
770
771            match scalar.primitive() {
772                abi::Primitive::Int(..) => {
773                    if !scalar.is_always_valid(bx) {
774                        bx.range_metadata(load, scalar.valid_range(bx));
775                    }
776                }
777                abi::Primitive::Pointer(_) => {
778                    if !scalar.valid_range(bx).contains(0) {
779                        bx.nonnull_metadata(load);
780                    }
781
782                    if let Some(pointee) = layout.pointee_info_at(bx, offset)
783                        && pointee.align > Align::ONE
784                    {
785                        bx.align_metadata(load, pointee.align);
786                    }
787                }
788                abi::Primitive::Float(_) => {}
789            }
790        }
791
792        let val = if let Some(_) = place.val.llextra {
793            // FIXME: Merge with the `else` below?
794            OperandValue::Ref(place.val)
795        } else if place.layout.backend_repr.is_scalar_or_simd() {
796            let mut const_llval = None;
797            let llty = place.layout.llvm_type(self);
798            if let Some(global) = llvm::LLVMIsAGlobalVariable(place.val.llval) {
799                if llvm::LLVMIsGlobalConstant(global).is_true() {
800                    if let Some(init) = llvm::LLVMGetInitializer(global) {
801                        if self.val_ty(init) == llty {
802                            const_llval = Some(init);
803                        }
804                    }
805                }
806            }
807
808            let llval = const_llval.unwrap_or_else(|| {
809                let load = self.load(llty, place.val.llval, place.val.align);
810                if let abi::BackendRepr::Scalar(scalar) = place.layout.backend_repr {
811                    scalar_load_metadata(self, load, scalar, place.layout, Size::ZERO);
812                    self.to_immediate_scalar(load, scalar)
813                } else {
814                    load
815                }
816            });
817            OperandValue::Immediate(llval)
818        } else if let abi::BackendRepr::ScalarPair { a, b, b_offset } = place.layout.backend_repr {
819            let mut load = |i, scalar: abi::Scalar, layout, align, offset| {
820                let llptr = if i == 0 {
821                    place.val.llval
822                } else {
823                    self.inbounds_ptradd(place.val.llval, self.const_usize(b_offset.bytes()))
824                };
825                let llty = place.layout.scalar_pair_element_llvm_type(self, i, false);
826                let load = self.load(llty, llptr, align);
827                scalar_load_metadata(self, load, scalar, layout, offset);
828                self.to_immediate_scalar(load, scalar)
829            };
830
831            OperandValue::Pair(
832                load(0, a, place.layout, place.val.align, Size::ZERO),
833                load(1, b, place.layout, place.val.align.restrict_for_offset(b_offset), b_offset),
834            )
835        } else {
836            OperandValue::Ref(place.val)
837        };
838
839        OperandRef { val, layout: place.layout, move_annotation: None }
840    }
841
842    fn write_operand_repeatedly(
843        &mut self,
844        cg_elem: OperandRef<'tcx, Value<'ll>>,
845        count: u64,
846        dest: PlaceRef<'tcx, Value<'ll>>,
847    ) {
848        if self.cx.sess().opts.optimize == OptLevel::No {
849            // To let debuggers single-step over lines like
850            //
851            //     let foo = ["bar"; 42];
852            //
853            // we need the debugger-friendly LLVM IR that `_unoptimized()`
854            // provides. The `_optimized()` version generates trickier LLVM IR.
855            // See PR #148058 for a failed attempt at handling that.
856            self.write_operand_repeatedly_unoptimized(cg_elem, count, dest);
857        } else {
858            self.write_operand_repeatedly_optimized(cg_elem, count, dest);
859        }
860    }
861
862    fn range_metadata(&mut self, load: Value<'ll>, range: WrappingRange) {
863        if self.cx.sess().opts.optimize == OptLevel::No {
864            // Don't emit metadata we're not going to use
865            return;
866        }
867
868        let llty = self.cx.val_ty(load);
869        let md = [
870            llvm::LLVMValueAsMetadata(self.cx.const_uint_big(llty, range.start)),
871            llvm::LLVMValueAsMetadata(self.cx.const_uint_big(llty, range.end.wrapping_add(1))),
872        ];
873        self.set_metadata_node(load, llvm::MD_range, &md);
874    }
875
876    fn nonnull_metadata(&mut self, load: Value<'ll>) {
877        self.set_metadata_node(load, llvm::MD_nonnull, &[]);
878    }
879
880    fn store_with_flags(
881        &mut self,
882        val: Value<'ll>,
883        ptr: Value<'ll>,
884        align: Align,
885        flags: MemFlags,
886    ) {
887        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/builder.rs:887",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(887u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                        ::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!("Store {0:?} -> {1:?} ({2:?})",
                                                    val, ptr, flags) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("Store {:?} -> {:?} ({:?})", val, ptr, flags);
888        {
    match (&self.cx.type_kind(self.cx.val_ty(ptr)), &TypeKind::Pointer) {
        (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!(self.cx.type_kind(self.cx.val_ty(ptr)), TypeKind::Pointer);
889        unsafe {
890            let store = llvm::LLVMBuildStore(self.llbuilder(), val, ptr);
891            let align = align.min(self.cx().tcx.sess.target.max_reliable_alignment());
892            let align = align.bytes() as c_uint;
893            llvm::LLVMSetAlignment(store, align);
894            if flags.contains(MemFlags::VOLATILE) {
895                llvm::LLVMSetVolatile(store, llvm::TRUE);
896            }
897            if flags.contains(MemFlags::NONTEMPORAL) {
898                // Make sure that the current target architectures supports "sane" non-temporal
899                // stores, i.e., non-temporal stores that are equivalent to regular stores except
900                // for performance. LLVM doesn't seem to care about this, and will happily treat
901                // `!nontemporal` stores as-if they were normal stores (for reordering optimizations
902                // etc) even on x86, despite later lowering them to MOVNT which do *not* behave like
903                // regular stores but require special fences. So we keep a list of architectures
904                // where `!nontemporal` is known to be truly just a hint, and use regular stores
905                // everywhere else. (In the future, we could alternatively ensure that an sfence
906                // gets emitted after a sequence of movnt before any kind of synchronizing
907                // operation. But it's not clear how to do that with LLVM.)
908                // For more context, see <https://github.com/rust-lang/rust/issues/114582> and
909                // <https://github.com/llvm/llvm-project/issues/64521>.
910                let use_nontemporal = #[allow(non_exhaustive_omitted_patterns)] match self.cx.tcx.sess.target.arch {
    Arch::AArch64 | Arch::Arm | Arch::RiscV32 | Arch::RiscV64 => true,
    _ => false,
}matches!(
911                    self.cx.tcx.sess.target.arch,
912                    Arch::AArch64 | Arch::Arm | Arch::RiscV32 | Arch::RiscV64
913                );
914                if use_nontemporal {
915                    // According to LLVM [1] building a nontemporal store must
916                    // *always* point to a metadata value of the integer 1.
917                    //
918                    // [1]: https://llvm.org/docs/LangRef.html#store-instruction
919                    let one = llvm::LLVMValueAsMetadata(self.cx.const_i32(1));
920                    self.set_metadata_node(store, llvm::MD_nontemporal, &[one]);
921                }
922            }
923            if flags.contains(MemFlags::CAPTURES_READ_ONLY) {
924                if !(self.type_kind(self.val_ty(val)) == TypeKind::Pointer) {
    {
        ::core::panicking::panic_fmt(format_args!("CAPTURED_READ_ONLY is only supported on pointer stores"));
    }
};assert!(
925                    self.type_kind(self.val_ty(val)) == TypeKind::Pointer,
926                    "CAPTURED_READ_ONLY is only supported on pointer stores"
927                );
928                let args = [
929                    self.cx.create_metadata(b"address"),
930                    self.cx.create_metadata(b"read_provenance"),
931                ];
932                // FIXME: Switch this to use MD_captures once LLVM 22 is the minimum.
933                let id = self.get_md_kind_id("captures");
934                let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, args.as_ptr(), args.len());
935                self.set_metadata(store, id, md);
936            }
937        }
938    }
939
940    fn atomic_store(
941        &mut self,
942        val: Value<'ll>,
943        ptr: Value<'ll>,
944        order: rustc_middle::ty::AtomicOrdering,
945        volatile: bool,
946        size: Size,
947    ) {
948        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/builder.rs:948",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(948u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                        ::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!("Store {0:?} -> {1:?}",
                                                    val, ptr) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("Store {:?} -> {:?}", val, ptr);
949        {
    match (&self.cx.type_kind(self.cx.val_ty(ptr)), &TypeKind::Pointer) {
        (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!(self.cx.type_kind(self.cx.val_ty(ptr)), TypeKind::Pointer);
950        unsafe {
951            let store = llvm::LLVMBuildStore(self.llbuilder(), val, ptr);
952            // Set atomic ordering
953            llvm::LLVMSetOrdering(store, AtomicOrdering::from_generic(order));
954            if volatile {
955                llvm::LLVMSetVolatile(store, llvm::TRUE);
956            }
957            // LLVM requires the alignment of atomic stores to be at least the size of the type.
958            llvm::LLVMSetAlignment(store, size.bytes() as c_uint);
959        }
960    }
961
962    fn gep(&mut self, stride: Size, ptr: Value<'ll>, index: Value<'ll>) -> Value<'ll> {
963        self.build_gep(stride, ptr, index, GEPNoWrapFlags::default())
964    }
965
966    fn inbounds_gep(&mut self, stride: Size, ptr: Value<'ll>, index: Value<'ll>) -> Value<'ll> {
967        self.build_gep(stride, ptr, index, GEPNoWrapFlags::InBounds)
968    }
969
970    fn inbounds_nuw_gep(&mut self, stride: Size, ptr: Value<'ll>, index: Value<'ll>) -> Value<'ll> {
971        self.build_gep(stride, ptr, index, GEPNoWrapFlags::InBounds | GEPNoWrapFlags::NUW)
972    }
973
974    /* Casts */
975    fn trunc(&mut self, val: Value<'ll>, dest_ty: Type<'ll>) -> Value<'ll> {
976        unsafe { llvm::LLVMBuildTrunc(self.llbuilder(), val, dest_ty, UNNAMED) }
977    }
978
979    fn unchecked_utrunc(&mut self, val: Value<'ll>, dest_ty: Type<'ll>) -> Value<'ll> {
980        if true {
    {
        match (&self.val_ty(val), &dest_ty) {
            (left_val, right_val) => {
                if *left_val == *right_val {
                    let kind = ::core::panicking::AssertKind::Ne;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_ne!(self.val_ty(val), dest_ty);
981
982        let trunc = self.trunc(val, dest_ty);
983        unsafe {
984            if llvm::LLVMIsAInstruction(trunc).is_some() {
985                llvm::LLVMSetNUW(trunc, TRUE);
986            }
987        }
988        trunc
989    }
990
991    fn unchecked_strunc(&mut self, val: Value<'ll>, dest_ty: Type<'ll>) -> Value<'ll> {
992        if true {
    {
        match (&self.val_ty(val), &dest_ty) {
            (left_val, right_val) => {
                if *left_val == *right_val {
                    let kind = ::core::panicking::AssertKind::Ne;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_ne!(self.val_ty(val), dest_ty);
993
994        let trunc = self.trunc(val, dest_ty);
995        unsafe {
996            if llvm::LLVMIsAInstruction(trunc).is_some() {
997                llvm::LLVMSetNSW(trunc, TRUE);
998            }
999        }
1000        trunc
1001    }
1002
1003    fn sext(&mut self, val: Value<'ll>, dest_ty: Type<'ll>) -> Value<'ll> {
1004        unsafe { llvm::LLVMBuildSExt(self.llbuilder(), val, dest_ty, UNNAMED) }
1005    }
1006
1007    fn fptoui_sat(&mut self, val: Value<'ll>, dest_ty: Type<'ll>) -> Value<'ll> {
1008        self.call_intrinsic("llvm.fptoui.sat", &[dest_ty, self.val_ty(val)], &[val])
1009    }
1010
1011    fn fptosi_sat(&mut self, val: Value<'ll>, dest_ty: Type<'ll>) -> Value<'ll> {
1012        self.call_intrinsic("llvm.fptosi.sat", &[dest_ty, self.val_ty(val)], &[val])
1013    }
1014
1015    fn fptoui(&mut self, val: Value<'ll>, dest_ty: Type<'ll>) -> Value<'ll> {
1016        // On WebAssembly the `fptoui` and `fptosi` instructions currently have
1017        // poor codegen. The reason for this is that the corresponding wasm
1018        // instructions, `i32.trunc_f32_s` for example, will trap when the float
1019        // is out-of-bounds, infinity, or nan. This means that LLVM
1020        // automatically inserts control flow around `fptoui` and `fptosi`
1021        // because the LLVM instruction `fptoui` is defined as producing a
1022        // poison value, not having UB on out-of-bounds values.
1023        //
1024        // This method, however, is only used with non-saturating casts that
1025        // have UB on out-of-bounds values. This means that it's ok if we use
1026        // the raw wasm instruction since out-of-bounds values can do whatever
1027        // we like. To ensure that LLVM picks the right instruction we choose
1028        // the raw wasm intrinsic functions which avoid LLVM inserting all the
1029        // other control flow automatically.
1030        if self.sess().target.is_like_wasm {
1031            let src_ty = self.cx.val_ty(val);
1032            if let Some(float_type) = self.cx.float_type(src_ty) {
1033                let int_width = self.cx.int_width(dest_ty).expect("dest was not an integer");
1034                if #[allow(non_exhaustive_omitted_patterns)] match (int_width, float_type) {
    (32 | 64, Float::F32 | Float::F64) => true,
    _ => false,
}matches!((int_width, float_type), (32 | 64, Float::F32 | Float::F64)) {
1035                    return self.call_intrinsic(
1036                        "llvm.wasm.trunc.unsigned",
1037                        &[dest_ty, src_ty],
1038                        &[val],
1039                    );
1040                }
1041            }
1042        }
1043        unsafe { llvm::LLVMBuildFPToUI(self.llbuilder(), val, dest_ty, UNNAMED) }
1044    }
1045
1046    fn fptosi(&mut self, val: Value<'ll>, dest_ty: Type<'ll>) -> Value<'ll> {
1047        // see `fptoui` above for why wasm is different here
1048        if self.sess().target.is_like_wasm {
1049            let src_ty = self.cx.val_ty(val);
1050            if let Some(float_type) = self.cx.float_type(src_ty) {
1051                let int_width = self.cx.int_width(dest_ty).expect("dest ty was not an integer");
1052                if #[allow(non_exhaustive_omitted_patterns)] match (int_width, float_type) {
    (32 | 64, Float::F32 | Float::F64) => true,
    _ => false,
}matches!((int_width, float_type), (32 | 64, Float::F32 | Float::F64)) {
1053                    return self.call_intrinsic(
1054                        "llvm.wasm.trunc.signed",
1055                        &[dest_ty, src_ty],
1056                        &[val],
1057                    );
1058                }
1059            }
1060        }
1061        unsafe { llvm::LLVMBuildFPToSI(self.llbuilder(), val, dest_ty, UNNAMED) }
1062    }
1063
1064    fn uitofp(&mut self, val: Value<'ll>, dest_ty: Type<'ll>) -> Value<'ll> {
1065        unsafe { llvm::LLVMBuildUIToFP(self.llbuilder(), val, dest_ty, UNNAMED) }
1066    }
1067
1068    fn sitofp(&mut self, val: Value<'ll>, dest_ty: Type<'ll>) -> Value<'ll> {
1069        unsafe { llvm::LLVMBuildSIToFP(self.llbuilder(), val, dest_ty, UNNAMED) }
1070    }
1071
1072    fn fptrunc(&mut self, val: Value<'ll>, dest_ty: Type<'ll>) -> Value<'ll> {
1073        unsafe { llvm::LLVMBuildFPTrunc(self.llbuilder(), val, dest_ty, UNNAMED) }
1074    }
1075
1076    fn fpext(&mut self, val: Value<'ll>, dest_ty: Type<'ll>) -> Value<'ll> {
1077        unsafe { llvm::LLVMBuildFPExt(self.llbuilder(), val, dest_ty, UNNAMED) }
1078    }
1079
1080    fn ptrtoint(&mut self, val: Value<'ll>, dest_ty: Type<'ll>) -> Value<'ll> {
1081        unsafe { llvm::LLVMBuildPtrToInt(self.llbuilder(), val, dest_ty, UNNAMED) }
1082    }
1083
1084    fn inttoptr(&mut self, val: Value<'ll>, dest_ty: Type<'ll>) -> Value<'ll> {
1085        unsafe { llvm::LLVMBuildIntToPtr(self.llbuilder(), val, dest_ty, UNNAMED) }
1086    }
1087
1088    fn bitcast(&mut self, val: Value<'ll>, dest_ty: Type<'ll>) -> Value<'ll> {
1089        unsafe { llvm::LLVMBuildBitCast(self.llbuilder(), val, dest_ty, UNNAMED) }
1090    }
1091
1092    fn intcast(&mut self, val: Value<'ll>, dest_ty: Type<'ll>, is_signed: bool) -> Value<'ll> {
1093        unsafe {
1094            llvm::LLVMBuildIntCast2(
1095                self.llbuilder(),
1096                val,
1097                dest_ty,
1098                is_signed.to_llvm_bool(),
1099                UNNAMED,
1100            )
1101        }
1102    }
1103
1104    fn pointercast(&mut self, val: Value<'ll>, dest_ty: Type<'ll>) -> Value<'ll> {
1105        unsafe { llvm::LLVMBuildPointerCast(self.llbuilder(), val, dest_ty, UNNAMED) }
1106    }
1107
1108    /* Comparisons */
1109    fn icmp(&mut self, op: IntPredicate, lhs: Value<'ll>, rhs: Value<'ll>) -> Value<'ll> {
1110        let op = llvm::IntPredicate::from_generic(op);
1111        unsafe { llvm::LLVMBuildICmp(self.llbuilder(), op as c_uint, lhs, rhs, UNNAMED) }
1112    }
1113
1114    fn fcmp(&mut self, op: RealPredicate, lhs: Value<'ll>, rhs: Value<'ll>) -> Value<'ll> {
1115        let op = llvm::RealPredicate::from_generic(op);
1116        unsafe { llvm::LLVMBuildFCmp(self.llbuilder(), op as c_uint, lhs, rhs, UNNAMED) }
1117    }
1118
1119    fn three_way_compare(
1120        &mut self,
1121        ty: Ty<'tcx>,
1122        lhs: Self::Value,
1123        rhs: Self::Value,
1124    ) -> Self::Value {
1125        let size = ty.primitive_size(self.tcx);
1126        let name = if ty.is_signed() { "llvm.scmp" } else { "llvm.ucmp" };
1127
1128        self.call_intrinsic(name, &[self.type_i8(), self.type_ix(size.bits())], &[lhs, rhs])
1129    }
1130
1131    /* Miscellaneous instructions */
1132    fn memcpy(
1133        &mut self,
1134        dst: Value<'ll>,
1135        dst_align: Align,
1136        src: Value<'ll>,
1137        src_align: Align,
1138        size: Value<'ll>,
1139        flags: MemFlags,
1140        tt: Option<FncTree>,
1141    ) {
1142        if !!flags.contains(MemFlags::NONTEMPORAL) {
    {
        ::core::panicking::panic_fmt(format_args!("non-temporal memcpy not supported"));
    }
};assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memcpy not supported");
1143        let size = self.intcast(size, self.type_isize(), false);
1144        let is_volatile = flags.contains(MemFlags::VOLATILE);
1145        let memcpy = unsafe {
1146            llvm::LLVMRustBuildMemCpy(
1147                self.llbuilder(),
1148                dst,
1149                dst_align.bytes() as c_uint,
1150                src,
1151                src_align.bytes() as c_uint,
1152                size,
1153                is_volatile,
1154            )
1155        };
1156
1157        // TypeTree metadata for memcpy is especially important: when Enzyme encounters
1158        // a memcpy during autodiff, it needs to know the structure of the data being
1159        // copied to properly track derivatives. For example, copying an array of floats
1160        // vs. copying a struct with mixed types requires different derivative handling.
1161        // The TypeTree tells Enzyme exactly what memory layout to expect.
1162        if let Some(tt) = tt {
1163            crate::typetree::add_tt(self, memcpy, tt);
1164        }
1165    }
1166
1167    fn memmove(
1168        &mut self,
1169        dst: Value<'ll>,
1170        dst_align: Align,
1171        src: Value<'ll>,
1172        src_align: Align,
1173        size: Value<'ll>,
1174        flags: MemFlags,
1175    ) {
1176        if !!flags.contains(MemFlags::NONTEMPORAL) {
    {
        ::core::panicking::panic_fmt(format_args!("non-temporal memmove not supported"));
    }
};assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memmove not supported");
1177        let size = self.intcast(size, self.type_isize(), false);
1178        let is_volatile = flags.contains(MemFlags::VOLATILE);
1179        unsafe {
1180            llvm::LLVMRustBuildMemMove(
1181                self.llbuilder(),
1182                dst,
1183                dst_align.bytes() as c_uint,
1184                src,
1185                src_align.bytes() as c_uint,
1186                size,
1187                is_volatile,
1188            );
1189        }
1190    }
1191
1192    fn memset(
1193        &mut self,
1194        ptr: Value<'ll>,
1195        fill_byte: Value<'ll>,
1196        size: Value<'ll>,
1197        align: Align,
1198        flags: MemFlags,
1199    ) {
1200        if !!flags.contains(MemFlags::NONTEMPORAL) {
    {
        ::core::panicking::panic_fmt(format_args!("non-temporal memset not supported"));
    }
};assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memset not supported");
1201        let is_volatile = flags.contains(MemFlags::VOLATILE);
1202        unsafe {
1203            llvm::LLVMRustBuildMemSet(
1204                self.llbuilder(),
1205                ptr,
1206                align.bytes() as c_uint,
1207                fill_byte,
1208                size,
1209                is_volatile,
1210            );
1211        }
1212    }
1213
1214    fn vscale(&mut self, ty: Type<'ll>) -> Value<'ll> {
1215        unsafe { llvm::LLVMRustBuildVScale(self.llbuilder(), ty) }
1216    }
1217
1218    fn select(
1219        &mut self,
1220        cond: Value<'ll>,
1221        then_val: Value<'ll>,
1222        else_val: Value<'ll>,
1223    ) -> Value<'ll> {
1224        unsafe { llvm::LLVMBuildSelect(self.llbuilder(), cond, then_val, else_val, UNNAMED) }
1225    }
1226
1227    fn va_arg(&mut self, list: Value<'ll>, ty: Type<'ll>) -> Value<'ll> {
1228        unsafe { llvm::LLVMBuildVAArg(self.llbuilder(), list, ty, UNNAMED) }
1229    }
1230
1231    fn extract_element(&mut self, vec: Value<'ll>, idx: Value<'ll>) -> Value<'ll> {
1232        unsafe { llvm::LLVMBuildExtractElement(self.llbuilder(), vec, idx, UNNAMED) }
1233    }
1234
1235    fn vector_splat(&mut self, num_elts: u64, elt: Value<'ll>) -> Value<'ll> {
1236        unsafe {
1237            let elt_ty = self.cx.val_ty(elt);
1238            let undef = llvm::LLVMGetUndef(self.type_vector(elt_ty, num_elts));
1239            let vec = self.insert_element(undef, elt, self.cx.const_i32(0));
1240            let vec_i32_ty = self.type_vector(self.type_i32(), num_elts);
1241            self.shuffle_vector(vec, undef, self.const_null(vec_i32_ty))
1242        }
1243    }
1244
1245    fn extract_value(&mut self, agg_val: Value<'ll>, idx: u64) -> Value<'ll> {
1246        {
    match (&(idx as c_uint as u64), &idx) {
        (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!(idx as c_uint as u64, idx);
1247        unsafe { llvm::LLVMBuildExtractValue(self.llbuilder(), agg_val, idx as c_uint, UNNAMED) }
1248    }
1249
1250    fn insert_value(&mut self, agg_val: Value<'ll>, elt: Value<'ll>, idx: u64) -> Value<'ll> {
1251        {
    match (&(idx as c_uint as u64), &idx) {
        (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!(idx as c_uint as u64, idx);
1252        unsafe {
1253            llvm::LLVMBuildInsertValue(self.llbuilder(), agg_val, elt, idx as c_uint, UNNAMED)
1254        }
1255    }
1256
1257    fn set_personality_fn(&mut self, personality: Value<'ll>) {
1258        unsafe {
1259            llvm::LLVMSetPersonalityFn(self.llfn(), personality);
1260        }
1261    }
1262
1263    fn cleanup_landing_pad(&mut self, pers_fn: Value<'ll>) -> (Value<'ll>, Value<'ll>) {
1264        let ty = self.type_struct(&[self.type_ptr(), self.type_i32()]);
1265        let landing_pad = self.landing_pad(ty, pers_fn, 0);
1266        unsafe {
1267            llvm::LLVMSetCleanup(landing_pad, llvm::TRUE);
1268        }
1269        (self.extract_value(landing_pad, 0), self.extract_value(landing_pad, 1))
1270    }
1271
1272    fn filter_landing_pad(&mut self, pers_fn: Value<'ll>) {
1273        let ty = self.type_struct(&[self.type_ptr(), self.type_i32()]);
1274        let landing_pad = self.landing_pad(ty, pers_fn, 1);
1275        self.add_clause(landing_pad, self.const_array(self.type_ptr(), &[]));
1276    }
1277
1278    fn resume(&mut self, exn0: Value<'ll>, exn1: Value<'ll>) {
1279        let ty = self.type_struct(&[self.type_ptr(), self.type_i32()]);
1280        let mut exn = self.const_poison(ty);
1281        exn = self.insert_value(exn, exn0, 0);
1282        exn = self.insert_value(exn, exn1, 1);
1283        unsafe {
1284            llvm::LLVMBuildResume(self.llbuilder(), exn);
1285        }
1286    }
1287
1288    fn cleanup_pad(&mut self, parent: Option<Value<'ll>>, args: &[Value<'ll>]) -> Funclet<'ll> {
1289        let ret = unsafe {
1290            llvm::LLVMBuildCleanupPad(
1291                self.llbuilder(),
1292                parent,
1293                args.as_ptr(),
1294                args.len() as c_uint,
1295                c"cleanuppad".as_ptr(),
1296            )
1297        };
1298        Funclet::new(ret.expect("LLVM does not have support for cleanuppad"))
1299    }
1300
1301    fn cleanup_ret(&mut self, funclet: &Funclet<'ll>, unwind: Option<&'ll BasicBlock>) {
1302        unsafe {
1303            llvm::LLVMBuildCleanupRet(self.llbuilder(), funclet.cleanuppad(), unwind)
1304                .expect("LLVM does not have support for cleanupret");
1305        }
1306    }
1307
1308    fn catch_pad(&mut self, parent: Value<'ll>, args: &[Value<'ll>]) -> Funclet<'ll> {
1309        let ret = unsafe {
1310            llvm::LLVMBuildCatchPad(
1311                self.llbuilder(),
1312                parent,
1313                args.as_ptr(),
1314                args.len() as c_uint,
1315                c"catchpad".as_ptr(),
1316            )
1317        };
1318        Funclet::new(ret.expect("LLVM does not have support for catchpad"))
1319    }
1320
1321    fn catch_switch(
1322        &mut self,
1323        parent: Option<Value<'ll>>,
1324        unwind: Option<&'ll BasicBlock>,
1325        handlers: &[&'ll BasicBlock],
1326    ) -> Value<'ll> {
1327        let ret = unsafe {
1328            llvm::LLVMBuildCatchSwitch(
1329                self.llbuilder(),
1330                parent,
1331                unwind,
1332                handlers.len() as c_uint,
1333                c"catchswitch".as_ptr(),
1334            )
1335        };
1336        let ret = ret.expect("LLVM does not have support for catchswitch");
1337        for handler in handlers {
1338            unsafe {
1339                llvm::LLVMAddHandler(ret, handler);
1340            }
1341        }
1342        ret
1343    }
1344
1345    fn get_funclet_cleanuppad(&self, funclet: &Funclet<'ll>) -> Value<'ll> {
1346        funclet.cleanuppad()
1347    }
1348
1349    // Atomic Operations
1350    fn atomic_cmpxchg(
1351        &mut self,
1352        dst: Value<'ll>,
1353        cmp: Value<'ll>,
1354        src: Value<'ll>,
1355        order: rustc_middle::ty::AtomicOrdering,
1356        failure_order: rustc_middle::ty::AtomicOrdering,
1357        weak: bool,
1358    ) -> (Value<'ll>, Value<'ll>) {
1359        unsafe {
1360            let value = llvm::LLVMBuildAtomicCmpXchg(
1361                self.llbuilder(),
1362                dst,
1363                cmp,
1364                src,
1365                AtomicOrdering::from_generic(order),
1366                AtomicOrdering::from_generic(failure_order),
1367                llvm::FALSE, // SingleThreaded
1368            );
1369            llvm::LLVMSetWeak(value, weak.to_llvm_bool());
1370            let val = self.extract_value(value, 0);
1371            let success = self.extract_value(value, 1);
1372            (val, success)
1373        }
1374    }
1375
1376    fn atomic_rmw(
1377        &mut self,
1378        op: rustc_codegen_ssa::common::AtomicRmwBinOp,
1379        dst: Value<'ll>,
1380        src: Value<'ll>,
1381        order: rustc_middle::ty::AtomicOrdering,
1382        ret_ptr: bool,
1383    ) -> Value<'ll> {
1384        // FIXME: If `ret_ptr` is true and `src` is not a pointer, we *should* tell LLVM that the
1385        // LHS is a pointer and the operation should be provenance-preserving, but LLVM does not
1386        // currently support that (https://github.com/llvm/llvm-project/issues/120837).
1387        let mut res = unsafe {
1388            llvm::LLVMBuildAtomicRMW(
1389                self.llbuilder(),
1390                AtomicRmwBinOp::from_generic(op),
1391                dst,
1392                src,
1393                AtomicOrdering::from_generic(order),
1394                llvm::FALSE, // SingleThreaded
1395            )
1396        };
1397        if ret_ptr && self.val_ty(res) != self.type_ptr() {
1398            res = self.inttoptr(res, self.type_ptr());
1399        }
1400        res
1401    }
1402
1403    fn atomic_fence(
1404        &mut self,
1405        order: rustc_middle::ty::AtomicOrdering,
1406        scope: SynchronizationScope,
1407    ) {
1408        let single_threaded = match scope {
1409            SynchronizationScope::SingleThread => true,
1410            SynchronizationScope::CrossThread => false,
1411        };
1412        unsafe {
1413            llvm::LLVMBuildFence(
1414                self.llbuilder(),
1415                AtomicOrdering::from_generic(order),
1416                single_threaded.to_llvm_bool(),
1417                UNNAMED,
1418            );
1419        }
1420    }
1421
1422    fn set_invariant_load(&mut self, load: Value<'ll>) {
1423        self.set_metadata_node(load, llvm::MD_invariant_load, &[]);
1424    }
1425
1426    fn lifetime_start(&mut self, ptr: Value<'ll>, size: Size) {
1427        self.call_lifetime_intrinsic("llvm.lifetime.start", ptr, size);
1428    }
1429
1430    fn lifetime_end(&mut self, ptr: Value<'ll>, size: Size) {
1431        self.call_lifetime_intrinsic("llvm.lifetime.end", ptr, size);
1432    }
1433
1434    fn call(
1435        &mut self,
1436        llty: Type<'ll>,
1437        caller_attrs: Option<&CodegenFnAttrs>,
1438        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1439        llfn: Value<'ll>,
1440        return_slot: ReturnSlot<Value<'ll>>,
1441        args: &[Value<'ll>],
1442        funclet: Option<&Funclet<'ll>>,
1443        callee_instance: Option<Instance<'tcx>>,
1444    ) -> Value<'ll> {
1445        // If this function returns indirectly (`PassMode::Indirect`),
1446        // the `return_slot` should be the first argument.
1447        let args = match return_slot {
1448            ReturnSlot::Direct => args.to_vec(),
1449            ReturnSlot::Indirect(sret_ptr) => {
1450                let mut args = args.to_vec();
1451                args.insert(0, sret_ptr);
1452                args
1453            }
1454        };
1455        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/builder.rs:1455",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(1455u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                        ::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 {0:?} with args ({1:?})",
                                                    llfn, args) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("call {:?} with args ({:?})", llfn, args);
1456        let args = self.check_call("call", llty, llfn, &args);
1457        let funclet_bundle = funclet.map(|funclet| funclet.bundle());
1458        let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
1459        if let Some(funclet_bundle) = funclet_bundle {
1460            bundles.push(funclet_bundle);
1461        }
1462
1463        // Emit CFI pointer type membership test
1464        self.cfi_type_test(caller_attrs, fn_abi, callee_instance, llfn);
1465
1466        // Emit KCFI operand bundle
1467        let kcfi_bundle = self.kcfi_operand_bundle(caller_attrs, fn_abi, callee_instance, llfn);
1468        if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
1469            bundles.push(kcfi_bundle);
1470        }
1471
1472        let pauth = self.ptrauth_operand_bundle(llfn, fn_abi);
1473        if let Some(p) = pauth.as_ref().map(|b| b.as_ref()) {
1474            bundles.push(p);
1475        }
1476
1477        let call = unsafe {
1478            llvm::LLVMBuildCallWithOperandBundles(
1479                self.llbuilder(),
1480                llty,
1481                llfn,
1482                args.as_ptr(),
1483                args.len() as c_uint,
1484                bundles.as_ptr(),
1485                bundles.len() as c_uint,
1486                c"".as_ptr(),
1487            )
1488        };
1489
1490        if let Some(fn_abi) = fn_abi {
1491            fn_abi.apply_attrs_callsite(self, call);
1492        }
1493        call
1494    }
1495
1496    fn tail_call(
1497        &mut self,
1498        llty: Self::Type,
1499        caller_attrs: Option<&CodegenFnAttrs>,
1500        fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
1501        llfn: Self::Value,
1502        return_slot: ReturnSlot<Self::Value>,
1503        args: &[Self::Value],
1504        funclet: Option<&Self::Funclet>,
1505        callee_instance: Option<Instance<'tcx>>,
1506    ) {
1507        let call = self.call(
1508            llty,
1509            caller_attrs,
1510            Some(fn_abi),
1511            llfn,
1512            return_slot,
1513            args,
1514            funclet,
1515            callee_instance,
1516        );
1517        llvm::LLVMSetTailCallKind(call, llvm::TailCallKind::MustTail);
1518
1519        match &fn_abi.ret.mode {
1520            PassMode::Ignore | PassMode::Indirect { .. } => self.ret_void(),
1521            PassMode::Direct(_) | PassMode::Pair { .. } | PassMode::Cast { .. } => self.ret(call),
1522            PassMode::IndirectUnsized { .. } => ::rustc_span::macros::bug_impl(None,
    format_args!("unsized returns are not supported"), Location::caller())bug!("unsized returns are not supported"),
1523        }
1524    }
1525
1526    fn zext(&mut self, val: Value<'ll>, dest_ty: Type<'ll>) -> Value<'ll> {
1527        unsafe { llvm::LLVMBuildZExt(self.llbuilder(), val, dest_ty, UNNAMED) }
1528    }
1529
1530    fn apply_attrs_to_cleanup_callsite(&mut self, llret: Value<'ll>) {
1531        // Cleanup is always the cold path.
1532        let cold_inline = llvm::AttributeKind::Cold.create_attr(self.llcx);
1533        attributes::apply_to_callsite(llret, llvm::AttributePlace::Function, &[cold_inline]);
1534    }
1535}
1536
1537impl<'ll> StaticBuilderMethods for Builder<'_, 'll, '_> {
1538    fn get_static(&mut self, def_id: DefId) -> Value<'ll> {
1539        // Forward to the `get_static` method of `CodegenCx`
1540        let global = self.cx().get_static(def_id);
1541        if self.cx().tcx.is_thread_local_static(def_id) {
1542            let pointer =
1543                self.call_intrinsic("llvm.threadlocal.address", &[self.val_ty(global)], &[global]);
1544            // Cast to default address space if globals are in a different addrspace
1545            self.pointercast(pointer, self.type_ptr())
1546        } else {
1547            // Cast to default address space if globals are in a different addrspace
1548            self.cx().const_pointercast(global, self.type_ptr())
1549        }
1550    }
1551}
1552
1553impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1554    pub(crate) fn llfn(&self) -> Value<'ll> {
1555        unsafe { llvm::LLVMGetBasicBlockParent(self.llbb()) }
1556    }
1557
1558    fn generate_ubsan_cfi_diag_data(
1559        &mut self,
1560        span: rustc_span::Span,
1561        expected_ty: String,
1562        check_kind: u8,
1563    ) -> Value<'ll> {
1564        let cx = self.cx();
1565        let tcx = cx.tcx;
1566
1567        let loc = tcx.sess.source_map().lookup_char_pos(span.lo());
1568
1569        let filename_str = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}\0",
                loc.file.name.prefer_local_unconditionally()))
    })format!("{}\0", loc.file.name.prefer_local_unconditionally());
1570        let filename_val = cx.const_bytes(filename_str.as_bytes());
1571        let filename_ptr = cx.static_addr_of_impl(filename_val, Align::ONE, None);
1572
1573        // SourceLocation UBSan struct: { const char *filename, uint32_t line, uint32_t column }
1574        let source_location = cx.const_struct(
1575            &[
1576                filename_ptr,
1577                cx.const_u32(loc.line as u32),
1578                // UBSan columns are 1-based
1579                cx.const_u32(loc.col.0 as u32 + 1),
1580            ],
1581            false, // packed = false
1582        );
1583
1584        let ty_name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}\0", expected_ty))
    })format!("{}\0", expected_ty);
1585        let ty_name_val = cx.const_bytes(ty_name.as_bytes());
1586
1587        // TypeDescriptor UBSan struct: { uint16_t TypeKind, uint16_t TypeInfo, const char *TypeName }
1588        let type_descriptor =
1589            cx.const_struct(&[cx.const_i16(0xffffu16 as i16), cx.const_i16(0), ty_name_val], false);
1590
1591        let type_descriptor_ptr =
1592            cx.static_addr_of_impl(type_descriptor, Align::from_bytes(2).unwrap(), None);
1593
1594        // CFICheckFailData UBSan struct: { uint8_t CheckKind, SourceLocation Loc, TypeDescriptor *Type }
1595        let cfi_check_fail_data = cx
1596            .const_struct(&[cx.const_u8(check_kind), source_location, type_descriptor_ptr], false);
1597        let align = tcx.data_layout.aggregate_align;
1598
1599        // Returns the final opaque pointer to the struct to be passed to __ubsan_handle_cfi_check_fail
1600        cx.static_addr_of_mut(cfi_check_fail_data, align, Some("__ubsan_cfi_check_fail_data"))
1601    }
1602}
1603
1604impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1605    fn position_at_start(&mut self, llbb: &'ll BasicBlock) {
1606        unsafe {
1607            llvm::LLVMRustPositionBuilderAtStart(self.llbuilder(), llbb);
1608        }
1609    }
1610}
1611impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1612    fn align_metadata(&mut self, load: Value<'ll>, align: Align) {
1613        let md = [llvm::LLVMValueAsMetadata(self.cx.const_u64(align.bytes()))];
1614        self.set_metadata_node(load, llvm::MD_align, &md);
1615    }
1616
1617    fn noundef_metadata(&mut self, load: Value<'ll>) {
1618        self.set_metadata_node(load, llvm::MD_noundef, &[]);
1619    }
1620
1621    pub(crate) fn set_unpredictable(&mut self, inst: Value<'ll>) {
1622        self.set_metadata_node(inst, llvm::MD_unpredictable, &[]);
1623    }
1624
1625    fn write_operand_repeatedly_optimized(
1626        &mut self,
1627        cg_elem: OperandRef<'tcx, Value<'ll>>,
1628        count: u64,
1629        dest: PlaceRef<'tcx, Value<'ll>>,
1630    ) {
1631        let zero = self.const_usize(0);
1632        let count = self.const_usize(count);
1633
1634        let header_bb = self.append_sibling_block("repeat_loop_header");
1635        let body_bb = self.append_sibling_block("repeat_loop_body");
1636        let next_bb = self.append_sibling_block("repeat_loop_next");
1637
1638        self.br(header_bb);
1639
1640        let mut header_bx = Self::build(self.cx, header_bb);
1641        let i = header_bx.phi(self.val_ty(zero), &[zero], &[self.llbb()]);
1642
1643        let keep_going = header_bx.icmp(IntPredicate::IntULT, i, count);
1644        header_bx.cond_br(keep_going, body_bb, next_bb);
1645
1646        let mut body_bx = Self::build(self.cx, body_bb);
1647        let dest_elem = dest.project_index(&mut body_bx, i);
1648        cg_elem.val.store(&mut body_bx, dest_elem);
1649
1650        let next = body_bx.unchecked_uadd(i, self.const_usize(1));
1651        body_bx.br(header_bb);
1652        header_bx.add_incoming_to_phi(i, next, body_bb);
1653
1654        *self = Self::build(self.cx, next_bb);
1655    }
1656
1657    fn write_operand_repeatedly_unoptimized(
1658        &mut self,
1659        cg_elem: OperandRef<'tcx, Value<'ll>>,
1660        count: u64,
1661        dest: PlaceRef<'tcx, Value<'ll>>,
1662    ) {
1663        let zero = self.const_usize(0);
1664        let count = self.const_usize(count);
1665        let start = dest.project_index(self, zero).val.llval;
1666        let end = dest.project_index(self, count).val.llval;
1667
1668        let header_bb = self.append_sibling_block("repeat_loop_header");
1669        let body_bb = self.append_sibling_block("repeat_loop_body");
1670        let next_bb = self.append_sibling_block("repeat_loop_next");
1671
1672        self.br(header_bb);
1673
1674        let mut header_bx = Self::build(self.cx, header_bb);
1675        let current = header_bx.phi(self.val_ty(start), &[start], &[self.llbb()]);
1676
1677        let keep_going = header_bx.icmp(IntPredicate::IntNE, current, end);
1678        header_bx.cond_br(keep_going, body_bb, next_bb);
1679
1680        let mut body_bx = Self::build(self.cx, body_bb);
1681        let align = dest.val.align.restrict_for_offset(dest.layout.field(self.cx(), 0).size);
1682        cg_elem
1683            .val
1684            .store(&mut body_bx, PlaceRef::new_sized_aligned(current, cg_elem.layout, align));
1685
1686        let next = body_bx.inbounds_ptradd(current, self.const_usize(cg_elem.layout.size.bytes()));
1687        body_bx.br(header_bb);
1688        header_bx.add_incoming_to_phi(current, next, body_bb);
1689
1690        *self = Self::build(self.cx, next_bb);
1691    }
1692
1693    pub(crate) fn minimum_number_nsz(&mut self, lhs: Value<'ll>, rhs: Value<'ll>) -> Value<'ll> {
1694        let call = self.call_intrinsic("llvm.minimumnum", &[self.val_ty(lhs)], &[lhs, rhs]);
1695        unsafe { llvm::LLVMRustSetNoSignedZeros(call) };
1696        call
1697    }
1698
1699    pub(crate) fn maximum_number_nsz(&mut self, lhs: Value<'ll>, rhs: Value<'ll>) -> Value<'ll> {
1700        let call = self.call_intrinsic("llvm.maximumnum", &[self.val_ty(lhs)], &[lhs, rhs]);
1701        unsafe { llvm::LLVMRustSetNoSignedZeros(call) };
1702        call
1703    }
1704
1705    pub(crate) fn insert_element(
1706        &mut self,
1707        vec: Value<'ll>,
1708        elt: Value<'ll>,
1709        idx: Value<'ll>,
1710    ) -> Value<'ll> {
1711        unsafe { llvm::LLVMBuildInsertElement(self.llbuilder(), vec, elt, idx, UNNAMED) }
1712    }
1713
1714    pub(crate) fn shuffle_vector(
1715        &mut self,
1716        v1: Value<'ll>,
1717        v2: Value<'ll>,
1718        mask: Value<'ll>,
1719    ) -> Value<'ll> {
1720        unsafe { llvm::LLVMBuildShuffleVector(self.llbuilder(), v1, v2, mask, UNNAMED) }
1721    }
1722
1723    pub(crate) fn vector_reduce_fadd(&mut self, acc: Value<'ll>, src: Value<'ll>) -> Value<'ll> {
1724        self.call_intrinsic("llvm.vector.reduce.fadd", &[self.val_ty(src)], &[acc, src])
1725    }
1726    pub(crate) fn vector_reduce_fmul(&mut self, acc: Value<'ll>, src: Value<'ll>) -> Value<'ll> {
1727        self.call_intrinsic("llvm.vector.reduce.fmul", &[self.val_ty(src)], &[acc, src])
1728    }
1729    pub(crate) fn vector_reduce_fadd_reassoc(
1730        &mut self,
1731        acc: Value<'ll>,
1732        src: Value<'ll>,
1733    ) -> Value<'ll> {
1734        unsafe {
1735            let instr =
1736                self.call_intrinsic("llvm.vector.reduce.fadd", &[self.val_ty(src)], &[acc, src]);
1737            llvm::LLVMRustSetAllowReassoc(instr);
1738            instr
1739        }
1740    }
1741    pub(crate) fn vector_reduce_fmul_reassoc(
1742        &mut self,
1743        acc: Value<'ll>,
1744        src: Value<'ll>,
1745    ) -> Value<'ll> {
1746        unsafe {
1747            let instr =
1748                self.call_intrinsic("llvm.vector.reduce.fmul", &[self.val_ty(src)], &[acc, src]);
1749            llvm::LLVMRustSetAllowReassoc(instr);
1750            instr
1751        }
1752    }
1753    pub(crate) fn vector_reduce_add(&mut self, src: Value<'ll>) -> Value<'ll> {
1754        self.call_intrinsic("llvm.vector.reduce.add", &[self.val_ty(src)], &[src])
1755    }
1756    pub(crate) fn vector_reduce_mul(&mut self, src: Value<'ll>) -> Value<'ll> {
1757        self.call_intrinsic("llvm.vector.reduce.mul", &[self.val_ty(src)], &[src])
1758    }
1759    pub(crate) fn vector_reduce_and(&mut self, src: Value<'ll>) -> Value<'ll> {
1760        self.call_intrinsic("llvm.vector.reduce.and", &[self.val_ty(src)], &[src])
1761    }
1762    pub(crate) fn vector_reduce_or(&mut self, src: Value<'ll>) -> Value<'ll> {
1763        self.call_intrinsic("llvm.vector.reduce.or", &[self.val_ty(src)], &[src])
1764    }
1765    pub(crate) fn vector_reduce_xor(&mut self, src: Value<'ll>) -> Value<'ll> {
1766        self.call_intrinsic("llvm.vector.reduce.xor", &[self.val_ty(src)], &[src])
1767    }
1768    pub(crate) fn vector_reduce_min(&mut self, src: Value<'ll>, is_signed: bool) -> Value<'ll> {
1769        self.call_intrinsic(
1770            if is_signed { "llvm.vector.reduce.smin" } else { "llvm.vector.reduce.umin" },
1771            &[self.val_ty(src)],
1772            &[src],
1773        )
1774    }
1775    pub(crate) fn vector_reduce_max(&mut self, src: Value<'ll>, is_signed: bool) -> Value<'ll> {
1776        self.call_intrinsic(
1777            if is_signed { "llvm.vector.reduce.smax" } else { "llvm.vector.reduce.umax" },
1778            &[self.val_ty(src)],
1779            &[src],
1780        )
1781    }
1782}
1783impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1784    pub(crate) fn add_clause(&mut self, landing_pad: Value<'ll>, clause: Value<'ll>) {
1785        unsafe {
1786            llvm::LLVMAddClause(landing_pad, clause);
1787        }
1788    }
1789
1790    pub(crate) fn catch_ret(
1791        &mut self,
1792        funclet: &Funclet<'ll>,
1793        unwind: &'ll BasicBlock,
1794    ) -> Value<'ll> {
1795        let ret =
1796            unsafe { llvm::LLVMBuildCatchRet(self.llbuilder(), funclet.cleanuppad(), unwind) };
1797        ret.expect("LLVM does not have support for catchret")
1798    }
1799
1800    pub(crate) fn check_call<'b>(
1801        &mut self,
1802        typ: &str,
1803        fn_ty: Type<'ll>,
1804        llfn: Value<'ll>,
1805        args: &'b [Value<'ll>],
1806    ) -> Cow<'b, [Value<'ll>]> {
1807        if !(self.cx.type_kind(fn_ty) == TypeKind::Function) {
    {
        ::core::panicking::panic_fmt(format_args!("builder::{0} not passed a function, but {1:?}",
                typ, fn_ty));
    }
};assert!(
1808            self.cx.type_kind(fn_ty) == TypeKind::Function,
1809            "builder::{typ} not passed a function, but {fn_ty:?}"
1810        );
1811
1812        let param_tys = self.cx.func_params_types(fn_ty);
1813
1814        let all_args_match = iter::zip(&param_tys, args.iter().map(|&v| self.cx.val_ty(v)))
1815            .all(|(expected_ty, actual_ty)| *expected_ty == actual_ty);
1816
1817        if all_args_match {
1818            return Cow::Borrowed(args);
1819        }
1820
1821        let casted_args: Vec<_> = iter::zip(param_tys, args)
1822            .enumerate()
1823            .map(|(i, (expected_ty, &actual_val))| {
1824                let actual_ty = self.cx.val_ty(actual_val);
1825                if expected_ty != actual_ty {
1826                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/builder.rs:1826",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(1826u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                        ::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!("type mismatch in function call of {0:?}. Expected {1:?} for param {2}, got {3:?}; injecting bitcast",
                                                    llfn, expected_ty, i, actual_ty) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
1827                        "type mismatch in function call of {:?}. \
1828                            Expected {:?} for param {}, got {:?}; injecting bitcast",
1829                        llfn, expected_ty, i, actual_ty
1830                    );
1831                    self.bitcast(actual_val, expected_ty)
1832                } else {
1833                    actual_val
1834                }
1835            })
1836            .collect();
1837
1838        Cow::Owned(casted_args)
1839    }
1840
1841    pub(crate) fn va_arg(&mut self, list: Value<'ll>, ty: Type<'ll>) -> Value<'ll> {
1842        unsafe { llvm::LLVMBuildVAArg(self.llbuilder(), list, ty, UNNAMED) }
1843    }
1844}
1845
1846impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1847    pub(crate) fn call_intrinsic(
1848        &mut self,
1849        base_name: impl Into<Cow<'static, str>>,
1850        type_params: &[Type<'ll>],
1851        args: &[Value<'ll>],
1852    ) -> Value<'ll> {
1853        let (ty, f) = self.cx.get_intrinsic(base_name.into(), type_params);
1854        // No LLVM intrinsic returns its data indirectly (via `sret`).
1855        self.call(ty, None, None, f, ReturnSlot::Direct, args, None, None)
1856    }
1857
1858    fn call_lifetime_intrinsic(&mut self, intrinsic: &'static str, ptr: Value<'ll>, size: Size) {
1859        let size = size.bytes();
1860        if size == 0 {
1861            return;
1862        }
1863
1864        if !self.cx().sess().emit_lifetime_markers() {
1865            return;
1866        }
1867
1868        // LLVM 22 requires the lifetime intrinsic to act directly on the alloca,
1869        // there can't be an addrspacecast in between.
1870        let ptr = unsafe { llvm::LLVMRustStripPointerCasts(ptr) };
1871        self.call_intrinsic(intrinsic, &[self.val_ty(ptr)], &[ptr]);
1872    }
1873}
1874impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1875    pub(crate) fn phi(
1876        &mut self,
1877        ty: Type<'ll>,
1878        vals: &[Value<'ll>],
1879        bbs: &[&'ll BasicBlock],
1880    ) -> Value<'ll> {
1881        {
    match (&vals.len(), &bbs.len()) {
        (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!(vals.len(), bbs.len());
1882        let phi = unsafe { llvm::LLVMBuildPhi(self.llbuilder(), ty, UNNAMED) };
1883        unsafe {
1884            llvm::LLVMAddIncoming(phi, vals.as_ptr(), bbs.as_ptr(), vals.len() as c_uint);
1885            phi
1886        }
1887    }
1888
1889    fn add_incoming_to_phi(&mut self, phi: Value<'ll>, val: Value<'ll>, bb: &'ll BasicBlock) {
1890        unsafe {
1891            llvm::LLVMAddIncoming(phi, &val, &bb, 1 as c_uint);
1892        }
1893    }
1894}
1895impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1896    pub(crate) fn landing_pad(
1897        &mut self,
1898        ty: Type<'ll>,
1899        pers_fn: Value<'ll>,
1900        num_clauses: usize,
1901    ) -> Value<'ll> {
1902        // Use LLVMSetPersonalityFn to set the personality. It supports arbitrary Consts while,
1903        // LLVMBuildLandingPad requires the argument to be a Function (as of LLVM 12). The
1904        // personality lives on the parent function anyway.
1905        self.set_personality_fn(pers_fn);
1906        unsafe {
1907            llvm::LLVMBuildLandingPad(self.llbuilder(), ty, None, num_clauses as c_uint, UNNAMED)
1908        }
1909    }
1910
1911    pub(crate) fn callbr(
1912        &mut self,
1913        llty: Type<'ll>,
1914        fn_attrs: Option<&CodegenFnAttrs>,
1915        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1916        llfn: Value<'ll>,
1917        args: &[Value<'ll>],
1918        default_dest: &'ll BasicBlock,
1919        indirect_dest: &[&'ll BasicBlock],
1920        funclet: Option<&Funclet<'ll>>,
1921        instance: Option<Instance<'tcx>>,
1922    ) -> Value<'ll> {
1923        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/builder.rs:1923",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(1923u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                        ::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!("invoke {0:?} with args ({1:?})",
                                                    llfn, args) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("invoke {:?} with args ({:?})", llfn, args);
1924
1925        let args = self.check_call("callbr", llty, llfn, args);
1926        let funclet_bundle = funclet.map(|funclet| funclet.bundle());
1927        let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
1928        if let Some(funclet_bundle) = funclet_bundle {
1929            bundles.push(funclet_bundle);
1930        }
1931
1932        // Emit CFI pointer type membership test
1933        self.cfi_type_test(fn_attrs, fn_abi, instance, llfn);
1934
1935        // Emit KCFI operand bundle
1936        let kcfi_bundle = self.kcfi_operand_bundle(fn_attrs, fn_abi, instance, llfn);
1937        if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|bundle| bundle.as_ref()) {
1938            bundles.push(kcfi_bundle);
1939        }
1940
1941        let pauth = self.ptrauth_operand_bundle(llfn, fn_abi);
1942        if let Some(p) = pauth.as_ref().map(|b| b.as_ref()) {
1943            bundles.push(p);
1944        }
1945
1946        let callbr = unsafe {
1947            llvm::LLVMBuildCallBr(
1948                self.llbuilder(),
1949                llty,
1950                llfn,
1951                default_dest,
1952                indirect_dest.as_ptr(),
1953                indirect_dest.len() as c_uint,
1954                args.as_ptr(),
1955                args.len() as c_uint,
1956                bundles.as_ptr(),
1957                bundles.len() as c_uint,
1958                UNNAMED,
1959            )
1960        };
1961        if let Some(fn_abi) = fn_abi {
1962            fn_abi.apply_attrs_callsite(self, callbr);
1963        }
1964        callbr
1965    }
1966
1967    // Emits CFI pointer type membership tests.
1968    fn cfi_type_test(
1969        &mut self,
1970        fn_attrs: Option<&CodegenFnAttrs>,
1971        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1972        instance: Option<Instance<'tcx>>,
1973        llfn: Value<'ll>,
1974    ) {
1975        let is_indirect_call = unsafe { llvm::LLVMRustIsNonGVFunctionPointerTy(llfn) };
1976        if self.tcx.sess.is_sanitizer_cfi_enabled()
1977            && let Some(fn_abi) = fn_abi
1978            && is_indirect_call
1979        {
1980            if let Some(fn_attrs) = fn_attrs
1981                && fn_attrs.sanitizers.disabled.contains(SanitizerSet::CFI)
1982            {
1983                return;
1984            }
1985            if crate::llvm::HasStringAttribute(self.llfn(), "no-sanitize-cfi") {
1986                return;
1987            }
1988
1989            let mut options = cfi::TypeIdOptions::empty();
1990            if self.tcx.sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1991                options.insert(cfi::TypeIdOptions::GENERALIZE_POINTERS);
1992            }
1993            if self.tcx.sess.is_sanitizer_cfi_normalize_integers_enabled() {
1994                options.insert(cfi::TypeIdOptions::NORMALIZE_INTEGERS);
1995            }
1996
1997            if self.cx.is_sanitizer_type_ignored(c"cfi", fn_abi) {
1998                return;
1999            }
2000
2001            let typeid = if let Some(instance) = instance {
2002                cfi::typeid_for_instance(self.tcx, instance, options)
2003            } else {
2004                cfi::typeid_for_fnabi(self.tcx, fn_abi, options)
2005            };
2006            let typeid_metadata = self.cx.create_metadata(typeid.as_bytes());
2007            let dbg_loc = self.get_dbg_loc();
2008
2009            // Test whether the function pointer is associated with the type identifier using the
2010            // llvm.type.test intrinsic. The LowerTypeTests link-time optimization pass replaces
2011            // calls to this intrinsic with code to test type membership.
2012            let typeid = self.get_metadata_value(typeid_metadata);
2013            let cond = self.call_intrinsic("llvm.type.test", &[], &[llfn, typeid]);
2014            let bb_pass = self.append_sibling_block("type_test.pass");
2015            let bb_fail = self.append_sibling_block("type_test.fail");
2016            self.cond_br(cond, bb_pass, bb_fail);
2017
2018            self.switch_to_block(bb_fail);
2019            if let Some(dbg_loc) = dbg_loc {
2020                self.set_dbg_loc(dbg_loc);
2021            }
2022
2023            let is_diag = self.tcx.sess.opts.unstable_opts.sanitizer_cfi_diag.unwrap_or(false);
2024            let is_recover =
2025                self.tcx.sess.opts.unstable_opts.sanitizer_cfi_recover.unwrap_or(false);
2026            let is_minimal =
2027                self.tcx.sess.opts.unstable_opts.sanitizer_cfi_minimal_runtime.unwrap_or(false);
2028
2029            if is_diag || is_recover {
2030                let fty = if is_minimal {
2031                    self.cx.type_func(&[], self.cx.type_void())
2032                } else {
2033                    self.cx.type_func(
2034                        &[self.cx.type_ptr(), self.cx.type_isize(), self.cx.type_isize()],
2035                        self.cx.type_void(),
2036                    )
2037                };
2038                let ubsan_handler = self.declare_cfn(
2039                    match (is_minimal, is_recover) {
2040                        (true, true) => "__ubsan_handle_cfi_check_fail_minimal",
2041                        (true, false) => "__ubsan_handle_cfi_check_fail_minimal_abort",
2042                        (false, true) => "__ubsan_handle_cfi_check_fail",
2043                        (false, false) => "__ubsan_handle_cfi_check_fail_abort",
2044                    },
2045                    llvm::UnnamedAddr::Global,
2046                    fty,
2047                );
2048
2049                let mut expected_ty = String::from("fn(");
2050                {
    let _guard = NoTrimmedGuard::new();
    {
        for (i, arg) in fn_abi.args.iter().enumerate() {
            if i > 0 { expected_ty.push_str(", "); }
            use std::fmt::Write;
            (&mut expected_ty).write_fmt(format_args!("{0}",
                        arg.layout.ty)).unwrap();
        }
        expected_ty.push(')');
        if !fn_abi.ret.layout.ty.is_unit() {
            use std::fmt::Write;
            (&mut expected_ty).write_fmt(format_args!(" -> {0}",
                        fn_abi.ret.layout.ty)).unwrap();
        }
    }
};ty::print::with_no_trimmed_paths!({
2051                    for (i, arg) in fn_abi.args.iter().enumerate() {
2052                        if i > 0 {
2053                            expected_ty.push_str(", ");
2054                        }
2055                        use std::fmt::Write;
2056                        write!(&mut expected_ty, "{}", arg.layout.ty).unwrap();
2057                    }
2058                    expected_ty.push(')');
2059                    if !fn_abi.ret.layout.ty.is_unit() {
2060                        use std::fmt::Write;
2061                        write!(&mut expected_ty, " -> {}", fn_abi.ret.layout.ty).unwrap();
2062                    }
2063                });
2064
2065                // 4 for cfi-icall (indirect call)
2066                let check_kind = 4;
2067                let diag_data =
2068                    self.generate_ubsan_cfi_diag_data(self.span, expected_ty, check_kind);
2069
2070                let function_address = self.ptrtoint(llfn, self.cx.type_isize());
2071                let arguments: &[_] = if is_minimal {
2072                    &[]
2073                } else {
2074                    &[diag_data, function_address, self.const_usize(0)]
2075                };
2076                self.call(
2077                    fty,
2078                    None,
2079                    None,
2080                    ubsan_handler,
2081                    ReturnSlot::Direct,
2082                    arguments,
2083                    None,
2084                    None,
2085                );
2086                if is_recover {
2087                    self.br(bb_pass);
2088                } else {
2089                    self.unreachable();
2090                }
2091            } else {
2092                self.abort_immediate();
2093                self.unreachable();
2094            }
2095
2096            self.switch_to_block(bb_pass);
2097            if let Some(dbg_loc) = dbg_loc {
2098                self.set_dbg_loc(dbg_loc);
2099            }
2100        }
2101    }
2102
2103    // Emits KCFI operand bundles.
2104    fn kcfi_operand_bundle(
2105        &mut self,
2106        fn_attrs: Option<&CodegenFnAttrs>,
2107        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
2108        instance: Option<Instance<'tcx>>,
2109        llfn: Value<'ll>,
2110    ) -> Option<llvm::OperandBundleBox<'ll>> {
2111        let is_indirect_call = unsafe { llvm::LLVMRustIsNonGVFunctionPointerTy(llfn) };
2112        let kcfi_bundle = if self.tcx.sess.is_sanitizer_kcfi_enabled()
2113            && let Some(fn_abi) = fn_abi
2114            && is_indirect_call
2115        {
2116            if let Some(fn_attrs) = fn_attrs
2117                && fn_attrs.sanitizers.disabled.contains(SanitizerSet::KCFI)
2118            {
2119                return None;
2120            }
2121            if crate::llvm::HasStringAttribute(self.llfn(), "no-sanitize-kcfi") {
2122                return None;
2123            }
2124
2125            let mut options = kcfi::TypeIdOptions::empty();
2126            if self.tcx.sess.is_sanitizer_cfi_generalize_pointers_enabled() {
2127                options.insert(kcfi::TypeIdOptions::GENERALIZE_POINTERS);
2128            }
2129            if self.tcx.sess.is_sanitizer_cfi_normalize_integers_enabled() {
2130                options.insert(kcfi::TypeIdOptions::NORMALIZE_INTEGERS);
2131            }
2132
2133            if self.cx.is_sanitizer_type_ignored(c"kcfi", fn_abi) {
2134                return None;
2135            }
2136
2137            let kcfi_typeid = if let Some(instance) = instance {
2138                kcfi::typeid_for_instance(self.tcx, instance, options)
2139            } else {
2140                kcfi::typeid_for_fnabi(self.tcx, fn_abi, options)
2141            };
2142
2143            Some(llvm::OperandBundleBox::new("kcfi", &[self.const_u32(kcfi_typeid)]))
2144        } else {
2145            None
2146        };
2147        kcfi_bundle
2148    }
2149
2150    // Emits pauth operand bundle.
2151    fn ptrauth_operand_bundle(
2152        &mut self,
2153        llfn: Value<'ll>,
2154        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
2155    ) -> Option<llvm::OperandBundleBox<'ll>> {
2156        let schema = self.sess().pointer_authentication_functions()?;
2157
2158        // Pointer authentication support is currently limited to extern "C" calls; filter out other
2159        // ABIs.
2160        if fn_abi?.conv != CanonAbi::C {
2161            return None;
2162        }
2163        // Filter out LLVM intrinsics.
2164        if llvm::get_value_name(llfn).starts_with(b"llvm.") {
2165            return None;
2166        }
2167
2168        // FIXME(jchlanda) Operand bundles should only be attached to indirect function calls.
2169        // However, function pointer signing is currently performed in `get_fn_addr`, which causes
2170        // the logic to be applied too broadly, including to function values (not just pointers).
2171        // As a result, direct calls using signed function values must also receive operand
2172        // bundles.
2173        // Once this is resolved, we should analyze each call and skip direct calls. See the
2174        // discussion in the rust-lang issue: <https://github.com/rust-lang/rust/issues/152532>
2175        Some(llvm::OperandBundleBox::new(
2176            "ptrauth",
2177            &[
2178                self.const_u32(schema.key as u32),
2179                self.const_u64(schema.constant_discriminator as u64),
2180            ],
2181        ))
2182    }
2183
2184    /// Emits a call to `llvm.instrprof.increment`. Used by coverage instrumentation.
2185    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("instrprof_increment",
                                    "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/builder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2185u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("fn_name")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("fn_name");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("hash")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("hash");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("num_counters")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("num_counters");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("index")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("index");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_name)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&hash)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&num_counters)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&index)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.call_intrinsic("llvm.instrprof.increment", &[],
                &[fn_name, hash, num_counters, index]);
        }
    }
}#[instrument(level = "debug", skip(self))]
2186    pub(crate) fn instrprof_increment(
2187        &mut self,
2188        fn_name: Value<'ll>,
2189        hash: Value<'ll>,
2190        num_counters: Value<'ll>,
2191        index: Value<'ll>,
2192    ) {
2193        self.call_intrinsic("llvm.instrprof.increment", &[], &[fn_name, hash, num_counters, index]);
2194    }
2195}