Skip to main content

rustc_codegen_llvm/
builder.rs

1use std::borrow::{Borrow, Cow};
2use std::iter;
3use std::ops::Deref;
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, Size, WrappingRange};
11use rustc_codegen_ssa::MemFlags;
12use rustc_codegen_ssa::common::{IntPredicate, RealPredicate, SynchronizationScope, TypeKind};
13use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
14use rustc_codegen_ssa::mir::place::PlaceRef;
15use rustc_codegen_ssa::traits::*;
16use rustc_data_structures::small_c_str::SmallCStr;
17use rustc_hir::attrs::{AttributeKind, UnrollAttr};
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;
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, Value,
40};
41use crate::type_of::LayoutLlvmExt;
42
43#[must_use]
44pub(crate) struct GenericBuilder<'a, 'll, CX: Borrow<SCx<'ll>>> {
45    pub llbuilder: &'ll mut llvm::Builder<'ll>,
46    pub cx: &'a GenericCx<'ll, CX>,
47    pub span: rustc_span::Span,
48}
49
50pub(crate) type SBuilder<'a, 'll> = GenericBuilder<'a, 'll, SCx<'ll>>;
51pub(crate) type Builder<'a, 'll, 'tcx> = GenericBuilder<'a, 'll, FullCx<'ll, 'tcx>>;
52
53impl<'a, 'll, CX: Borrow<SCx<'ll>>> Drop for GenericBuilder<'a, 'll, CX> {
54    fn drop(&mut self) {
55        unsafe {
56            llvm::LLVMDisposeBuilder(&mut *(self.llbuilder as *mut _));
57        }
58    }
59}
60
61impl<'a, 'll> SBuilder<'a, 'll> {
62    pub(crate) fn call(
63        &mut self,
64        llty: &'ll Type,
65        llfn: &'ll Value,
66        args: &[&'ll Value],
67        funclet: Option<&Funclet<'ll>>,
68    ) -> &'ll Value {
69        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_codegen_llvm/src/builder.rs:69",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(69u32),
                        ::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);
70
71        let args = self.check_call("call", llty, llfn, args);
72        let funclet_bundle = funclet.map(|funclet| funclet.bundle());
73        let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
74        if let Some(funclet_bundle) = funclet_bundle {
75            bundles.push(funclet_bundle);
76        }
77
78        let call = unsafe {
79            llvm::LLVMBuildCallWithOperandBundles(
80                self.llbuilder,
81                llty,
82                llfn,
83                args.as_ptr() as *const &llvm::Value,
84                args.len() as c_uint,
85                bundles.as_ptr(),
86                bundles.len() as c_uint,
87                c"".as_ptr(),
88            )
89        };
90        call
91    }
92}
93
94impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
95    fn with_cx(scx: &'a GenericCx<'ll, CX>) -> Self {
96        // Create a fresh builder from the simple context.
97        let llbuilder = unsafe { llvm::LLVMCreateBuilderInContext(scx.deref().borrow().llcx) };
98        GenericBuilder { llbuilder, cx: scx, span: rustc_span::DUMMY_SP }
99    }
100
101    pub(crate) fn append_block(
102        cx: &'a GenericCx<'ll, CX>,
103        llfn: &'ll Value,
104        name: &str,
105    ) -> &'ll BasicBlock {
106        unsafe {
107            let name = SmallCStr::new(name);
108            llvm::LLVMAppendBasicBlockInContext(cx.llcx(), llfn, name.as_ptr())
109        }
110    }
111
112    pub(crate) fn trunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
113        unsafe { llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
114    }
115
116    pub(crate) fn bitcast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
117        unsafe { llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty, UNNAMED) }
118    }
119
120    pub(crate) fn ret_void(&mut self) {
121        llvm::LLVMBuildRetVoid(self.llbuilder);
122    }
123
124    pub(crate) fn ret(&mut self, v: &'ll Value) {
125        unsafe {
126            llvm::LLVMBuildRet(self.llbuilder, v);
127        }
128    }
129
130    pub(crate) fn build(cx: &'a GenericCx<'ll, CX>, llbb: &'ll BasicBlock) -> Self {
131        let bx = Self::with_cx(cx);
132        unsafe {
133            llvm::LLVMPositionBuilderAtEnd(bx.llbuilder, llbb);
134        }
135        bx
136    }
137
138    // The generic builder has less functionality and thus (unlike the other alloca) we can not
139    // easily jump to the beginning of the function to place our allocas there. We trust the user
140    // to manually do that. FIXME(offload): improve the genericCx and add more llvm wrappers to
141    // handle this.
142    pub(crate) fn direct_alloca(&mut self, ty: &'ll Type, align: Align, name: &str) -> &'ll Value {
143        let val = unsafe {
144            let alloca = llvm::LLVMBuildAlloca(self.llbuilder, ty, UNNAMED);
145            llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
146            // Cast to default addrspace if necessary
147            llvm::LLVMBuildPointerCast(self.llbuilder, alloca, self.cx.type_ptr(), UNNAMED)
148        };
149        if name != "" {
150            let name = std::ffi::CString::new(name).unwrap();
151            llvm::set_value_name(val, &name.as_bytes());
152        }
153        val
154    }
155
156    pub(crate) fn inbounds_gep(
157        &mut self,
158        ty: &'ll Type,
159        ptr: &'ll Value,
160        indices: &[&'ll Value],
161    ) -> &'ll Value {
162        unsafe {
163            llvm::LLVMBuildGEPWithNoWrapFlags(
164                self.llbuilder,
165                ty,
166                ptr,
167                indices.as_ptr(),
168                indices.len() as c_uint,
169                UNNAMED,
170                GEPNoWrapFlags::InBounds,
171            )
172        }
173    }
174
175    pub(crate) fn store(&mut self, val: &'ll Value, ptr: &'ll Value, align: Align) -> &'ll Value {
176        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_codegen_llvm/src/builder.rs:176",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(176u32),
                        ::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);
177        {
    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);
178        unsafe {
179            let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
180            llvm::LLVMSetAlignment(store, align.bytes() as c_uint);
181            store
182        }
183    }
184
185    pub(crate) fn load(&mut self, ty: &'ll Type, ptr: &'ll Value, align: Align) -> &'ll Value {
186        unsafe {
187            let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
188            llvm::LLVMSetAlignment(load, align.bytes() as c_uint);
189            load
190        }
191    }
192}
193
194/// Empty string, to be used where LLVM expects an instruction name, indicating
195/// that the instruction is to be left unnamed (i.e. numbered, in textual IR).
196// FIXME(eddyb) pass `&CStr` directly to FFI once it's a thin pointer.
197pub(crate) const UNNAMED: *const c_char = c"".as_ptr();
198
199impl<'ll, CX: Borrow<SCx<'ll>>> BackendTypes for GenericBuilder<'_, 'll, CX> {
200    type Function = <GenericCx<'ll, CX> as BackendTypes>::Function;
201    type BasicBlock = <GenericCx<'ll, CX> as BackendTypes>::BasicBlock;
202    type Funclet = <GenericCx<'ll, CX> as BackendTypes>::Funclet;
203
204    type Value = <GenericCx<'ll, CX> as BackendTypes>::Value;
205    type Type = <GenericCx<'ll, CX> as BackendTypes>::Type;
206    type FunctionSignature = <GenericCx<'ll, CX> as BackendTypes>::FunctionSignature;
207
208    type DIScope = <GenericCx<'ll, CX> as BackendTypes>::DIScope;
209    type DILocation = <GenericCx<'ll, CX> as BackendTypes>::DILocation;
210    type DIVariable = <GenericCx<'ll, CX> as BackendTypes>::DIVariable;
211}
212
213impl abi::HasDataLayout for Builder<'_, '_, '_> {
214    fn data_layout(&self) -> &abi::TargetDataLayout {
215        self.cx.data_layout()
216    }
217}
218
219impl<'tcx> ty::layout::HasTyCtxt<'tcx> for Builder<'_, '_, 'tcx> {
220    #[inline]
221    fn tcx(&self) -> TyCtxt<'tcx> {
222        self.cx.tcx
223    }
224}
225
226impl<'tcx> ty::layout::HasTypingEnv<'tcx> for Builder<'_, '_, 'tcx> {
227    fn typing_env(&self) -> ty::TypingEnv<'tcx> {
228        self.cx.typing_env()
229    }
230}
231
232impl HasTargetSpec for Builder<'_, '_, '_> {
233    #[inline]
234    fn target_spec(&self) -> &Target {
235        self.cx.target_spec()
236    }
237}
238
239impl<'tcx> LayoutOfHelpers<'tcx> for Builder<'_, '_, 'tcx> {
240    #[inline]
241    fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
242        self.cx.handle_layout_err(err, span, ty)
243    }
244}
245
246impl<'tcx> FnAbiOfHelpers<'tcx> for Builder<'_, '_, 'tcx> {
247    #[inline]
248    fn handle_fn_abi_err(
249        &self,
250        err: FnAbiError<'tcx>,
251        span: Span,
252        fn_abi_request: FnAbiRequest<'tcx>,
253    ) -> ! {
254        self.cx.handle_fn_abi_err(err, span, fn_abi_request)
255    }
256}
257
258impl<'ll, 'tcx> Deref for Builder<'_, 'll, 'tcx> {
259    type Target = CodegenCx<'ll, 'tcx>;
260
261    #[inline]
262    fn deref(&self) -> &Self::Target {
263        self.cx
264    }
265}
266
267macro_rules! math_builder_methods {
268    ($($name:ident($($arg:ident),*) => $llvm_capi:ident),+ $(,)?) => {
269        $(fn $name(&mut self, $($arg: &'ll Value),*) -> &'ll Value {
270            unsafe {
271                llvm::$llvm_capi(self.llbuilder, $($arg,)* UNNAMED)
272            }
273        })+
274    }
275}
276
277macro_rules! set_math_builder_methods {
278    ($($name:ident($($arg:ident),*) => ($llvm_capi:ident, $llvm_set_math:ident)),+ $(,)?) => {
279        $(fn $name(&mut self, $($arg: &'ll Value),*) -> &'ll Value {
280            unsafe {
281                let instr = llvm::$llvm_capi(self.llbuilder, $($arg,)* UNNAMED);
282                llvm::$llvm_set_math(instr);
283                instr
284            }
285        })+
286    }
287}
288
289impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> {
290    type CodegenCx = CodegenCx<'ll, 'tcx>;
291
292    fn build(cx: &'a CodegenCx<'ll, 'tcx>, llbb: &'ll BasicBlock) -> Self {
293        let bx = Builder::with_cx(cx);
294        unsafe {
295            llvm::LLVMPositionBuilderAtEnd(bx.llbuilder, llbb);
296        }
297        bx
298    }
299
300    fn cx(&self) -> &CodegenCx<'ll, 'tcx> {
301        self.cx
302    }
303
304    fn llbb(&self) -> &'ll BasicBlock {
305        unsafe { llvm::LLVMGetInsertBlock(self.llbuilder) }
306    }
307
308    fn set_span(&mut self, span: rustc_span::Span) {
309        self.span = span;
310    }
311
312    fn append_block(cx: &'a CodegenCx<'ll, 'tcx>, llfn: &'ll Value, name: &str) -> &'ll BasicBlock {
313        unsafe {
314            let name = SmallCStr::new(name);
315            llvm::LLVMAppendBasicBlockInContext(cx.llcx, llfn, name.as_ptr())
316        }
317    }
318
319    fn append_sibling_block(&mut self, name: &str) -> &'ll BasicBlock {
320        Self::append_block(self.cx, self.llfn(), name)
321    }
322
323    fn switch_to_block(&mut self, llbb: Self::BasicBlock) {
324        *self = Self::build(self.cx, llbb)
325    }
326
327    fn ret_void(&mut self) {
328        llvm::LLVMBuildRetVoid(self.llbuilder);
329    }
330
331    fn ret(&mut self, v: &'ll Value) {
332        unsafe {
333            llvm::LLVMBuildRet(self.llbuilder, v);
334        }
335    }
336
337    fn br(&mut self, dest: &'ll BasicBlock) {
338        unsafe {
339            llvm::LLVMBuildBr(self.llbuilder, dest);
340        }
341    }
342
343    fn br_with_attrs(&mut self, dest: &'ll BasicBlock, attributes: &[AttributeKind]) {
344        unsafe {
345            let val = llvm::LLVMBuildBr(self.llbuilder, dest);
346
347            let mut nodes = Vec::new();
348
349            for attribute in attributes {
350                let AttributeKind::Unroll(unroll) = attribute else {
351                    continue;
352                };
353                // UnrollAttr::Count needs a second operand, the provided count, but the other
354                // unroll hints do not.
355                let md_node = if let UnrollAttr::Count(count) = unroll {
356                    let unroll_meta = self.create_metadata("llvm.loop.unroll.count".as_bytes());
357                    let count = llvm::LLVMValueAsMetadata(self.get_const_i32(u64::from(*count)));
358                    self.md_node_in_context(&[unroll_meta, count])
359                } else {
360                    let metadata_str = match unroll {
361                        UnrollAttr::Hint => "llvm.loop.unroll.enable",
362                        UnrollAttr::Full => "llvm.loop.unroll.full",
363                        UnrollAttr::Never => "llvm.loop.unroll.disable",
364                        UnrollAttr::Count(_) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
365                    };
366                    let unroll_meta = self.create_metadata(metadata_str.as_bytes());
367                    self.md_node_in_context(&[unroll_meta])
368                };
369                nodes.push(md_node);
370            }
371
372            if let [first, ..] = nodes[..] {
373                nodes.insert(0, first);
374
375                // Create the loop metadata node
376                let loop_meta_mdnode = self.set_metadata_node(val, llvm::MD_loop, &nodes);
377
378                // Look up the metadata node as a value
379                let loop_meta_val = llvm::LLVMGetMetadata(val, llvm::MD_loop).unwrap();
380
381                // Replace the first entry with a reference to itself
382                // This is required by LLVM. See the LangRef page for llvm.loop metadata.
383                llvm::LLVMReplaceMDNodeOperandWith(loop_meta_val, 0, loop_meta_mdnode);
384            }
385        }
386    }
387
388    fn cond_br(
389        &mut self,
390        cond: &'ll Value,
391        then_llbb: &'ll BasicBlock,
392        else_llbb: &'ll BasicBlock,
393    ) {
394        unsafe {
395            llvm::LLVMBuildCondBr(self.llbuilder, cond, then_llbb, else_llbb);
396        }
397    }
398
399    fn switch(
400        &mut self,
401        v: &'ll Value,
402        else_llbb: &'ll BasicBlock,
403        cases: impl ExactSizeIterator<Item = (u128, &'ll BasicBlock)>,
404    ) {
405        let switch =
406            unsafe { llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, cases.len() as c_uint) };
407        for (on_val, dest) in cases {
408            let on_val = self.const_uint_big(self.val_ty(v), on_val);
409            unsafe { llvm::LLVMAddCase(switch, on_val, dest) }
410        }
411    }
412
413    fn switch_with_weights(
414        &mut self,
415        v: Self::Value,
416        else_llbb: Self::BasicBlock,
417        else_is_cold: bool,
418        cases: impl ExactSizeIterator<Item = (u128, Self::BasicBlock, bool)>,
419    ) {
420        if self.cx.sess().opts.optimize == rustc_session::config::OptLevel::No {
421            self.switch(v, else_llbb, cases.map(|(val, dest, _)| (val, dest)));
422            return;
423        }
424
425        let id = self.cx.create_metadata(b"branch_weights");
426
427        // For switch instructions with 2 targets, the `llvm.expect` intrinsic is used.
428        // This function handles switch instructions with more than 2 targets and it needs to
429        // emit branch weights metadata instead of using the intrinsic.
430        // The values 1 and 2000 are the same as the values used by the `llvm.expect` intrinsic.
431        let cold_weight = llvm::LLVMValueAsMetadata(self.cx.const_u32(1));
432        let hot_weight = llvm::LLVMValueAsMetadata(self.cx.const_u32(2000));
433        let weight =
434            |is_cold: bool| -> &Metadata { if is_cold { cold_weight } else { hot_weight } };
435
436        let mut md: SmallVec<[&Metadata; 16]> = SmallVec::with_capacity(cases.len() + 2);
437        md.push(id);
438        md.push(weight(else_is_cold));
439
440        let switch =
441            unsafe { llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, cases.len() as c_uint) };
442        for (on_val, dest, is_cold) in cases {
443            let on_val = self.const_uint_big(self.val_ty(v), on_val);
444            unsafe { llvm::LLVMAddCase(switch, on_val, dest) }
445            md.push(weight(is_cold));
446        }
447
448        self.cx.set_metadata_node(switch, llvm::MD_prof, &md);
449    }
450
451    fn invoke(
452        &mut self,
453        llty: &'ll Type,
454        fn_attrs: Option<&CodegenFnAttrs>,
455        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
456        llfn: &'ll Value,
457        return_slot: ReturnSlot<&'ll Value>,
458        args: &[&'ll Value],
459        then: &'ll BasicBlock,
460        catch: &'ll BasicBlock,
461        funclet: Option<&Funclet<'ll>>,
462        instance: Option<Instance<'tcx>>,
463    ) -> &'ll Value {
464        // If this function returns indirectly (`PassMode::Indirect`),
465        // the `return_slot` should be the first argument.
466        let args = match return_slot {
467            ReturnSlot::Direct => args.to_vec(),
468            ReturnSlot::Indirect(sret_ptr) => {
469                let mut args = args.to_vec();
470                args.insert(0, sret_ptr);
471                args
472            }
473        };
474        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_codegen_llvm/src/builder.rs:474",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(474u32),
                        ::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);
475        let args = self.check_call("invoke", llty, llfn, &args);
476        let funclet_bundle = funclet.map(|funclet| funclet.bundle());
477        let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
478        if let Some(funclet_bundle) = funclet_bundle {
479            bundles.push(funclet_bundle);
480        }
481
482        // Emit CFI pointer type membership test
483        self.cfi_type_test(fn_attrs, fn_abi, instance, llfn);
484
485        // Emit KCFI operand bundle
486        let kcfi_bundle = self.kcfi_operand_bundle(fn_attrs, fn_abi, instance, llfn);
487        if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
488            bundles.push(kcfi_bundle);
489        }
490
491        let pauth = self.ptrauth_operand_bundle(llfn, fn_abi);
492        if let Some(p) = pauth.as_ref().map(|b| b.as_ref()) {
493            bundles.push(p);
494        }
495
496        let invoke = unsafe {
497            llvm::LLVMBuildInvokeWithOperandBundles(
498                self.llbuilder,
499                llty,
500                llfn,
501                args.as_ptr(),
502                args.len() as c_uint,
503                then,
504                catch,
505                bundles.as_ptr(),
506                bundles.len() as c_uint,
507                UNNAMED,
508            )
509        };
510        if let Some(fn_abi) = fn_abi {
511            fn_abi.apply_attrs_callsite(self, invoke);
512        }
513        invoke
514    }
515
516    fn unreachable(&mut self) {
517        unsafe {
518            llvm::LLVMBuildUnreachable(self.llbuilder);
519        }
520    }
521
522    fn add(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildAdd(self.llbuilder, a, b, UNNAMED) }
}
fn fadd(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildFAdd(self.llbuilder, a, b, UNNAMED) }
}
fn sub(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildSub(self.llbuilder, a, b, UNNAMED) }
}
fn fsub(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildFSub(self.llbuilder, a, b, UNNAMED) }
}
fn mul(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildMul(self.llbuilder, a, b, UNNAMED) }
}
fn fmul(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildFMul(self.llbuilder, a, b, UNNAMED) }
}
fn udiv(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildUDiv(self.llbuilder, a, b, UNNAMED) }
}
fn exactudiv(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildExactUDiv(self.llbuilder, a, b, UNNAMED) }
}
fn sdiv(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildSDiv(self.llbuilder, a, b, UNNAMED) }
}
fn exactsdiv(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildExactSDiv(self.llbuilder, a, b, UNNAMED) }
}
fn fdiv(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildFDiv(self.llbuilder, a, b, UNNAMED) }
}
fn urem(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildURem(self.llbuilder, a, b, UNNAMED) }
}
fn srem(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildSRem(self.llbuilder, a, b, UNNAMED) }
}
fn frem(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildFRem(self.llbuilder, a, b, UNNAMED) }
}
fn shl(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildShl(self.llbuilder, a, b, UNNAMED) }
}
fn lshr(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildLShr(self.llbuilder, a, b, UNNAMED) }
}
fn ashr(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildAShr(self.llbuilder, a, b, UNNAMED) }
}
fn and(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildAnd(self.llbuilder, a, b, UNNAMED) }
}
fn or(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildOr(self.llbuilder, a, b, UNNAMED) }
}
fn xor(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildXor(self.llbuilder, a, b, UNNAMED) }
}
fn neg(&mut self, x: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildNeg(self.llbuilder, x, UNNAMED) }
}
fn fneg(&mut self, x: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildFNeg(self.llbuilder, x, UNNAMED) }
}
fn not(&mut self, x: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildNot(self.llbuilder, x, UNNAMED) }
}
fn unchecked_sadd(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildNSWAdd(self.llbuilder, x, y, UNNAMED) }
}
fn unchecked_uadd(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildNUWAdd(self.llbuilder, x, y, UNNAMED) }
}
fn unchecked_ssub(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildNSWSub(self.llbuilder, x, y, UNNAMED) }
}
fn unchecked_usub(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildNUWSub(self.llbuilder, x, y, UNNAMED) }
}
fn unchecked_smul(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildNSWMul(self.llbuilder, x, y, UNNAMED) }
}
fn unchecked_umul(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe { llvm::LLVMBuildNUWMul(self.llbuilder, x, y, UNNAMED) }
}math_builder_methods! {
523        add(a, b) => LLVMBuildAdd,
524        fadd(a, b) => LLVMBuildFAdd,
525        sub(a, b) => LLVMBuildSub,
526        fsub(a, b) => LLVMBuildFSub,
527        mul(a, b) => LLVMBuildMul,
528        fmul(a, b) => LLVMBuildFMul,
529        udiv(a, b) => LLVMBuildUDiv,
530        exactudiv(a, b) => LLVMBuildExactUDiv,
531        sdiv(a, b) => LLVMBuildSDiv,
532        exactsdiv(a, b) => LLVMBuildExactSDiv,
533        fdiv(a, b) => LLVMBuildFDiv,
534        urem(a, b) => LLVMBuildURem,
535        srem(a, b) => LLVMBuildSRem,
536        frem(a, b) => LLVMBuildFRem,
537        shl(a, b) => LLVMBuildShl,
538        lshr(a, b) => LLVMBuildLShr,
539        ashr(a, b) => LLVMBuildAShr,
540        and(a, b) => LLVMBuildAnd,
541        or(a, b) => LLVMBuildOr,
542        xor(a, b) => LLVMBuildXor,
543        neg(x) => LLVMBuildNeg,
544        fneg(x) => LLVMBuildFNeg,
545        not(x) => LLVMBuildNot,
546        unchecked_sadd(x, y) => LLVMBuildNSWAdd,
547        unchecked_uadd(x, y) => LLVMBuildNUWAdd,
548        unchecked_ssub(x, y) => LLVMBuildNSWSub,
549        unchecked_usub(x, y) => LLVMBuildNUWSub,
550        unchecked_smul(x, y) => LLVMBuildNSWMul,
551        unchecked_umul(x, y) => LLVMBuildNUWMul,
552    }
553
554    fn unchecked_suadd(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
555        unsafe {
556            let add = llvm::LLVMBuildAdd(self.llbuilder, a, b, UNNAMED);
557            if llvm::LLVMIsAInstruction(add).is_some() {
558                llvm::LLVMSetNUW(add, TRUE);
559                llvm::LLVMSetNSW(add, TRUE);
560            }
561            add
562        }
563    }
564    fn unchecked_susub(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
565        unsafe {
566            let sub = llvm::LLVMBuildSub(self.llbuilder, a, b, UNNAMED);
567            if llvm::LLVMIsAInstruction(sub).is_some() {
568                llvm::LLVMSetNUW(sub, TRUE);
569                llvm::LLVMSetNSW(sub, TRUE);
570            }
571            sub
572        }
573    }
574    fn unchecked_sumul(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
575        unsafe {
576            let mul = llvm::LLVMBuildMul(self.llbuilder, a, b, UNNAMED);
577            if llvm::LLVMIsAInstruction(mul).is_some() {
578                llvm::LLVMSetNUW(mul, TRUE);
579                llvm::LLVMSetNSW(mul, TRUE);
580            }
581            mul
582        }
583    }
584
585    fn or_disjoint(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
586        unsafe {
587            let or = llvm::LLVMBuildOr(self.llbuilder, a, b, UNNAMED);
588
589            // If a and b are both values, then `or` is a value, rather than
590            // an instruction, so we need to check before setting the flag.
591            // (See also `LLVMBuildNUWNeg` which also needs a check.)
592            if llvm::LLVMIsAInstruction(or).is_some() {
593                llvm::LLVMSetIsDisjoint(or, TRUE);
594            }
595            or
596        }
597    }
598
599    fn fadd_fast(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe {
        let instr = llvm::LLVMBuildFAdd(self.llbuilder, x, y, UNNAMED);
        llvm::LLVMRustSetFastMath(instr);
        instr
    }
}
fn fsub_fast(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe {
        let instr = llvm::LLVMBuildFSub(self.llbuilder, x, y, UNNAMED);
        llvm::LLVMRustSetFastMath(instr);
        instr
    }
}
fn fmul_fast(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe {
        let instr = llvm::LLVMBuildFMul(self.llbuilder, x, y, UNNAMED);
        llvm::LLVMRustSetFastMath(instr);
        instr
    }
}
fn fdiv_fast(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe {
        let instr = llvm::LLVMBuildFDiv(self.llbuilder, x, y, UNNAMED);
        llvm::LLVMRustSetFastMath(instr);
        instr
    }
}
fn frem_fast(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe {
        let instr = llvm::LLVMBuildFRem(self.llbuilder, x, y, UNNAMED);
        llvm::LLVMRustSetFastMath(instr);
        instr
    }
}
fn fadd_algebraic(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe {
        let instr = llvm::LLVMBuildFAdd(self.llbuilder, x, y, UNNAMED);
        llvm::LLVMRustSetAlgebraicMath(instr);
        instr
    }
}
fn fsub_algebraic(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe {
        let instr = llvm::LLVMBuildFSub(self.llbuilder, x, y, UNNAMED);
        llvm::LLVMRustSetAlgebraicMath(instr);
        instr
    }
}
fn fmul_algebraic(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe {
        let instr = llvm::LLVMBuildFMul(self.llbuilder, x, y, UNNAMED);
        llvm::LLVMRustSetAlgebraicMath(instr);
        instr
    }
}
fn fdiv_algebraic(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe {
        let instr = llvm::LLVMBuildFDiv(self.llbuilder, x, y, UNNAMED);
        llvm::LLVMRustSetAlgebraicMath(instr);
        instr
    }
}
fn frem_algebraic(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
    unsafe {
        let instr = llvm::LLVMBuildFRem(self.llbuilder, x, y, UNNAMED);
        llvm::LLVMRustSetAlgebraicMath(instr);
        instr
    }
}set_math_builder_methods! {
600        fadd_fast(x, y) => (LLVMBuildFAdd, LLVMRustSetFastMath),
601        fsub_fast(x, y) => (LLVMBuildFSub, LLVMRustSetFastMath),
602        fmul_fast(x, y) => (LLVMBuildFMul, LLVMRustSetFastMath),
603        fdiv_fast(x, y) => (LLVMBuildFDiv, LLVMRustSetFastMath),
604        frem_fast(x, y) => (LLVMBuildFRem, LLVMRustSetFastMath),
605        fadd_algebraic(x, y) => (LLVMBuildFAdd, LLVMRustSetAlgebraicMath),
606        fsub_algebraic(x, y) => (LLVMBuildFSub, LLVMRustSetAlgebraicMath),
607        fmul_algebraic(x, y) => (LLVMBuildFMul, LLVMRustSetAlgebraicMath),
608        fdiv_algebraic(x, y) => (LLVMBuildFDiv, LLVMRustSetAlgebraicMath),
609        frem_algebraic(x, y) => (LLVMBuildFRem, LLVMRustSetAlgebraicMath),
610    }
611
612    fn checked_binop(
613        &mut self,
614        oop: OverflowOp,
615        ty: Ty<'tcx>,
616        lhs: Self::Value,
617        rhs: Self::Value,
618    ) -> (Self::Value, Self::Value) {
619        let (size, signed) = ty.int_size_and_signed(self.tcx);
620        let width = size.bits();
621
622        if !signed {
623            match oop {
624                OverflowOp::Sub => {
625                    // Emit sub and icmp instead of llvm.usub.with.overflow. LLVM considers these
626                    // to be the canonical form. It will attempt to reform llvm.usub.with.overflow
627                    // in the backend if profitable.
628                    let sub = self.sub(lhs, rhs);
629                    let cmp = self.icmp(IntPredicate::IntULT, lhs, rhs);
630                    return (sub, cmp);
631                }
632                OverflowOp::Add => {
633                    // Like with sub above, using icmp is the preferred form. See
634                    // <https://rust-lang.zulipchat.com/#narrow/channel/187780-t-compiler.2Fllvm/topic/.60uadd.2Ewith.2Eoverflow.60.20.28again.29/near/533041085>
635                    let add = self.add(lhs, rhs);
636                    let cmp = self.icmp(IntPredicate::IntULT, add, lhs);
637                    return (add, cmp);
638                }
639                OverflowOp::Mul => {}
640            }
641        }
642
643        let oop_str = match oop {
644            OverflowOp::Add => "add",
645            OverflowOp::Sub => "sub",
646            OverflowOp::Mul => "mul",
647        };
648
649        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' });
650
651        let res = self.call_intrinsic(name, &[self.type_ix(width)], &[lhs, rhs]);
652        (self.extract_value(res, 0), self.extract_value(res, 1))
653    }
654
655    fn from_immediate(&mut self, val: Self::Value) -> Self::Value {
656        if self.cx().val_ty(val) == self.cx().type_i1() {
657            self.zext(val, self.cx().type_i8())
658        } else {
659            val
660        }
661    }
662
663    fn to_immediate_scalar(&mut self, val: Self::Value, scalar: abi::Scalar) -> Self::Value {
664        if scalar.is_bool() {
665            return self.unchecked_utrunc(val, self.cx().type_i1());
666        }
667        val
668    }
669
670    fn alloca(&mut self, size: Size, align: Align) -> &'ll Value {
671        let mut bx = Builder::with_cx(self.cx);
672        bx.position_at_start(unsafe { llvm::LLVMGetFirstBasicBlock(self.llfn()) });
673        let ty = self.cx().type_array(self.cx().type_i8(), size.bytes());
674        unsafe {
675            let alloca = llvm::LLVMBuildAlloca(bx.llbuilder, ty, UNNAMED);
676            llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
677            // Cast to default addrspace if necessary
678            llvm::LLVMBuildPointerCast(bx.llbuilder, alloca, self.cx().type_ptr(), UNNAMED)
679        }
680    }
681
682    fn alloca_with_ty(&mut self, layout: TyAndLayout<'tcx>) -> Self::Value {
683        let mut bx = Builder::with_cx(self.cx);
684        bx.position_at_start(unsafe { llvm::LLVMGetFirstBasicBlock(self.llfn()) });
685        let scalable_vector_ty = layout.llvm_type(self.cx);
686
687        unsafe {
688            let alloca = llvm::LLVMBuildAlloca(&bx.llbuilder, scalable_vector_ty, UNNAMED);
689            llvm::LLVMSetAlignment(alloca, layout.align.abi.bytes() as c_uint);
690            alloca
691        }
692    }
693
694    fn load(&mut self, ty: &'ll Type, ptr: &'ll Value, align: Align) -> &'ll Value {
695        unsafe {
696            let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
697            let align = align.min(self.cx().tcx.sess.target.max_reliable_alignment());
698            llvm::LLVMSetAlignment(load, align.bytes() as c_uint);
699            load
700        }
701    }
702
703    fn volatile_load(&mut self, ty: &'ll Type, ptr: &'ll Value, align: Align) -> &'ll Value {
704        unsafe {
705            let load = self.load(ty, ptr, align);
706            llvm::LLVMSetVolatile(load, llvm::TRUE);
707            load
708        }
709    }
710
711    fn atomic_load(
712        &mut self,
713        ty: &'ll Type,
714        ptr: &'ll Value,
715        order: rustc_middle::ty::AtomicOrdering,
716        volatile: bool,
717        size: Size,
718    ) -> &'ll Value {
719        unsafe {
720            let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
721            // Set atomic ordering
722            llvm::LLVMSetOrdering(load, AtomicOrdering::from_generic(order));
723            if volatile {
724                llvm::LLVMSetVolatile(load, llvm::TRUE);
725            }
726            // LLVM requires the alignment of atomic loads to be at least the size of the type.
727            llvm::LLVMSetAlignment(load, size.bytes() as c_uint);
728            load
729        }
730    }
731
732    {}
#[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/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_codegen_llvm/src/builder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(732u32),
                                    ::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, &'ll Value> =
                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: &'ll Value,
                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/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_codegen_llvm/src/builder.rs"),
                                                    ::tracing_core::__macro_support::Option::Some(749u32),
                                                    ::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))]
733    fn load_operand(&mut self, place: PlaceRef<'tcx, &'ll Value>) -> OperandRef<'tcx, &'ll Value> {
734        if place.layout.is_unsized() {
735            let tail = self.tcx.struct_tail_for_codegen(place.layout.ty, self.typing_env());
736            if matches!(tail.kind(), ty::Foreign(..)) {
737                // Unsized locals and, at least conceptually, even unsized arguments must be copied
738                // around, which requires dynamically determining their size. Therefore, we cannot
739                // allow `extern` types here. Consult t-opsem before removing this check.
740                panic!("unsized locals must not be `extern` types");
741            }
742        }
743        assert_eq!(place.val.llextra.is_some(), place.layout.is_unsized());
744
745        if place.layout.is_zst() {
746            return OperandRef::zero_sized(place.layout);
747        }
748
749        #[instrument(level = "trace", skip(bx))]
750        fn scalar_load_metadata<'a, 'll, 'tcx>(
751            bx: &mut Builder<'a, 'll, 'tcx>,
752            load: &'ll Value,
753            scalar: abi::Scalar,
754            layout: TyAndLayout<'tcx>,
755            offset: Size,
756        ) {
757            if bx.cx.sess().opts.optimize == OptLevel::No {
758                // Don't emit metadata we're not going to use
759                return;
760            }
761
762            if !scalar.is_uninit_valid() {
763                bx.noundef_metadata(load);
764            }
765
766            match scalar.primitive() {
767                abi::Primitive::Int(..) => {
768                    if !scalar.is_always_valid(bx) {
769                        bx.range_metadata(load, scalar.valid_range(bx));
770                    }
771                }
772                abi::Primitive::Pointer(_) => {
773                    if !scalar.valid_range(bx).contains(0) {
774                        bx.nonnull_metadata(load);
775                    }
776
777                    if let Some(pointee) = layout.pointee_info_at(bx, offset)
778                        && pointee.align > Align::ONE
779                    {
780                        bx.align_metadata(load, pointee.align);
781                    }
782                }
783                abi::Primitive::Float(_) => {}
784            }
785        }
786
787        let val = if let Some(_) = place.val.llextra {
788            // FIXME: Merge with the `else` below?
789            OperandValue::Ref(place.val)
790        } else if place.layout.backend_repr.is_scalar_or_simd() {
791            let mut const_llval = None;
792            let llty = place.layout.llvm_type(self);
793            if let Some(global) = llvm::LLVMIsAGlobalVariable(place.val.llval) {
794                if llvm::LLVMIsGlobalConstant(global).is_true() {
795                    if let Some(init) = llvm::LLVMGetInitializer(global) {
796                        if self.val_ty(init) == llty {
797                            const_llval = Some(init);
798                        }
799                    }
800                }
801            }
802
803            let llval = const_llval.unwrap_or_else(|| {
804                let load = self.load(llty, place.val.llval, place.val.align);
805                if let abi::BackendRepr::Scalar(scalar) = place.layout.backend_repr {
806                    scalar_load_metadata(self, load, scalar, place.layout, Size::ZERO);
807                    self.to_immediate_scalar(load, scalar)
808                } else {
809                    load
810                }
811            });
812            OperandValue::Immediate(llval)
813        } else if let abi::BackendRepr::ScalarPair { a, b, b_offset } = place.layout.backend_repr {
814            let mut load = |i, scalar: abi::Scalar, layout, align, offset| {
815                let llptr = if i == 0 {
816                    place.val.llval
817                } else {
818                    self.inbounds_ptradd(place.val.llval, self.const_usize(b_offset.bytes()))
819                };
820                let llty = place.layout.scalar_pair_element_llvm_type(self, i, false);
821                let load = self.load(llty, llptr, align);
822                scalar_load_metadata(self, load, scalar, layout, offset);
823                self.to_immediate_scalar(load, scalar)
824            };
825
826            OperandValue::Pair(
827                load(0, a, place.layout, place.val.align, Size::ZERO),
828                load(1, b, place.layout, place.val.align.restrict_for_offset(b_offset), b_offset),
829            )
830        } else {
831            OperandValue::Ref(place.val)
832        };
833
834        OperandRef { val, layout: place.layout, move_annotation: None }
835    }
836
837    fn write_operand_repeatedly(
838        &mut self,
839        cg_elem: OperandRef<'tcx, &'ll Value>,
840        count: u64,
841        dest: PlaceRef<'tcx, &'ll Value>,
842    ) {
843        if self.cx.sess().opts.optimize == OptLevel::No {
844            // To let debuggers single-step over lines like
845            //
846            //     let foo = ["bar"; 42];
847            //
848            // we need the debugger-friendly LLVM IR that `_unoptimized()`
849            // provides. The `_optimized()` version generates trickier LLVM IR.
850            // See PR #148058 for a failed attempt at handling that.
851            self.write_operand_repeatedly_unoptimized(cg_elem, count, dest);
852        } else {
853            self.write_operand_repeatedly_optimized(cg_elem, count, dest);
854        }
855    }
856
857    fn range_metadata(&mut self, load: &'ll Value, range: WrappingRange) {
858        if self.cx.sess().opts.optimize == OptLevel::No {
859            // Don't emit metadata we're not going to use
860            return;
861        }
862
863        let llty = self.cx.val_ty(load);
864        let md = [
865            llvm::LLVMValueAsMetadata(self.cx.const_uint_big(llty, range.start)),
866            llvm::LLVMValueAsMetadata(self.cx.const_uint_big(llty, range.end.wrapping_add(1))),
867        ];
868        self.set_metadata_node(load, llvm::MD_range, &md);
869    }
870
871    fn nonnull_metadata(&mut self, load: &'ll Value) {
872        self.set_metadata_node(load, llvm::MD_nonnull, &[]);
873    }
874
875    fn store(&mut self, val: &'ll Value, ptr: &'ll Value, align: Align) -> &'ll Value {
876        self.store_with_flags(val, ptr, align, MemFlags::empty())
877    }
878
879    fn store_with_flags(
880        &mut self,
881        val: &'ll Value,
882        ptr: &'ll Value,
883        align: Align,
884        flags: MemFlags,
885    ) -> &'ll Value {
886        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_codegen_llvm/src/builder.rs:886",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(886u32),
                        ::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);
887        {
    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);
888        unsafe {
889            let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
890            let align = align.min(self.cx().tcx.sess.target.max_reliable_alignment());
891            let align = align.bytes() as c_uint;
892            llvm::LLVMSetAlignment(store, align);
893            if flags.contains(MemFlags::VOLATILE) {
894                llvm::LLVMSetVolatile(store, llvm::TRUE);
895            }
896            if flags.contains(MemFlags::NONTEMPORAL) {
897                // Make sure that the current target architectures supports "sane" non-temporal
898                // stores, i.e., non-temporal stores that are equivalent to regular stores except
899                // for performance. LLVM doesn't seem to care about this, and will happily treat
900                // `!nontemporal` stores as-if they were normal stores (for reordering optimizations
901                // etc) even on x86, despite later lowering them to MOVNT which do *not* behave like
902                // regular stores but require special fences. So we keep a list of architectures
903                // where `!nontemporal` is known to be truly just a hint, and use regular stores
904                // everywhere else. (In the future, we could alternatively ensure that an sfence
905                // gets emitted after a sequence of movnt before any kind of synchronizing
906                // operation. But it's not clear how to do that with LLVM.)
907                // For more context, see <https://github.com/rust-lang/rust/issues/114582> and
908                // <https://github.com/llvm/llvm-project/issues/64521>.
909                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!(
910                    self.cx.tcx.sess.target.arch,
911                    Arch::AArch64 | Arch::Arm | Arch::RiscV32 | Arch::RiscV64
912                );
913                if use_nontemporal {
914                    // According to LLVM [1] building a nontemporal store must
915                    // *always* point to a metadata value of the integer 1.
916                    //
917                    // [1]: https://llvm.org/docs/LangRef.html#store-instruction
918                    let one = llvm::LLVMValueAsMetadata(self.cx.const_i32(1));
919                    self.set_metadata_node(store, llvm::MD_nontemporal, &[one]);
920                }
921            }
922            if flags.contains(MemFlags::CAPTURES_READ_ONLY)
923                && crate::llvm_util::get_version() >= (22, 0, 0)
924            {
925                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!(
926                    self.type_kind(self.val_ty(val)) == TypeKind::Pointer,
927                    "CAPTURED_READ_ONLY is only supported on pointer stores"
928                );
929                let args = [
930                    self.cx.create_metadata(b"address"),
931                    self.cx.create_metadata(b"read_provenance"),
932                ];
933                // FIXME: Switch this to use MD_captures once LLVM 22 is the minimum.
934                let id = self.get_md_kind_id("captures");
935                let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, args.as_ptr(), args.len());
936                self.set_metadata(store, id, md);
937            }
938            store
939        }
940    }
941
942    fn atomic_store(
943        &mut self,
944        val: &'ll Value,
945        ptr: &'ll Value,
946        order: rustc_middle::ty::AtomicOrdering,
947        volatile: bool,
948        size: Size,
949    ) {
950        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_codegen_llvm/src/builder.rs:950",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(950u32),
                        ::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);
951        {
    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);
952        unsafe {
953            let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
954            // Set atomic ordering
955            llvm::LLVMSetOrdering(store, AtomicOrdering::from_generic(order));
956            if volatile {
957                llvm::LLVMSetVolatile(store, llvm::TRUE);
958            }
959            // LLVM requires the alignment of atomic stores to be at least the size of the type.
960            llvm::LLVMSetAlignment(store, size.bytes() as c_uint);
961        }
962    }
963
964    fn gep(&mut self, ty: &'ll Type, ptr: &'ll Value, indices: &[&'ll Value]) -> &'ll Value {
965        unsafe {
966            llvm::LLVMBuildGEPWithNoWrapFlags(
967                self.llbuilder,
968                ty,
969                ptr,
970                indices.as_ptr(),
971                indices.len() as c_uint,
972                UNNAMED,
973                GEPNoWrapFlags::default(),
974            )
975        }
976    }
977
978    fn inbounds_gep(
979        &mut self,
980        ty: &'ll Type,
981        ptr: &'ll Value,
982        indices: &[&'ll Value],
983    ) -> &'ll Value {
984        unsafe {
985            llvm::LLVMBuildGEPWithNoWrapFlags(
986                self.llbuilder,
987                ty,
988                ptr,
989                indices.as_ptr(),
990                indices.len() as c_uint,
991                UNNAMED,
992                GEPNoWrapFlags::InBounds,
993            )
994        }
995    }
996
997    fn inbounds_nuw_gep(
998        &mut self,
999        ty: &'ll Type,
1000        ptr: &'ll Value,
1001        indices: &[&'ll Value],
1002    ) -> &'ll Value {
1003        unsafe {
1004            llvm::LLVMBuildGEPWithNoWrapFlags(
1005                self.llbuilder,
1006                ty,
1007                ptr,
1008                indices.as_ptr(),
1009                indices.len() as c_uint,
1010                UNNAMED,
1011                GEPNoWrapFlags::InBounds | GEPNoWrapFlags::NUW,
1012            )
1013        }
1014    }
1015
1016    /* Casts */
1017    fn trunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1018        unsafe { llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
1019    }
1020
1021    fn unchecked_utrunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1022        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);
1023
1024        let trunc = self.trunc(val, dest_ty);
1025        unsafe {
1026            if llvm::LLVMIsAInstruction(trunc).is_some() {
1027                llvm::LLVMSetNUW(trunc, TRUE);
1028            }
1029        }
1030        trunc
1031    }
1032
1033    fn unchecked_strunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1034        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);
1035
1036        let trunc = self.trunc(val, dest_ty);
1037        unsafe {
1038            if llvm::LLVMIsAInstruction(trunc).is_some() {
1039                llvm::LLVMSetNSW(trunc, TRUE);
1040            }
1041        }
1042        trunc
1043    }
1044
1045    fn sext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1046        unsafe { llvm::LLVMBuildSExt(self.llbuilder, val, dest_ty, UNNAMED) }
1047    }
1048
1049    fn fptoui_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1050        self.call_intrinsic("llvm.fptoui.sat", &[dest_ty, self.val_ty(val)], &[val])
1051    }
1052
1053    fn fptosi_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1054        self.call_intrinsic("llvm.fptosi.sat", &[dest_ty, self.val_ty(val)], &[val])
1055    }
1056
1057    fn fptoui(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1058        // On WebAssembly the `fptoui` and `fptosi` instructions currently have
1059        // poor codegen. The reason for this is that the corresponding wasm
1060        // instructions, `i32.trunc_f32_s` for example, will trap when the float
1061        // is out-of-bounds, infinity, or nan. This means that LLVM
1062        // automatically inserts control flow around `fptoui` and `fptosi`
1063        // because the LLVM instruction `fptoui` is defined as producing a
1064        // poison value, not having UB on out-of-bounds values.
1065        //
1066        // This method, however, is only used with non-saturating casts that
1067        // have UB on out-of-bounds values. This means that it's ok if we use
1068        // the raw wasm instruction since out-of-bounds values can do whatever
1069        // we like. To ensure that LLVM picks the right instruction we choose
1070        // the raw wasm intrinsic functions which avoid LLVM inserting all the
1071        // other control flow automatically.
1072        if self.sess().target.is_like_wasm {
1073            let src_ty = self.cx.val_ty(val);
1074            if self.cx.type_kind(src_ty) != TypeKind::Vector {
1075                let float_width = self.cx.float_width(src_ty);
1076                let int_width = self.cx.int_width(dest_ty);
1077                if #[allow(non_exhaustive_omitted_patterns)] match (int_width, float_width) {
    (32 | 64, 32 | 64) => true,
    _ => false,
}matches!((int_width, float_width), (32 | 64, 32 | 64)) {
1078                    return self.call_intrinsic(
1079                        "llvm.wasm.trunc.unsigned",
1080                        &[dest_ty, src_ty],
1081                        &[val],
1082                    );
1083                }
1084            }
1085        }
1086        unsafe { llvm::LLVMBuildFPToUI(self.llbuilder, val, dest_ty, UNNAMED) }
1087    }
1088
1089    fn fptosi(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1090        // see `fptoui` above for why wasm is different here
1091        if self.sess().target.is_like_wasm {
1092            let src_ty = self.cx.val_ty(val);
1093            if self.cx.type_kind(src_ty) != TypeKind::Vector {
1094                let float_width = self.cx.float_width(src_ty);
1095                let int_width = self.cx.int_width(dest_ty);
1096                if #[allow(non_exhaustive_omitted_patterns)] match (int_width, float_width) {
    (32 | 64, 32 | 64) => true,
    _ => false,
}matches!((int_width, float_width), (32 | 64, 32 | 64)) {
1097                    return self.call_intrinsic(
1098                        "llvm.wasm.trunc.signed",
1099                        &[dest_ty, src_ty],
1100                        &[val],
1101                    );
1102                }
1103            }
1104        }
1105        unsafe { llvm::LLVMBuildFPToSI(self.llbuilder, val, dest_ty, UNNAMED) }
1106    }
1107
1108    fn uitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1109        unsafe { llvm::LLVMBuildUIToFP(self.llbuilder, val, dest_ty, UNNAMED) }
1110    }
1111
1112    fn sitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1113        unsafe { llvm::LLVMBuildSIToFP(self.llbuilder, val, dest_ty, UNNAMED) }
1114    }
1115
1116    fn fptrunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1117        unsafe { llvm::LLVMBuildFPTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
1118    }
1119
1120    fn fpext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1121        unsafe { llvm::LLVMBuildFPExt(self.llbuilder, val, dest_ty, UNNAMED) }
1122    }
1123
1124    fn ptrtoint(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1125        unsafe { llvm::LLVMBuildPtrToInt(self.llbuilder, val, dest_ty, UNNAMED) }
1126    }
1127
1128    fn inttoptr(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1129        unsafe { llvm::LLVMBuildIntToPtr(self.llbuilder, val, dest_ty, UNNAMED) }
1130    }
1131
1132    fn bitcast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1133        unsafe { llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty, UNNAMED) }
1134    }
1135
1136    fn intcast(&mut self, val: &'ll Value, dest_ty: &'ll Type, is_signed: bool) -> &'ll Value {
1137        unsafe {
1138            llvm::LLVMBuildIntCast2(self.llbuilder, val, dest_ty, is_signed.to_llvm_bool(), UNNAMED)
1139        }
1140    }
1141
1142    fn pointercast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1143        unsafe { llvm::LLVMBuildPointerCast(self.llbuilder, val, dest_ty, UNNAMED) }
1144    }
1145
1146    /* Comparisons */
1147    fn icmp(&mut self, op: IntPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1148        let op = llvm::IntPredicate::from_generic(op);
1149        unsafe { llvm::LLVMBuildICmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
1150    }
1151
1152    fn fcmp(&mut self, op: RealPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1153        let op = llvm::RealPredicate::from_generic(op);
1154        unsafe { llvm::LLVMBuildFCmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
1155    }
1156
1157    fn three_way_compare(
1158        &mut self,
1159        ty: Ty<'tcx>,
1160        lhs: Self::Value,
1161        rhs: Self::Value,
1162    ) -> Self::Value {
1163        let size = ty.primitive_size(self.tcx);
1164        let name = if ty.is_signed() { "llvm.scmp" } else { "llvm.ucmp" };
1165
1166        self.call_intrinsic(name, &[self.type_i8(), self.type_ix(size.bits())], &[lhs, rhs])
1167    }
1168
1169    /* Miscellaneous instructions */
1170    fn memcpy(
1171        &mut self,
1172        dst: &'ll Value,
1173        dst_align: Align,
1174        src: &'ll Value,
1175        src_align: Align,
1176        size: &'ll Value,
1177        flags: MemFlags,
1178        tt: Option<FncTree>,
1179    ) {
1180        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");
1181        let size = self.intcast(size, self.type_isize(), false);
1182        let is_volatile = flags.contains(MemFlags::VOLATILE);
1183        let memcpy = unsafe {
1184            llvm::LLVMRustBuildMemCpy(
1185                self.llbuilder,
1186                dst,
1187                dst_align.bytes() as c_uint,
1188                src,
1189                src_align.bytes() as c_uint,
1190                size,
1191                is_volatile,
1192            )
1193        };
1194
1195        // TypeTree metadata for memcpy is especially important: when Enzyme encounters
1196        // a memcpy during autodiff, it needs to know the structure of the data being
1197        // copied to properly track derivatives. For example, copying an array of floats
1198        // vs. copying a struct with mixed types requires different derivative handling.
1199        // The TypeTree tells Enzyme exactly what memory layout to expect.
1200        if let Some(tt) = tt {
1201            crate::typetree::add_tt(self, memcpy, tt);
1202        }
1203    }
1204
1205    fn memmove(
1206        &mut self,
1207        dst: &'ll Value,
1208        dst_align: Align,
1209        src: &'ll Value,
1210        src_align: Align,
1211        size: &'ll Value,
1212        flags: MemFlags,
1213    ) {
1214        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");
1215        let size = self.intcast(size, self.type_isize(), false);
1216        let is_volatile = flags.contains(MemFlags::VOLATILE);
1217        unsafe {
1218            llvm::LLVMRustBuildMemMove(
1219                self.llbuilder,
1220                dst,
1221                dst_align.bytes() as c_uint,
1222                src,
1223                src_align.bytes() as c_uint,
1224                size,
1225                is_volatile,
1226            );
1227        }
1228    }
1229
1230    fn memset(
1231        &mut self,
1232        ptr: &'ll Value,
1233        fill_byte: &'ll Value,
1234        size: &'ll Value,
1235        align: Align,
1236        flags: MemFlags,
1237    ) {
1238        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");
1239        let is_volatile = flags.contains(MemFlags::VOLATILE);
1240        unsafe {
1241            llvm::LLVMRustBuildMemSet(
1242                self.llbuilder,
1243                ptr,
1244                align.bytes() as c_uint,
1245                fill_byte,
1246                size,
1247                is_volatile,
1248            );
1249        }
1250    }
1251
1252    fn vscale(&mut self, ty: &'ll Type) -> &'ll Value {
1253        unsafe { llvm::LLVMRustBuildVScale(self.llbuilder, ty) }
1254    }
1255
1256    fn select(
1257        &mut self,
1258        cond: &'ll Value,
1259        then_val: &'ll Value,
1260        else_val: &'ll Value,
1261    ) -> &'ll Value {
1262        unsafe { llvm::LLVMBuildSelect(self.llbuilder, cond, then_val, else_val, UNNAMED) }
1263    }
1264
1265    fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
1266        unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
1267    }
1268
1269    fn extract_element(&mut self, vec: &'ll Value, idx: &'ll Value) -> &'ll Value {
1270        unsafe { llvm::LLVMBuildExtractElement(self.llbuilder, vec, idx, UNNAMED) }
1271    }
1272
1273    fn vector_splat(&mut self, num_elts: usize, elt: &'ll Value) -> &'ll Value {
1274        unsafe {
1275            let elt_ty = self.cx.val_ty(elt);
1276            let undef = llvm::LLVMGetUndef(self.type_vector(elt_ty, num_elts as u64));
1277            let vec = self.insert_element(undef, elt, self.cx.const_i32(0));
1278            let vec_i32_ty = self.type_vector(self.type_i32(), num_elts as u64);
1279            self.shuffle_vector(vec, undef, self.const_null(vec_i32_ty))
1280        }
1281    }
1282
1283    fn extract_value(&mut self, agg_val: &'ll Value, idx: u64) -> &'ll Value {
1284        {
    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);
1285        unsafe { llvm::LLVMBuildExtractValue(self.llbuilder, agg_val, idx as c_uint, UNNAMED) }
1286    }
1287
1288    fn insert_value(&mut self, agg_val: &'ll Value, elt: &'ll Value, idx: u64) -> &'ll Value {
1289        {
    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);
1290        unsafe { llvm::LLVMBuildInsertValue(self.llbuilder, agg_val, elt, idx as c_uint, UNNAMED) }
1291    }
1292
1293    fn set_personality_fn(&mut self, personality: &'ll Value) {
1294        unsafe {
1295            llvm::LLVMSetPersonalityFn(self.llfn(), personality);
1296        }
1297    }
1298
1299    fn cleanup_landing_pad(&mut self, pers_fn: &'ll Value) -> (&'ll Value, &'ll Value) {
1300        let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1301        let landing_pad = self.landing_pad(ty, pers_fn, 0);
1302        unsafe {
1303            llvm::LLVMSetCleanup(landing_pad, llvm::TRUE);
1304        }
1305        (self.extract_value(landing_pad, 0), self.extract_value(landing_pad, 1))
1306    }
1307
1308    fn filter_landing_pad(&mut self, pers_fn: &'ll Value) {
1309        let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1310        let landing_pad = self.landing_pad(ty, pers_fn, 1);
1311        self.add_clause(landing_pad, self.const_array(self.type_ptr(), &[]));
1312    }
1313
1314    fn resume(&mut self, exn0: &'ll Value, exn1: &'ll Value) {
1315        let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1316        let mut exn = self.const_poison(ty);
1317        exn = self.insert_value(exn, exn0, 0);
1318        exn = self.insert_value(exn, exn1, 1);
1319        unsafe {
1320            llvm::LLVMBuildResume(self.llbuilder, exn);
1321        }
1322    }
1323
1324    fn cleanup_pad(&mut self, parent: Option<&'ll Value>, args: &[&'ll Value]) -> Funclet<'ll> {
1325        let ret = unsafe {
1326            llvm::LLVMBuildCleanupPad(
1327                self.llbuilder,
1328                parent,
1329                args.as_ptr(),
1330                args.len() as c_uint,
1331                c"cleanuppad".as_ptr(),
1332            )
1333        };
1334        Funclet::new(ret.expect("LLVM does not have support for cleanuppad"))
1335    }
1336
1337    fn cleanup_ret(&mut self, funclet: &Funclet<'ll>, unwind: Option<&'ll BasicBlock>) {
1338        unsafe {
1339            llvm::LLVMBuildCleanupRet(self.llbuilder, funclet.cleanuppad(), unwind)
1340                .expect("LLVM does not have support for cleanupret");
1341        }
1342    }
1343
1344    fn catch_pad(&mut self, parent: &'ll Value, args: &[&'ll Value]) -> Funclet<'ll> {
1345        let ret = unsafe {
1346            llvm::LLVMBuildCatchPad(
1347                self.llbuilder,
1348                parent,
1349                args.as_ptr(),
1350                args.len() as c_uint,
1351                c"catchpad".as_ptr(),
1352            )
1353        };
1354        Funclet::new(ret.expect("LLVM does not have support for catchpad"))
1355    }
1356
1357    fn catch_switch(
1358        &mut self,
1359        parent: Option<&'ll Value>,
1360        unwind: Option<&'ll BasicBlock>,
1361        handlers: &[&'ll BasicBlock],
1362    ) -> &'ll Value {
1363        let ret = unsafe {
1364            llvm::LLVMBuildCatchSwitch(
1365                self.llbuilder,
1366                parent,
1367                unwind,
1368                handlers.len() as c_uint,
1369                c"catchswitch".as_ptr(),
1370            )
1371        };
1372        let ret = ret.expect("LLVM does not have support for catchswitch");
1373        for handler in handlers {
1374            unsafe {
1375                llvm::LLVMAddHandler(ret, handler);
1376            }
1377        }
1378        ret
1379    }
1380
1381    fn get_funclet_cleanuppad(&self, funclet: &Funclet<'ll>) -> &'ll Value {
1382        funclet.cleanuppad()
1383    }
1384
1385    // Atomic Operations
1386    fn atomic_cmpxchg(
1387        &mut self,
1388        dst: &'ll Value,
1389        cmp: &'ll Value,
1390        src: &'ll Value,
1391        order: rustc_middle::ty::AtomicOrdering,
1392        failure_order: rustc_middle::ty::AtomicOrdering,
1393        weak: bool,
1394    ) -> (&'ll Value, &'ll Value) {
1395        unsafe {
1396            let value = llvm::LLVMBuildAtomicCmpXchg(
1397                self.llbuilder,
1398                dst,
1399                cmp,
1400                src,
1401                AtomicOrdering::from_generic(order),
1402                AtomicOrdering::from_generic(failure_order),
1403                llvm::FALSE, // SingleThreaded
1404            );
1405            llvm::LLVMSetWeak(value, weak.to_llvm_bool());
1406            let val = self.extract_value(value, 0);
1407            let success = self.extract_value(value, 1);
1408            (val, success)
1409        }
1410    }
1411
1412    fn atomic_rmw(
1413        &mut self,
1414        op: rustc_codegen_ssa::common::AtomicRmwBinOp,
1415        dst: &'ll Value,
1416        src: &'ll Value,
1417        order: rustc_middle::ty::AtomicOrdering,
1418        ret_ptr: bool,
1419    ) -> &'ll Value {
1420        // FIXME: If `ret_ptr` is true and `src` is not a pointer, we *should* tell LLVM that the
1421        // LHS is a pointer and the operation should be provenance-preserving, but LLVM does not
1422        // currently support that (https://github.com/llvm/llvm-project/issues/120837).
1423        let mut res = unsafe {
1424            llvm::LLVMBuildAtomicRMW(
1425                self.llbuilder,
1426                AtomicRmwBinOp::from_generic(op),
1427                dst,
1428                src,
1429                AtomicOrdering::from_generic(order),
1430                llvm::FALSE, // SingleThreaded
1431            )
1432        };
1433        if ret_ptr && self.val_ty(res) != self.type_ptr() {
1434            res = self.inttoptr(res, self.type_ptr());
1435        }
1436        res
1437    }
1438
1439    fn atomic_fence(
1440        &mut self,
1441        order: rustc_middle::ty::AtomicOrdering,
1442        scope: SynchronizationScope,
1443    ) {
1444        let single_threaded = match scope {
1445            SynchronizationScope::SingleThread => true,
1446            SynchronizationScope::CrossThread => false,
1447        };
1448        unsafe {
1449            llvm::LLVMBuildFence(
1450                self.llbuilder,
1451                AtomicOrdering::from_generic(order),
1452                single_threaded.to_llvm_bool(),
1453                UNNAMED,
1454            );
1455        }
1456    }
1457
1458    fn set_invariant_load(&mut self, load: &'ll Value) {
1459        self.set_metadata_node(load, llvm::MD_invariant_load, &[]);
1460    }
1461
1462    fn lifetime_start(&mut self, ptr: &'ll Value, size: Size) {
1463        self.call_lifetime_intrinsic("llvm.lifetime.start", ptr, size);
1464    }
1465
1466    fn lifetime_end(&mut self, ptr: &'ll Value, size: Size) {
1467        self.call_lifetime_intrinsic("llvm.lifetime.end", ptr, size);
1468    }
1469
1470    fn call(
1471        &mut self,
1472        llty: &'ll Type,
1473        caller_attrs: Option<&CodegenFnAttrs>,
1474        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1475        llfn: &'ll Value,
1476        return_slot: ReturnSlot<&'ll Value>,
1477        args: &[&'ll Value],
1478        funclet: Option<&Funclet<'ll>>,
1479        callee_instance: Option<Instance<'tcx>>,
1480    ) -> &'ll Value {
1481        // If this function returns indirectly (`PassMode::Indirect`),
1482        // the `return_slot` should be the first argument.
1483        let args = match return_slot {
1484            ReturnSlot::Direct => args.to_vec(),
1485            ReturnSlot::Indirect(sret_ptr) => {
1486                let mut args = args.to_vec();
1487                args.insert(0, sret_ptr);
1488                args
1489            }
1490        };
1491        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_codegen_llvm/src/builder.rs:1491",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(1491u32),
                        ::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);
1492        let args = self.check_call("call", llty, llfn, &args);
1493        let funclet_bundle = funclet.map(|funclet| funclet.bundle());
1494        let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
1495        if let Some(funclet_bundle) = funclet_bundle {
1496            bundles.push(funclet_bundle);
1497        }
1498
1499        // Emit CFI pointer type membership test
1500        self.cfi_type_test(caller_attrs, fn_abi, callee_instance, llfn);
1501
1502        // Emit KCFI operand bundle
1503        let kcfi_bundle = self.kcfi_operand_bundle(caller_attrs, fn_abi, callee_instance, llfn);
1504        if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
1505            bundles.push(kcfi_bundle);
1506        }
1507
1508        let pauth = self.ptrauth_operand_bundle(llfn, fn_abi);
1509        if let Some(p) = pauth.as_ref().map(|b| b.as_ref()) {
1510            bundles.push(p);
1511        }
1512
1513        let call = unsafe {
1514            llvm::LLVMBuildCallWithOperandBundles(
1515                self.llbuilder,
1516                llty,
1517                llfn,
1518                args.as_ptr() as *const &llvm::Value,
1519                args.len() as c_uint,
1520                bundles.as_ptr(),
1521                bundles.len() as c_uint,
1522                c"".as_ptr(),
1523            )
1524        };
1525
1526        if let Some(callee_instance) = callee_instance {
1527            // Attributes on the function definition being called
1528            let callee_attrs = self.cx.tcx.codegen_fn_attrs(callee_instance.def_id());
1529
1530            if let Some(inlining_rule) =
1531                attributes::inline_attr(&self.cx, self.cx.tcx, callee_instance, callee_attrs)
1532            {
1533                attributes::apply_to_callsite(
1534                    call,
1535                    llvm::AttributePlace::Function,
1536                    &[inlining_rule],
1537                );
1538            }
1539        }
1540
1541        if let Some(fn_abi) = fn_abi {
1542            fn_abi.apply_attrs_callsite(self, call);
1543        }
1544        call
1545    }
1546
1547    fn tail_call(
1548        &mut self,
1549        llty: Self::Type,
1550        caller_attrs: Option<&CodegenFnAttrs>,
1551        fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
1552        llfn: Self::Value,
1553        return_slot: ReturnSlot<Self::Value>,
1554        args: &[Self::Value],
1555        funclet: Option<&Self::Funclet>,
1556        callee_instance: Option<Instance<'tcx>>,
1557    ) {
1558        let call = self.call(
1559            llty,
1560            caller_attrs,
1561            Some(fn_abi),
1562            llfn,
1563            return_slot,
1564            args,
1565            funclet,
1566            callee_instance,
1567        );
1568        llvm::LLVMSetTailCallKind(call, llvm::TailCallKind::MustTail);
1569
1570        match &fn_abi.ret.mode {
1571            PassMode::Ignore | PassMode::Indirect { .. } => self.ret_void(),
1572            PassMode::Direct(_) | PassMode::Pair { .. } | PassMode::Cast { .. } => self.ret(call),
1573        }
1574    }
1575
1576    fn zext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1577        unsafe { llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty, UNNAMED) }
1578    }
1579
1580    fn apply_attrs_to_cleanup_callsite(&mut self, llret: &'ll Value) {
1581        // Cleanup is always the cold path.
1582        let cold_inline = llvm::AttributeKind::Cold.create_attr(self.llcx);
1583        attributes::apply_to_callsite(llret, llvm::AttributePlace::Function, &[cold_inline]);
1584    }
1585}
1586
1587impl<'ll> StaticBuilderMethods for Builder<'_, 'll, '_> {
1588    fn get_static(&mut self, def_id: DefId) -> &'ll Value {
1589        // Forward to the `get_static` method of `CodegenCx`
1590        let global = self.cx().get_static(def_id);
1591        if self.cx().tcx.is_thread_local_static(def_id) {
1592            let pointer =
1593                self.call_intrinsic("llvm.threadlocal.address", &[self.val_ty(global)], &[global]);
1594            // Cast to default address space if globals are in a different addrspace
1595            self.pointercast(pointer, self.type_ptr())
1596        } else {
1597            // Cast to default address space if globals are in a different addrspace
1598            self.cx().const_pointercast(global, self.type_ptr())
1599        }
1600    }
1601}
1602
1603impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1604    pub(crate) fn llfn(&self) -> &'ll Value {
1605        unsafe { llvm::LLVMGetBasicBlockParent(self.llbb()) }
1606    }
1607
1608    fn generate_ubsan_cfi_diag_data(
1609        &mut self,
1610        span: rustc_span::Span,
1611        expected_ty: String,
1612        check_kind: u8,
1613    ) -> &'ll Value {
1614        let cx = self.cx();
1615        let tcx = cx.tcx;
1616
1617        let loc = tcx.sess.source_map().lookup_char_pos(span.lo());
1618
1619        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());
1620        let filename_val = cx.const_bytes(filename_str.as_bytes());
1621        let filename_ptr = cx.static_addr_of_impl(filename_val, Align::ONE, None);
1622
1623        // SourceLocation UBSan struct: { const char *filename, uint32_t line, uint32_t column }
1624        let source_location = cx.const_struct(
1625            &[
1626                filename_ptr,
1627                cx.const_u32(loc.line as u32),
1628                // UBSan columns are 1-based
1629                cx.const_u32(loc.col.0 as u32 + 1),
1630            ],
1631            false, // packed = false
1632        );
1633
1634        let ty_name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}\0", expected_ty))
    })format!("{}\0", expected_ty);
1635        let ty_name_val = cx.const_bytes(ty_name.as_bytes());
1636
1637        // TypeDescriptor UBSan struct: { uint16_t TypeKind, uint16_t TypeInfo, const char *TypeName }
1638        let type_descriptor =
1639            cx.const_struct(&[cx.const_i16(0xffffu16 as i16), cx.const_i16(0), ty_name_val], false);
1640
1641        let type_descriptor_ptr =
1642            cx.static_addr_of_impl(type_descriptor, Align::from_bytes(2).unwrap(), None);
1643
1644        // CFICheckFailData UBSan struct: { uint8_t CheckKind, SourceLocation Loc, TypeDescriptor *Type }
1645        let cfi_check_fail_data = cx
1646            .const_struct(&[cx.const_u8(check_kind), source_location, type_descriptor_ptr], false);
1647        let align = tcx.data_layout.aggregate_align;
1648
1649        // Returns the final opaque pointer to the struct to be passed to __ubsan_handle_cfi_check_fail
1650        cx.static_addr_of_mut(cfi_check_fail_data, align, Some("__ubsan_cfi_check_fail_data"))
1651    }
1652}
1653
1654impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1655    fn position_at_start(&mut self, llbb: &'ll BasicBlock) {
1656        unsafe {
1657            llvm::LLVMRustPositionBuilderAtStart(self.llbuilder, llbb);
1658        }
1659    }
1660}
1661impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1662    fn align_metadata(&mut self, load: &'ll Value, align: Align) {
1663        let md = [llvm::LLVMValueAsMetadata(self.cx.const_u64(align.bytes()))];
1664        self.set_metadata_node(load, llvm::MD_align, &md);
1665    }
1666
1667    fn noundef_metadata(&mut self, load: &'ll Value) {
1668        self.set_metadata_node(load, llvm::MD_noundef, &[]);
1669    }
1670
1671    pub(crate) fn set_unpredictable(&mut self, inst: &'ll Value) {
1672        self.set_metadata_node(inst, llvm::MD_unpredictable, &[]);
1673    }
1674
1675    fn write_operand_repeatedly_optimized(
1676        &mut self,
1677        cg_elem: OperandRef<'tcx, &'ll Value>,
1678        count: u64,
1679        dest: PlaceRef<'tcx, &'ll Value>,
1680    ) {
1681        let zero = self.const_usize(0);
1682        let count = self.const_usize(count);
1683
1684        let header_bb = self.append_sibling_block("repeat_loop_header");
1685        let body_bb = self.append_sibling_block("repeat_loop_body");
1686        let next_bb = self.append_sibling_block("repeat_loop_next");
1687
1688        self.br(header_bb);
1689
1690        let mut header_bx = Self::build(self.cx, header_bb);
1691        let i = header_bx.phi(self.val_ty(zero), &[zero], &[self.llbb()]);
1692
1693        let keep_going = header_bx.icmp(IntPredicate::IntULT, i, count);
1694        header_bx.cond_br(keep_going, body_bb, next_bb);
1695
1696        let mut body_bx = Self::build(self.cx, body_bb);
1697        let dest_elem = dest.project_index(&mut body_bx, i);
1698        cg_elem.val.store(&mut body_bx, dest_elem);
1699
1700        let next = body_bx.unchecked_uadd(i, self.const_usize(1));
1701        body_bx.br(header_bb);
1702        header_bx.add_incoming_to_phi(i, next, body_bb);
1703
1704        *self = Self::build(self.cx, next_bb);
1705    }
1706
1707    fn write_operand_repeatedly_unoptimized(
1708        &mut self,
1709        cg_elem: OperandRef<'tcx, &'ll Value>,
1710        count: u64,
1711        dest: PlaceRef<'tcx, &'ll Value>,
1712    ) {
1713        let zero = self.const_usize(0);
1714        let count = self.const_usize(count);
1715        let start = dest.project_index(self, zero).val.llval;
1716        let end = dest.project_index(self, count).val.llval;
1717
1718        let header_bb = self.append_sibling_block("repeat_loop_header");
1719        let body_bb = self.append_sibling_block("repeat_loop_body");
1720        let next_bb = self.append_sibling_block("repeat_loop_next");
1721
1722        self.br(header_bb);
1723
1724        let mut header_bx = Self::build(self.cx, header_bb);
1725        let current = header_bx.phi(self.val_ty(start), &[start], &[self.llbb()]);
1726
1727        let keep_going = header_bx.icmp(IntPredicate::IntNE, current, end);
1728        header_bx.cond_br(keep_going, body_bb, next_bb);
1729
1730        let mut body_bx = Self::build(self.cx, body_bb);
1731        let align = dest.val.align.restrict_for_offset(dest.layout.field(self.cx(), 0).size);
1732        cg_elem
1733            .val
1734            .store(&mut body_bx, PlaceRef::new_sized_aligned(current, cg_elem.layout, align));
1735
1736        let next = body_bx.inbounds_gep(
1737            self.backend_type(cg_elem.layout),
1738            current,
1739            &[self.const_usize(1)],
1740        );
1741        body_bx.br(header_bb);
1742        header_bx.add_incoming_to_phi(current, next, body_bb);
1743
1744        *self = Self::build(self.cx, next_bb);
1745    }
1746
1747    pub(crate) fn minimum_number_nsz(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1748        let call = self.call_intrinsic("llvm.minimumnum", &[self.val_ty(lhs)], &[lhs, rhs]);
1749        unsafe { llvm::LLVMRustSetNoSignedZeros(call) };
1750        call
1751    }
1752
1753    pub(crate) fn maximum_number_nsz(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1754        let call = self.call_intrinsic("llvm.maximumnum", &[self.val_ty(lhs)], &[lhs, rhs]);
1755        unsafe { llvm::LLVMRustSetNoSignedZeros(call) };
1756        call
1757    }
1758
1759    pub(crate) fn insert_element(
1760        &mut self,
1761        vec: &'ll Value,
1762        elt: &'ll Value,
1763        idx: &'ll Value,
1764    ) -> &'ll Value {
1765        unsafe { llvm::LLVMBuildInsertElement(self.llbuilder, vec, elt, idx, UNNAMED) }
1766    }
1767
1768    pub(crate) fn shuffle_vector(
1769        &mut self,
1770        v1: &'ll Value,
1771        v2: &'ll Value,
1772        mask: &'ll Value,
1773    ) -> &'ll Value {
1774        unsafe { llvm::LLVMBuildShuffleVector(self.llbuilder, v1, v2, mask, UNNAMED) }
1775    }
1776
1777    pub(crate) fn vector_reduce_fadd(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1778        self.call_intrinsic("llvm.vector.reduce.fadd", &[self.val_ty(src)], &[acc, src])
1779    }
1780    pub(crate) fn vector_reduce_fmul(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1781        self.call_intrinsic("llvm.vector.reduce.fmul", &[self.val_ty(src)], &[acc, src])
1782    }
1783    pub(crate) fn vector_reduce_fadd_reassoc(
1784        &mut self,
1785        acc: &'ll Value,
1786        src: &'ll Value,
1787    ) -> &'ll Value {
1788        unsafe {
1789            let instr =
1790                self.call_intrinsic("llvm.vector.reduce.fadd", &[self.val_ty(src)], &[acc, src]);
1791            llvm::LLVMRustSetAllowReassoc(instr);
1792            instr
1793        }
1794    }
1795    pub(crate) fn vector_reduce_fmul_reassoc(
1796        &mut self,
1797        acc: &'ll Value,
1798        src: &'ll Value,
1799    ) -> &'ll Value {
1800        unsafe {
1801            let instr =
1802                self.call_intrinsic("llvm.vector.reduce.fmul", &[self.val_ty(src)], &[acc, src]);
1803            llvm::LLVMRustSetAllowReassoc(instr);
1804            instr
1805        }
1806    }
1807    pub(crate) fn vector_reduce_add(&mut self, src: &'ll Value) -> &'ll Value {
1808        self.call_intrinsic("llvm.vector.reduce.add", &[self.val_ty(src)], &[src])
1809    }
1810    pub(crate) fn vector_reduce_mul(&mut self, src: &'ll Value) -> &'ll Value {
1811        self.call_intrinsic("llvm.vector.reduce.mul", &[self.val_ty(src)], &[src])
1812    }
1813    pub(crate) fn vector_reduce_and(&mut self, src: &'ll Value) -> &'ll Value {
1814        self.call_intrinsic("llvm.vector.reduce.and", &[self.val_ty(src)], &[src])
1815    }
1816    pub(crate) fn vector_reduce_or(&mut self, src: &'ll Value) -> &'ll Value {
1817        self.call_intrinsic("llvm.vector.reduce.or", &[self.val_ty(src)], &[src])
1818    }
1819    pub(crate) fn vector_reduce_xor(&mut self, src: &'ll Value) -> &'ll Value {
1820        self.call_intrinsic("llvm.vector.reduce.xor", &[self.val_ty(src)], &[src])
1821    }
1822    pub(crate) fn vector_reduce_min(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1823        self.call_intrinsic(
1824            if is_signed { "llvm.vector.reduce.smin" } else { "llvm.vector.reduce.umin" },
1825            &[self.val_ty(src)],
1826            &[src],
1827        )
1828    }
1829    pub(crate) fn vector_reduce_max(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1830        self.call_intrinsic(
1831            if is_signed { "llvm.vector.reduce.smax" } else { "llvm.vector.reduce.umax" },
1832            &[self.val_ty(src)],
1833            &[src],
1834        )
1835    }
1836}
1837impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1838    pub(crate) fn add_clause(&mut self, landing_pad: &'ll Value, clause: &'ll Value) {
1839        unsafe {
1840            llvm::LLVMAddClause(landing_pad, clause);
1841        }
1842    }
1843
1844    pub(crate) fn catch_ret(
1845        &mut self,
1846        funclet: &Funclet<'ll>,
1847        unwind: &'ll BasicBlock,
1848    ) -> &'ll Value {
1849        let ret = unsafe { llvm::LLVMBuildCatchRet(self.llbuilder, funclet.cleanuppad(), unwind) };
1850        ret.expect("LLVM does not have support for catchret")
1851    }
1852
1853    pub(crate) fn check_call<'b>(
1854        &mut self,
1855        typ: &str,
1856        fn_ty: &'ll Type,
1857        llfn: &'ll Value,
1858        args: &'b [&'ll Value],
1859    ) -> Cow<'b, [&'ll Value]> {
1860        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!(
1861            self.cx.type_kind(fn_ty) == TypeKind::Function,
1862            "builder::{typ} not passed a function, but {fn_ty:?}"
1863        );
1864
1865        let param_tys = self.cx.func_params_types(fn_ty);
1866
1867        let all_args_match = iter::zip(&param_tys, args.iter().map(|&v| self.cx.val_ty(v)))
1868            .all(|(expected_ty, actual_ty)| *expected_ty == actual_ty);
1869
1870        if all_args_match {
1871            return Cow::Borrowed(args);
1872        }
1873
1874        let casted_args: Vec<_> = iter::zip(param_tys, args)
1875            .enumerate()
1876            .map(|(i, (expected_ty, &actual_val))| {
1877                let actual_ty = self.cx.val_ty(actual_val);
1878                if expected_ty != actual_ty {
1879                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_codegen_llvm/src/builder.rs:1879",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(1879u32),
                        ::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!(
1880                        "type mismatch in function call of {:?}. \
1881                            Expected {:?} for param {}, got {:?}; injecting bitcast",
1882                        llfn, expected_ty, i, actual_ty
1883                    );
1884                    self.bitcast(actual_val, expected_ty)
1885                } else {
1886                    actual_val
1887                }
1888            })
1889            .collect();
1890
1891        Cow::Owned(casted_args)
1892    }
1893
1894    pub(crate) fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
1895        unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
1896    }
1897}
1898
1899impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1900    pub(crate) fn call_intrinsic(
1901        &mut self,
1902        base_name: impl Into<Cow<'static, str>>,
1903        type_params: &[&'ll Type],
1904        args: &[&'ll Value],
1905    ) -> &'ll Value {
1906        let (ty, f) = self.cx.get_intrinsic(base_name.into(), type_params);
1907        // No LLVM intrinsic returns its data indirectly (via `sret`).
1908        self.call(ty, None, None, f, ReturnSlot::Direct, args, None, None)
1909    }
1910
1911    fn call_lifetime_intrinsic(&mut self, intrinsic: &'static str, ptr: &'ll Value, size: Size) {
1912        let size = size.bytes();
1913        if size == 0 {
1914            return;
1915        }
1916
1917        if !self.cx().sess().emit_lifetime_markers() {
1918            return;
1919        }
1920
1921        if crate::llvm_util::get_version() >= (22, 0, 0) {
1922            // LLVM 22 requires the lifetime intrinsic to act directly on the alloca,
1923            // there can't be an addrspacecast in between.
1924            let ptr = unsafe { llvm::LLVMRustStripPointerCasts(ptr) };
1925            self.call_intrinsic(intrinsic, &[self.val_ty(ptr)], &[ptr]);
1926        } else {
1927            self.call_intrinsic(intrinsic, &[self.val_ty(ptr)], &[self.cx.const_u64(size), ptr]);
1928        }
1929    }
1930}
1931impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1932    pub(crate) fn phi(
1933        &mut self,
1934        ty: &'ll Type,
1935        vals: &[&'ll Value],
1936        bbs: &[&'ll BasicBlock],
1937    ) -> &'ll Value {
1938        {
    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());
1939        let phi = unsafe { llvm::LLVMBuildPhi(self.llbuilder, ty, UNNAMED) };
1940        unsafe {
1941            llvm::LLVMAddIncoming(phi, vals.as_ptr(), bbs.as_ptr(), vals.len() as c_uint);
1942            phi
1943        }
1944    }
1945
1946    fn add_incoming_to_phi(&mut self, phi: &'ll Value, val: &'ll Value, bb: &'ll BasicBlock) {
1947        unsafe {
1948            llvm::LLVMAddIncoming(phi, &val, &bb, 1 as c_uint);
1949        }
1950    }
1951}
1952impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1953    pub(crate) fn landing_pad(
1954        &mut self,
1955        ty: &'ll Type,
1956        pers_fn: &'ll Value,
1957        num_clauses: usize,
1958    ) -> &'ll Value {
1959        // Use LLVMSetPersonalityFn to set the personality. It supports arbitrary Consts while,
1960        // LLVMBuildLandingPad requires the argument to be a Function (as of LLVM 12). The
1961        // personality lives on the parent function anyway.
1962        self.set_personality_fn(pers_fn);
1963        unsafe {
1964            llvm::LLVMBuildLandingPad(self.llbuilder, ty, None, num_clauses as c_uint, UNNAMED)
1965        }
1966    }
1967
1968    pub(crate) fn callbr(
1969        &mut self,
1970        llty: &'ll Type,
1971        fn_attrs: Option<&CodegenFnAttrs>,
1972        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1973        llfn: &'ll Value,
1974        args: &[&'ll Value],
1975        default_dest: &'ll BasicBlock,
1976        indirect_dest: &[&'ll BasicBlock],
1977        funclet: Option<&Funclet<'ll>>,
1978        instance: Option<Instance<'tcx>>,
1979    ) -> &'ll Value {
1980        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_codegen_llvm/src/builder.rs:1980",
                        "rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_codegen_llvm/src/builder.rs"),
                        ::tracing_core::__macro_support::Option::Some(1980u32),
                        ::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);
1981
1982        let args = self.check_call("callbr", llty, llfn, args);
1983        let funclet_bundle = funclet.map(|funclet| funclet.bundle());
1984        let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
1985        if let Some(funclet_bundle) = funclet_bundle {
1986            bundles.push(funclet_bundle);
1987        }
1988
1989        // Emit CFI pointer type membership test
1990        self.cfi_type_test(fn_attrs, fn_abi, instance, llfn);
1991
1992        // Emit KCFI operand bundle
1993        let kcfi_bundle = self.kcfi_operand_bundle(fn_attrs, fn_abi, instance, llfn);
1994        if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|bundle| bundle.as_ref()) {
1995            bundles.push(kcfi_bundle);
1996        }
1997
1998        let pauth = self.ptrauth_operand_bundle(llfn, fn_abi);
1999        if let Some(p) = pauth.as_ref().map(|b| b.as_ref()) {
2000            bundles.push(p);
2001        }
2002
2003        let callbr = unsafe {
2004            llvm::LLVMBuildCallBr(
2005                self.llbuilder,
2006                llty,
2007                llfn,
2008                default_dest,
2009                indirect_dest.as_ptr(),
2010                indirect_dest.len() as c_uint,
2011                args.as_ptr(),
2012                args.len() as c_uint,
2013                bundles.as_ptr(),
2014                bundles.len() as c_uint,
2015                UNNAMED,
2016            )
2017        };
2018        if let Some(fn_abi) = fn_abi {
2019            fn_abi.apply_attrs_callsite(self, callbr);
2020        }
2021        callbr
2022    }
2023
2024    // Emits CFI pointer type membership tests.
2025    fn cfi_type_test(
2026        &mut self,
2027        fn_attrs: Option<&CodegenFnAttrs>,
2028        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
2029        instance: Option<Instance<'tcx>>,
2030        llfn: &'ll Value,
2031    ) {
2032        let is_indirect_call = unsafe { llvm::LLVMRustIsNonGVFunctionPointerTy(llfn) };
2033        if self.tcx.sess.is_sanitizer_cfi_enabled()
2034            && let Some(fn_abi) = fn_abi
2035            && is_indirect_call
2036        {
2037            if let Some(fn_attrs) = fn_attrs
2038                && fn_attrs.sanitizers.disabled.contains(SanitizerSet::CFI)
2039            {
2040                return;
2041            }
2042            if crate::llvm::HasStringAttribute(self.llfn(), "no-sanitize-cfi") {
2043                return;
2044            }
2045
2046            let mut options = cfi::TypeIdOptions::empty();
2047            if self.tcx.sess.is_sanitizer_cfi_generalize_pointers_enabled() {
2048                options.insert(cfi::TypeIdOptions::GENERALIZE_POINTERS);
2049            }
2050            if self.tcx.sess.is_sanitizer_cfi_normalize_integers_enabled() {
2051                options.insert(cfi::TypeIdOptions::NORMALIZE_INTEGERS);
2052            }
2053
2054            if self.cx.is_sanitizer_type_ignored(c"cfi", fn_abi) {
2055                return;
2056            }
2057
2058            let typeid = if let Some(instance) = instance {
2059                cfi::typeid_for_instance(self.tcx, instance, options)
2060            } else {
2061                cfi::typeid_for_fnabi(self.tcx, fn_abi, options)
2062            };
2063            let typeid_metadata = self.cx.create_metadata(typeid.as_bytes());
2064            let dbg_loc = self.get_dbg_loc();
2065
2066            // Test whether the function pointer is associated with the type identifier using the
2067            // llvm.type.test intrinsic. The LowerTypeTests link-time optimization pass replaces
2068            // calls to this intrinsic with code to test type membership.
2069            let typeid = self.get_metadata_value(typeid_metadata);
2070            let cond = self.call_intrinsic("llvm.type.test", &[], &[llfn, typeid]);
2071            let bb_pass = self.append_sibling_block("type_test.pass");
2072            let bb_fail = self.append_sibling_block("type_test.fail");
2073            self.cond_br(cond, bb_pass, bb_fail);
2074
2075            self.switch_to_block(bb_fail);
2076            if let Some(dbg_loc) = dbg_loc {
2077                self.set_dbg_loc(dbg_loc);
2078            }
2079
2080            let is_diag = self.tcx.sess.opts.unstable_opts.sanitizer_cfi_diag.unwrap_or(false);
2081            let is_recover =
2082                self.tcx.sess.opts.unstable_opts.sanitizer_cfi_recover.unwrap_or(false);
2083
2084            if is_diag || is_recover {
2085                let fty = self.cx.type_func(
2086                    &[self.cx.type_ptr(), self.cx.type_isize(), self.cx.type_isize()],
2087                    self.cx.type_void(),
2088                );
2089                let ubsan_handler = self.declare_cfn(
2090                    if is_recover {
2091                        "__ubsan_handle_cfi_check_fail"
2092                    } else {
2093                        "__ubsan_handle_cfi_check_fail_abort"
2094                    },
2095                    llvm::UnnamedAddr::Global,
2096                    fty,
2097                );
2098
2099                let mut expected_ty = String::from("fn(");
2100                for (i, arg) in fn_abi.args.iter().enumerate() {
2101                    if i > 0 {
2102                        expected_ty.push_str(", ");
2103                    }
2104                    use std::fmt::Write;
2105                    (&mut expected_ty).write_fmt(format_args!("{0}", arg.layout.ty))write!(&mut expected_ty, "{}", arg.layout.ty).unwrap();
2106                }
2107                expected_ty.push(')');
2108                if !fn_abi.ret.layout.ty.is_unit() {
2109                    use std::fmt::Write;
2110                    (&mut expected_ty).write_fmt(format_args!(" -> {0}", fn_abi.ret.layout.ty))write!(&mut expected_ty, " -> {}", fn_abi.ret.layout.ty).unwrap();
2111                }
2112
2113                // 4 for cfi-icall (indirect call)
2114                let check_kind = 4;
2115                let diag_data =
2116                    self.generate_ubsan_cfi_diag_data(self.span, expected_ty, check_kind);
2117
2118                let function_address = self.ptrtoint(llfn, self.cx.type_isize());
2119                self.call(
2120                    fty,
2121                    None,
2122                    None,
2123                    ubsan_handler,
2124                    ReturnSlot::Direct,
2125                    &[diag_data, function_address, self.const_usize(0)],
2126                    None,
2127                    None,
2128                );
2129                if is_recover {
2130                    self.br(bb_pass);
2131                } else {
2132                    self.unreachable();
2133                }
2134            } else {
2135                self.abort();
2136                self.unreachable();
2137            }
2138
2139            self.switch_to_block(bb_pass);
2140            if let Some(dbg_loc) = dbg_loc {
2141                self.set_dbg_loc(dbg_loc);
2142            }
2143        }
2144    }
2145
2146    // Emits KCFI operand bundles.
2147    fn kcfi_operand_bundle(
2148        &mut self,
2149        fn_attrs: Option<&CodegenFnAttrs>,
2150        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
2151        instance: Option<Instance<'tcx>>,
2152        llfn: &'ll Value,
2153    ) -> Option<llvm::OperandBundleBox<'ll>> {
2154        let is_indirect_call = unsafe { llvm::LLVMRustIsNonGVFunctionPointerTy(llfn) };
2155        let kcfi_bundle = if self.tcx.sess.is_sanitizer_kcfi_enabled()
2156            && let Some(fn_abi) = fn_abi
2157            && is_indirect_call
2158        {
2159            if let Some(fn_attrs) = fn_attrs
2160                && fn_attrs.sanitizers.disabled.contains(SanitizerSet::KCFI)
2161            {
2162                return None;
2163            }
2164            if crate::llvm::HasStringAttribute(self.llfn(), "no-sanitize-kcfi") {
2165                return None;
2166            }
2167
2168            let mut options = kcfi::TypeIdOptions::empty();
2169            if self.tcx.sess.is_sanitizer_cfi_generalize_pointers_enabled() {
2170                options.insert(kcfi::TypeIdOptions::GENERALIZE_POINTERS);
2171            }
2172            if self.tcx.sess.is_sanitizer_cfi_normalize_integers_enabled() {
2173                options.insert(kcfi::TypeIdOptions::NORMALIZE_INTEGERS);
2174            }
2175
2176            if self.cx.is_sanitizer_type_ignored(c"kcfi", fn_abi) {
2177                return None;
2178            }
2179
2180            let kcfi_typeid = if let Some(instance) = instance {
2181                kcfi::typeid_for_instance(self.tcx, instance, options)
2182            } else {
2183                kcfi::typeid_for_fnabi(self.tcx, fn_abi, options)
2184            };
2185
2186            Some(llvm::OperandBundleBox::new("kcfi", &[self.const_u32(kcfi_typeid)]))
2187        } else {
2188            None
2189        };
2190        kcfi_bundle
2191    }
2192
2193    // Emits pauth operand bundle.
2194    fn ptrauth_operand_bundle(
2195        &mut self,
2196        llfn: &'ll Value,
2197        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
2198    ) -> Option<llvm::OperandBundleBox<'ll>> {
2199        if self.sess().pointer_authentication_functions().is_none() {
2200            return None;
2201        }
2202        // Pointer authentication support is currently limited to extern "C" calls; filter out other
2203        // ABIs.
2204        if fn_abi?.conv != CanonAbi::C {
2205            return None;
2206        }
2207        // Filter out LLVM intrinsics.
2208        if llvm::get_value_name(llfn).starts_with(b"llvm.") {
2209            return None;
2210        }
2211
2212        // FIXME(jchlanda) Operand bundles should only be attached to indirect function calls.
2213        // However, function pointer signing is currently performed in `get_fn_addr`, which causes
2214        // the logic to be applied too broadly, including to function values (not just pointers).
2215        // As a result, direct calls using signed function values must also receive operand
2216        // bundles.
2217        // Once this is resolved, we should analyze each call and skip direct calls. See the
2218        // discussion in the rust-lang issue: <https://github.com/rust-lang/rust/issues/152532>
2219        let key: u32 = 0;
2220        let discriminator: u64 = 0;
2221        Some(llvm::OperandBundleBox::new(
2222            "ptrauth",
2223            &[self.const_u32(key), self.const_u64(discriminator)],
2224        ))
2225    }
2226
2227    /// Emits a call to `llvm.instrprof.increment`. Used by coverage instrumentation.
2228    {}
#[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/809936eac66c547a5127ce1da805f0d3a6789b98/compiler/rustc_codegen_llvm/src/builder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2228u32),
                                    ::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))]
2229    pub(crate) fn instrprof_increment(
2230        &mut self,
2231        fn_name: &'ll Value,
2232        hash: &'ll Value,
2233        num_counters: &'ll Value,
2234        index: &'ll Value,
2235    ) {
2236        self.call_intrinsic("llvm.instrprof.increment", &[], &[fn_name, hash, num_counters, index]);
2237    }
2238}