rustc_codegen_llvm/
builder.rs

1use std::borrow::{Borrow, Cow};
2use std::ops::Deref;
3use std::{iter, ptr};
4
5pub(crate) mod autodiff;
6pub(crate) mod gpu_offload;
7
8use libc::{c_char, c_uint, size_t};
9use rustc_abi as abi;
10use rustc_abi::{Align, 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::def_id::DefId;
18use rustc_middle::bug;
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::{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, GEPNoWrapFlags, Metadata, TRUE, ToLlvmBool,
39};
40use crate::type_::Type;
41use crate::type_of::LayoutLlvmExt;
42use crate::value::Value;
43
44#[must_use]
45pub(crate) struct GenericBuilder<'a, 'll, CX: Borrow<SCx<'ll>>> {
46    pub llbuilder: &'ll mut llvm::Builder<'ll>,
47    pub cx: &'a GenericCx<'ll, CX>,
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        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 }
99    }
100
101    pub(crate) fn bitcast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
102        unsafe { llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty, UNNAMED) }
103    }
104
105    pub(crate) fn ret_void(&mut self) {
106        llvm::LLVMBuildRetVoid(self.llbuilder);
107    }
108
109    pub(crate) fn ret(&mut self, v: &'ll Value) {
110        unsafe {
111            llvm::LLVMBuildRet(self.llbuilder, v);
112        }
113    }
114
115    pub(crate) fn build(cx: &'a GenericCx<'ll, CX>, llbb: &'ll BasicBlock) -> Self {
116        let bx = Self::with_cx(cx);
117        unsafe {
118            llvm::LLVMPositionBuilderAtEnd(bx.llbuilder, llbb);
119        }
120        bx
121    }
122
123    // The generic builder has less functionality and thus (unlike the other alloca) we can not
124    // easily jump to the beginning of the function to place our allocas there. We trust the user
125    // to manually do that. FIXME(offload): improve the genericCx and add more llvm wrappers to
126    // handle this.
127    pub(crate) fn direct_alloca(&mut self, ty: &'ll Type, align: Align, name: &str) -> &'ll Value {
128        let val = unsafe {
129            let alloca = llvm::LLVMBuildAlloca(self.llbuilder, ty, UNNAMED);
130            llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
131            // Cast to default addrspace if necessary
132            llvm::LLVMBuildPointerCast(self.llbuilder, alloca, self.cx.type_ptr(), UNNAMED)
133        };
134        if name != "" {
135            let name = std::ffi::CString::new(name).unwrap();
136            llvm::set_value_name(val, &name.as_bytes());
137        }
138        val
139    }
140
141    pub(crate) fn inbounds_gep(
142        &mut self,
143        ty: &'ll Type,
144        ptr: &'ll Value,
145        indices: &[&'ll Value],
146    ) -> &'ll Value {
147        unsafe {
148            llvm::LLVMBuildGEPWithNoWrapFlags(
149                self.llbuilder,
150                ty,
151                ptr,
152                indices.as_ptr(),
153                indices.len() as c_uint,
154                UNNAMED,
155                GEPNoWrapFlags::InBounds,
156            )
157        }
158    }
159
160    pub(crate) fn store(&mut self, val: &'ll Value, ptr: &'ll Value, align: Align) -> &'ll Value {
161        debug!("Store {:?} -> {:?}", val, ptr);
162        assert_eq!(self.cx.type_kind(self.cx.val_ty(ptr)), TypeKind::Pointer);
163        unsafe {
164            let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
165            llvm::LLVMSetAlignment(store, align.bytes() as c_uint);
166            store
167        }
168    }
169
170    pub(crate) fn load(&mut self, ty: &'ll Type, ptr: &'ll Value, align: Align) -> &'ll Value {
171        unsafe {
172            let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
173            llvm::LLVMSetAlignment(load, align.bytes() as c_uint);
174            load
175        }
176    }
177
178    fn memset(&mut self, ptr: &'ll Value, fill_byte: &'ll Value, size: &'ll Value, align: Align) {
179        unsafe {
180            llvm::LLVMRustBuildMemSet(
181                self.llbuilder,
182                ptr,
183                align.bytes() as c_uint,
184                fill_byte,
185                size,
186                false,
187            );
188        }
189    }
190}
191
192/// Empty string, to be used where LLVM expects an instruction name, indicating
193/// that the instruction is to be left unnamed (i.e. numbered, in textual IR).
194// FIXME(eddyb) pass `&CStr` directly to FFI once it's a thin pointer.
195pub(crate) const UNNAMED: *const c_char = c"".as_ptr();
196
197impl<'ll, CX: Borrow<SCx<'ll>>> BackendTypes for GenericBuilder<'_, 'll, CX> {
198    type Value = <GenericCx<'ll, CX> as BackendTypes>::Value;
199    type Metadata = <GenericCx<'ll, CX> as BackendTypes>::Metadata;
200    type Function = <GenericCx<'ll, CX> as BackendTypes>::Function;
201    type BasicBlock = <GenericCx<'ll, CX> as BackendTypes>::BasicBlock;
202    type Type = <GenericCx<'ll, CX> as BackendTypes>::Type;
203    type Funclet = <GenericCx<'ll, CX> as BackendTypes>::Funclet;
204
205    type DIScope = <GenericCx<'ll, CX> as BackendTypes>::DIScope;
206    type DILocation = <GenericCx<'ll, CX> as BackendTypes>::DILocation;
207    type DIVariable = <GenericCx<'ll, CX> as BackendTypes>::DIVariable;
208}
209
210impl abi::HasDataLayout for Builder<'_, '_, '_> {
211    fn data_layout(&self) -> &abi::TargetDataLayout {
212        self.cx.data_layout()
213    }
214}
215
216impl<'tcx> ty::layout::HasTyCtxt<'tcx> for Builder<'_, '_, 'tcx> {
217    #[inline]
218    fn tcx(&self) -> TyCtxt<'tcx> {
219        self.cx.tcx
220    }
221}
222
223impl<'tcx> ty::layout::HasTypingEnv<'tcx> for Builder<'_, '_, 'tcx> {
224    fn typing_env(&self) -> ty::TypingEnv<'tcx> {
225        self.cx.typing_env()
226    }
227}
228
229impl HasTargetSpec for Builder<'_, '_, '_> {
230    #[inline]
231    fn target_spec(&self) -> &Target {
232        self.cx.target_spec()
233    }
234}
235
236impl<'tcx> LayoutOfHelpers<'tcx> for Builder<'_, '_, 'tcx> {
237    #[inline]
238    fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
239        self.cx.handle_layout_err(err, span, ty)
240    }
241}
242
243impl<'tcx> FnAbiOfHelpers<'tcx> for Builder<'_, '_, 'tcx> {
244    #[inline]
245    fn handle_fn_abi_err(
246        &self,
247        err: FnAbiError<'tcx>,
248        span: Span,
249        fn_abi_request: FnAbiRequest<'tcx>,
250    ) -> ! {
251        self.cx.handle_fn_abi_err(err, span, fn_abi_request)
252    }
253}
254
255impl<'ll, 'tcx> Deref for Builder<'_, 'll, 'tcx> {
256    type Target = CodegenCx<'ll, 'tcx>;
257
258    #[inline]
259    fn deref(&self) -> &Self::Target {
260        self.cx
261    }
262}
263
264macro_rules! math_builder_methods {
265    ($($name:ident($($arg:ident),*) => $llvm_capi:ident),+ $(,)?) => {
266        $(fn $name(&mut self, $($arg: &'ll Value),*) -> &'ll Value {
267            unsafe {
268                llvm::$llvm_capi(self.llbuilder, $($arg,)* UNNAMED)
269            }
270        })+
271    }
272}
273
274macro_rules! set_math_builder_methods {
275    ($($name:ident($($arg:ident),*) => ($llvm_capi:ident, $llvm_set_math:ident)),+ $(,)?) => {
276        $(fn $name(&mut self, $($arg: &'ll Value),*) -> &'ll Value {
277            unsafe {
278                let instr = llvm::$llvm_capi(self.llbuilder, $($arg,)* UNNAMED);
279                llvm::$llvm_set_math(instr);
280                instr
281            }
282        })+
283    }
284}
285
286impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> {
287    type CodegenCx = CodegenCx<'ll, 'tcx>;
288
289    fn build(cx: &'a CodegenCx<'ll, 'tcx>, llbb: &'ll BasicBlock) -> Self {
290        let bx = Builder::with_cx(cx);
291        unsafe {
292            llvm::LLVMPositionBuilderAtEnd(bx.llbuilder, llbb);
293        }
294        bx
295    }
296
297    fn cx(&self) -> &CodegenCx<'ll, 'tcx> {
298        self.cx
299    }
300
301    fn llbb(&self) -> &'ll BasicBlock {
302        unsafe { llvm::LLVMGetInsertBlock(self.llbuilder) }
303    }
304
305    fn set_span(&mut self, _span: Span) {}
306
307    fn append_block(cx: &'a CodegenCx<'ll, 'tcx>, llfn: &'ll Value, name: &str) -> &'ll BasicBlock {
308        unsafe {
309            let name = SmallCStr::new(name);
310            llvm::LLVMAppendBasicBlockInContext(cx.llcx, llfn, name.as_ptr())
311        }
312    }
313
314    fn append_sibling_block(&mut self, name: &str) -> &'ll BasicBlock {
315        Self::append_block(self.cx, self.llfn(), name)
316    }
317
318    fn switch_to_block(&mut self, llbb: Self::BasicBlock) {
319        *self = Self::build(self.cx, llbb)
320    }
321
322    fn ret_void(&mut self) {
323        llvm::LLVMBuildRetVoid(self.llbuilder);
324    }
325
326    fn ret(&mut self, v: &'ll Value) {
327        unsafe {
328            llvm::LLVMBuildRet(self.llbuilder, v);
329        }
330    }
331
332    fn br(&mut self, dest: &'ll BasicBlock) {
333        unsafe {
334            llvm::LLVMBuildBr(self.llbuilder, dest);
335        }
336    }
337
338    fn cond_br(
339        &mut self,
340        cond: &'ll Value,
341        then_llbb: &'ll BasicBlock,
342        else_llbb: &'ll BasicBlock,
343    ) {
344        unsafe {
345            llvm::LLVMBuildCondBr(self.llbuilder, cond, then_llbb, else_llbb);
346        }
347    }
348
349    fn switch(
350        &mut self,
351        v: &'ll Value,
352        else_llbb: &'ll BasicBlock,
353        cases: impl ExactSizeIterator<Item = (u128, &'ll BasicBlock)>,
354    ) {
355        let switch =
356            unsafe { llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, cases.len() as c_uint) };
357        for (on_val, dest) in cases {
358            let on_val = self.const_uint_big(self.val_ty(v), on_val);
359            unsafe { llvm::LLVMAddCase(switch, on_val, dest) }
360        }
361    }
362
363    fn switch_with_weights(
364        &mut self,
365        v: Self::Value,
366        else_llbb: Self::BasicBlock,
367        else_is_cold: bool,
368        cases: impl ExactSizeIterator<Item = (u128, Self::BasicBlock, bool)>,
369    ) {
370        if self.cx.sess().opts.optimize == rustc_session::config::OptLevel::No {
371            self.switch(v, else_llbb, cases.map(|(val, dest, _)| (val, dest)));
372            return;
373        }
374
375        let id = self.cx.create_metadata(b"branch_weights");
376
377        // For switch instructions with 2 targets, the `llvm.expect` intrinsic is used.
378        // This function handles switch instructions with more than 2 targets and it needs to
379        // emit branch weights metadata instead of using the intrinsic.
380        // The values 1 and 2000 are the same as the values used by the `llvm.expect` intrinsic.
381        let cold_weight = llvm::LLVMValueAsMetadata(self.cx.const_u32(1));
382        let hot_weight = llvm::LLVMValueAsMetadata(self.cx.const_u32(2000));
383        let weight =
384            |is_cold: bool| -> &Metadata { if is_cold { cold_weight } else { hot_weight } };
385
386        let mut md: SmallVec<[&Metadata; 16]> = SmallVec::with_capacity(cases.len() + 2);
387        md.push(id);
388        md.push(weight(else_is_cold));
389
390        let switch =
391            unsafe { llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, cases.len() as c_uint) };
392        for (on_val, dest, is_cold) in cases {
393            let on_val = self.const_uint_big(self.val_ty(v), on_val);
394            unsafe { llvm::LLVMAddCase(switch, on_val, dest) }
395            md.push(weight(is_cold));
396        }
397
398        unsafe {
399            let md_node = llvm::LLVMMDNodeInContext2(self.cx.llcx, md.as_ptr(), md.len() as size_t);
400            self.cx.set_metadata(switch, llvm::MD_prof, md_node);
401        }
402    }
403
404    fn invoke(
405        &mut self,
406        llty: &'ll Type,
407        fn_attrs: Option<&CodegenFnAttrs>,
408        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
409        llfn: &'ll Value,
410        args: &[&'ll Value],
411        then: &'ll BasicBlock,
412        catch: &'ll BasicBlock,
413        funclet: Option<&Funclet<'ll>>,
414        instance: Option<Instance<'tcx>>,
415    ) -> &'ll Value {
416        debug!("invoke {:?} with args ({:?})", llfn, args);
417
418        let args = self.check_call("invoke", llty, llfn, args);
419        let funclet_bundle = funclet.map(|funclet| funclet.bundle());
420        let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
421        if let Some(funclet_bundle) = funclet_bundle {
422            bundles.push(funclet_bundle);
423        }
424
425        // Emit CFI pointer type membership test
426        self.cfi_type_test(fn_attrs, fn_abi, instance, llfn);
427
428        // Emit KCFI operand bundle
429        let kcfi_bundle = self.kcfi_operand_bundle(fn_attrs, fn_abi, instance, llfn);
430        if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
431            bundles.push(kcfi_bundle);
432        }
433
434        let invoke = unsafe {
435            llvm::LLVMBuildInvokeWithOperandBundles(
436                self.llbuilder,
437                llty,
438                llfn,
439                args.as_ptr(),
440                args.len() as c_uint,
441                then,
442                catch,
443                bundles.as_ptr(),
444                bundles.len() as c_uint,
445                UNNAMED,
446            )
447        };
448        if let Some(fn_abi) = fn_abi {
449            fn_abi.apply_attrs_callsite(self, invoke);
450        }
451        invoke
452    }
453
454    fn unreachable(&mut self) {
455        unsafe {
456            llvm::LLVMBuildUnreachable(self.llbuilder);
457        }
458    }
459
460    math_builder_methods! {
461        add(a, b) => LLVMBuildAdd,
462        fadd(a, b) => LLVMBuildFAdd,
463        sub(a, b) => LLVMBuildSub,
464        fsub(a, b) => LLVMBuildFSub,
465        mul(a, b) => LLVMBuildMul,
466        fmul(a, b) => LLVMBuildFMul,
467        udiv(a, b) => LLVMBuildUDiv,
468        exactudiv(a, b) => LLVMBuildExactUDiv,
469        sdiv(a, b) => LLVMBuildSDiv,
470        exactsdiv(a, b) => LLVMBuildExactSDiv,
471        fdiv(a, b) => LLVMBuildFDiv,
472        urem(a, b) => LLVMBuildURem,
473        srem(a, b) => LLVMBuildSRem,
474        frem(a, b) => LLVMBuildFRem,
475        shl(a, b) => LLVMBuildShl,
476        lshr(a, b) => LLVMBuildLShr,
477        ashr(a, b) => LLVMBuildAShr,
478        and(a, b) => LLVMBuildAnd,
479        or(a, b) => LLVMBuildOr,
480        xor(a, b) => LLVMBuildXor,
481        neg(x) => LLVMBuildNeg,
482        fneg(x) => LLVMBuildFNeg,
483        not(x) => LLVMBuildNot,
484        unchecked_sadd(x, y) => LLVMBuildNSWAdd,
485        unchecked_uadd(x, y) => LLVMBuildNUWAdd,
486        unchecked_ssub(x, y) => LLVMBuildNSWSub,
487        unchecked_usub(x, y) => LLVMBuildNUWSub,
488        unchecked_smul(x, y) => LLVMBuildNSWMul,
489        unchecked_umul(x, y) => LLVMBuildNUWMul,
490    }
491
492    fn unchecked_suadd(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
493        unsafe {
494            let add = llvm::LLVMBuildAdd(self.llbuilder, a, b, UNNAMED);
495            if llvm::LLVMIsAInstruction(add).is_some() {
496                llvm::LLVMSetNUW(add, TRUE);
497                llvm::LLVMSetNSW(add, TRUE);
498            }
499            add
500        }
501    }
502    fn unchecked_susub(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
503        unsafe {
504            let sub = llvm::LLVMBuildSub(self.llbuilder, a, b, UNNAMED);
505            if llvm::LLVMIsAInstruction(sub).is_some() {
506                llvm::LLVMSetNUW(sub, TRUE);
507                llvm::LLVMSetNSW(sub, TRUE);
508            }
509            sub
510        }
511    }
512    fn unchecked_sumul(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
513        unsafe {
514            let mul = llvm::LLVMBuildMul(self.llbuilder, a, b, UNNAMED);
515            if llvm::LLVMIsAInstruction(mul).is_some() {
516                llvm::LLVMSetNUW(mul, TRUE);
517                llvm::LLVMSetNSW(mul, TRUE);
518            }
519            mul
520        }
521    }
522
523    fn or_disjoint(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
524        unsafe {
525            let or = llvm::LLVMBuildOr(self.llbuilder, a, b, UNNAMED);
526
527            // If a and b are both values, then `or` is a value, rather than
528            // an instruction, so we need to check before setting the flag.
529            // (See also `LLVMBuildNUWNeg` which also needs a check.)
530            if llvm::LLVMIsAInstruction(or).is_some() {
531                llvm::LLVMSetIsDisjoint(or, TRUE);
532            }
533            or
534        }
535    }
536
537    set_math_builder_methods! {
538        fadd_fast(x, y) => (LLVMBuildFAdd, LLVMRustSetFastMath),
539        fsub_fast(x, y) => (LLVMBuildFSub, LLVMRustSetFastMath),
540        fmul_fast(x, y) => (LLVMBuildFMul, LLVMRustSetFastMath),
541        fdiv_fast(x, y) => (LLVMBuildFDiv, LLVMRustSetFastMath),
542        frem_fast(x, y) => (LLVMBuildFRem, LLVMRustSetFastMath),
543        fadd_algebraic(x, y) => (LLVMBuildFAdd, LLVMRustSetAlgebraicMath),
544        fsub_algebraic(x, y) => (LLVMBuildFSub, LLVMRustSetAlgebraicMath),
545        fmul_algebraic(x, y) => (LLVMBuildFMul, LLVMRustSetAlgebraicMath),
546        fdiv_algebraic(x, y) => (LLVMBuildFDiv, LLVMRustSetAlgebraicMath),
547        frem_algebraic(x, y) => (LLVMBuildFRem, LLVMRustSetAlgebraicMath),
548    }
549
550    fn checked_binop(
551        &mut self,
552        oop: OverflowOp,
553        ty: Ty<'tcx>,
554        lhs: Self::Value,
555        rhs: Self::Value,
556    ) -> (Self::Value, Self::Value) {
557        let (size, signed) = ty.int_size_and_signed(self.tcx);
558        let width = size.bits();
559
560        if !signed {
561            match oop {
562                OverflowOp::Sub => {
563                    // Emit sub and icmp instead of llvm.usub.with.overflow. LLVM considers these
564                    // to be the canonical form. It will attempt to reform llvm.usub.with.overflow
565                    // in the backend if profitable.
566                    let sub = self.sub(lhs, rhs);
567                    let cmp = self.icmp(IntPredicate::IntULT, lhs, rhs);
568                    return (sub, cmp);
569                }
570                OverflowOp::Add => {
571                    // Like with sub above, using icmp is the preferred form. See
572                    // <https://rust-lang.zulipchat.com/#narrow/channel/187780-t-compiler.2Fllvm/topic/.60uadd.2Ewith.2Eoverflow.60.20.28again.29/near/533041085>
573                    let add = self.add(lhs, rhs);
574                    let cmp = self.icmp(IntPredicate::IntULT, add, lhs);
575                    return (add, cmp);
576                }
577                OverflowOp::Mul => {}
578            }
579        }
580
581        let oop_str = match oop {
582            OverflowOp::Add => "add",
583            OverflowOp::Sub => "sub",
584            OverflowOp::Mul => "mul",
585        };
586
587        let name = format!("llvm.{}{oop_str}.with.overflow", if signed { 's' } else { 'u' });
588
589        let res = self.call_intrinsic(name, &[self.type_ix(width)], &[lhs, rhs]);
590        (self.extract_value(res, 0), self.extract_value(res, 1))
591    }
592
593    fn from_immediate(&mut self, val: Self::Value) -> Self::Value {
594        if self.cx().val_ty(val) == self.cx().type_i1() {
595            self.zext(val, self.cx().type_i8())
596        } else {
597            val
598        }
599    }
600
601    fn to_immediate_scalar(&mut self, val: Self::Value, scalar: abi::Scalar) -> Self::Value {
602        if scalar.is_bool() {
603            return self.unchecked_utrunc(val, self.cx().type_i1());
604        }
605        val
606    }
607
608    fn alloca(&mut self, size: Size, align: Align) -> &'ll Value {
609        let mut bx = Builder::with_cx(self.cx);
610        bx.position_at_start(unsafe { llvm::LLVMGetFirstBasicBlock(self.llfn()) });
611        let ty = self.cx().type_array(self.cx().type_i8(), size.bytes());
612        unsafe {
613            let alloca = llvm::LLVMBuildAlloca(bx.llbuilder, ty, UNNAMED);
614            llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
615            // Cast to default addrspace if necessary
616            llvm::LLVMBuildPointerCast(bx.llbuilder, alloca, self.cx().type_ptr(), UNNAMED)
617        }
618    }
619
620    fn load(&mut self, ty: &'ll Type, ptr: &'ll Value, align: Align) -> &'ll Value {
621        unsafe {
622            let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
623            let align = align.min(self.cx().tcx.sess.target.max_reliable_alignment());
624            llvm::LLVMSetAlignment(load, align.bytes() as c_uint);
625            load
626        }
627    }
628
629    fn volatile_load(&mut self, ty: &'ll Type, ptr: &'ll Value) -> &'ll Value {
630        unsafe {
631            let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
632            llvm::LLVMSetVolatile(load, llvm::TRUE);
633            load
634        }
635    }
636
637    fn atomic_load(
638        &mut self,
639        ty: &'ll Type,
640        ptr: &'ll Value,
641        order: rustc_middle::ty::AtomicOrdering,
642        size: Size,
643    ) -> &'ll Value {
644        unsafe {
645            let load = llvm::LLVMRustBuildAtomicLoad(
646                self.llbuilder,
647                ty,
648                ptr,
649                UNNAMED,
650                AtomicOrdering::from_generic(order),
651            );
652            // LLVM requires the alignment of atomic loads to be at least the size of the type.
653            llvm::LLVMSetAlignment(load, size.bytes() as c_uint);
654            load
655        }
656    }
657
658    #[instrument(level = "trace", skip(self))]
659    fn load_operand(&mut self, place: PlaceRef<'tcx, &'ll Value>) -> OperandRef<'tcx, &'ll Value> {
660        if place.layout.is_unsized() {
661            let tail = self.tcx.struct_tail_for_codegen(place.layout.ty, self.typing_env());
662            if matches!(tail.kind(), ty::Foreign(..)) {
663                // Unsized locals and, at least conceptually, even unsized arguments must be copied
664                // around, which requires dynamically determining their size. Therefore, we cannot
665                // allow `extern` types here. Consult t-opsem before removing this check.
666                panic!("unsized locals must not be `extern` types");
667            }
668        }
669        assert_eq!(place.val.llextra.is_some(), place.layout.is_unsized());
670
671        if place.layout.is_zst() {
672            return OperandRef::zero_sized(place.layout);
673        }
674
675        #[instrument(level = "trace", skip(bx))]
676        fn scalar_load_metadata<'a, 'll, 'tcx>(
677            bx: &mut Builder<'a, 'll, 'tcx>,
678            load: &'ll Value,
679            scalar: abi::Scalar,
680            layout: TyAndLayout<'tcx>,
681            offset: Size,
682        ) {
683            if bx.cx.sess().opts.optimize == OptLevel::No {
684                // Don't emit metadata we're not going to use
685                return;
686            }
687
688            if !scalar.is_uninit_valid() {
689                bx.noundef_metadata(load);
690            }
691
692            match scalar.primitive() {
693                abi::Primitive::Int(..) => {
694                    if !scalar.is_always_valid(bx) {
695                        bx.range_metadata(load, scalar.valid_range(bx));
696                    }
697                }
698                abi::Primitive::Pointer(_) => {
699                    if !scalar.valid_range(bx).contains(0) {
700                        bx.nonnull_metadata(load);
701                    }
702
703                    if let Some(pointee) = layout.pointee_info_at(bx, offset)
704                        && let Some(_) = pointee.safe
705                    {
706                        bx.align_metadata(load, pointee.align);
707                    }
708                }
709                abi::Primitive::Float(_) => {}
710            }
711        }
712
713        let val = if let Some(_) = place.val.llextra {
714            // FIXME: Merge with the `else` below?
715            OperandValue::Ref(place.val)
716        } else if place.layout.is_llvm_immediate() {
717            let mut const_llval = None;
718            let llty = place.layout.llvm_type(self);
719            if let Some(global) = llvm::LLVMIsAGlobalVariable(place.val.llval) {
720                if llvm::LLVMIsGlobalConstant(global).is_true() {
721                    if let Some(init) = llvm::LLVMGetInitializer(global) {
722                        if self.val_ty(init) == llty {
723                            const_llval = Some(init);
724                        }
725                    }
726                }
727            }
728
729            let llval = const_llval.unwrap_or_else(|| {
730                let load = self.load(llty, place.val.llval, place.val.align);
731                if let abi::BackendRepr::Scalar(scalar) = place.layout.backend_repr {
732                    scalar_load_metadata(self, load, scalar, place.layout, Size::ZERO);
733                    self.to_immediate_scalar(load, scalar)
734                } else {
735                    load
736                }
737            });
738            OperandValue::Immediate(llval)
739        } else if let abi::BackendRepr::ScalarPair(a, b) = place.layout.backend_repr {
740            let b_offset = a.size(self).align_to(b.align(self).abi);
741
742            let mut load = |i, scalar: abi::Scalar, layout, align, offset| {
743                let llptr = if i == 0 {
744                    place.val.llval
745                } else {
746                    self.inbounds_ptradd(place.val.llval, self.const_usize(b_offset.bytes()))
747                };
748                let llty = place.layout.scalar_pair_element_llvm_type(self, i, false);
749                let load = self.load(llty, llptr, align);
750                scalar_load_metadata(self, load, scalar, layout, offset);
751                self.to_immediate_scalar(load, scalar)
752            };
753
754            OperandValue::Pair(
755                load(0, a, place.layout, place.val.align, Size::ZERO),
756                load(1, b, place.layout, place.val.align.restrict_for_offset(b_offset), b_offset),
757            )
758        } else {
759            OperandValue::Ref(place.val)
760        };
761
762        OperandRef { val, layout: place.layout }
763    }
764
765    fn write_operand_repeatedly(
766        &mut self,
767        cg_elem: OperandRef<'tcx, &'ll Value>,
768        count: u64,
769        dest: PlaceRef<'tcx, &'ll Value>,
770    ) {
771        let zero = self.const_usize(0);
772        let count = self.const_usize(count);
773
774        let header_bb = self.append_sibling_block("repeat_loop_header");
775        let body_bb = self.append_sibling_block("repeat_loop_body");
776        let next_bb = self.append_sibling_block("repeat_loop_next");
777
778        self.br(header_bb);
779
780        let mut header_bx = Self::build(self.cx, header_bb);
781        let i = header_bx.phi(self.val_ty(zero), &[zero], &[self.llbb()]);
782
783        let keep_going = header_bx.icmp(IntPredicate::IntULT, i, count);
784        header_bx.cond_br(keep_going, body_bb, next_bb);
785
786        let mut body_bx = Self::build(self.cx, body_bb);
787        let dest_elem = dest.project_index(&mut body_bx, i);
788        cg_elem.val.store(&mut body_bx, dest_elem);
789
790        let next = body_bx.unchecked_uadd(i, self.const_usize(1));
791        body_bx.br(header_bb);
792        header_bx.add_incoming_to_phi(i, next, body_bb);
793
794        *self = Self::build(self.cx, next_bb);
795    }
796
797    fn range_metadata(&mut self, load: &'ll Value, range: WrappingRange) {
798        if self.cx.sess().opts.optimize == OptLevel::No {
799            // Don't emit metadata we're not going to use
800            return;
801        }
802
803        unsafe {
804            let llty = self.cx.val_ty(load);
805            let md = [
806                llvm::LLVMValueAsMetadata(self.cx.const_uint_big(llty, range.start)),
807                llvm::LLVMValueAsMetadata(self.cx.const_uint_big(llty, range.end.wrapping_add(1))),
808            ];
809            let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, md.as_ptr(), md.len());
810            self.set_metadata(load, llvm::MD_range, md);
811        }
812    }
813
814    fn nonnull_metadata(&mut self, load: &'ll Value) {
815        unsafe {
816            let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, ptr::null(), 0);
817            self.set_metadata(load, llvm::MD_nonnull, md);
818        }
819    }
820
821    fn store(&mut self, val: &'ll Value, ptr: &'ll Value, align: Align) -> &'ll Value {
822        self.store_with_flags(val, ptr, align, MemFlags::empty())
823    }
824
825    fn store_with_flags(
826        &mut self,
827        val: &'ll Value,
828        ptr: &'ll Value,
829        align: Align,
830        flags: MemFlags,
831    ) -> &'ll Value {
832        debug!("Store {:?} -> {:?} ({:?})", val, ptr, flags);
833        assert_eq!(self.cx.type_kind(self.cx.val_ty(ptr)), TypeKind::Pointer);
834        unsafe {
835            let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
836            let align = align.min(self.cx().tcx.sess.target.max_reliable_alignment());
837            let align =
838                if flags.contains(MemFlags::UNALIGNED) { 1 } else { align.bytes() as c_uint };
839            llvm::LLVMSetAlignment(store, align);
840            if flags.contains(MemFlags::VOLATILE) {
841                llvm::LLVMSetVolatile(store, llvm::TRUE);
842            }
843            if flags.contains(MemFlags::NONTEMPORAL) {
844                // Make sure that the current target architectures supports "sane" non-temporal
845                // stores, i.e., non-temporal stores that are equivalent to regular stores except
846                // for performance. LLVM doesn't seem to care about this, and will happily treat
847                // `!nontemporal` stores as-if they were normal stores (for reordering optimizations
848                // etc) even on x86, despite later lowering them to MOVNT which do *not* behave like
849                // regular stores but require special fences. So we keep a list of architectures
850                // where `!nontemporal` is known to be truly just a hint, and use regular stores
851                // everywhere else. (In the future, we could alternatively ensure that an sfence
852                // gets emitted after a sequence of movnt before any kind of synchronizing
853                // operation. But it's not clear how to do that with LLVM.)
854                // For more context, see <https://github.com/rust-lang/rust/issues/114582> and
855                // <https://github.com/llvm/llvm-project/issues/64521>.
856                const WELL_BEHAVED_NONTEMPORAL_ARCHS: &[&str] =
857                    &["aarch64", "arm", "riscv32", "riscv64"];
858
859                let use_nontemporal =
860                    WELL_BEHAVED_NONTEMPORAL_ARCHS.contains(&&*self.cx.tcx.sess.target.arch);
861                if use_nontemporal {
862                    // According to LLVM [1] building a nontemporal store must
863                    // *always* point to a metadata value of the integer 1.
864                    //
865                    // [1]: https://llvm.org/docs/LangRef.html#store-instruction
866                    let one = llvm::LLVMValueAsMetadata(self.cx.const_i32(1));
867                    let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, &one, 1);
868                    self.set_metadata(store, llvm::MD_nontemporal, md);
869                }
870            }
871            store
872        }
873    }
874
875    fn atomic_store(
876        &mut self,
877        val: &'ll Value,
878        ptr: &'ll Value,
879        order: rustc_middle::ty::AtomicOrdering,
880        size: Size,
881    ) {
882        debug!("Store {:?} -> {:?}", val, ptr);
883        assert_eq!(self.cx.type_kind(self.cx.val_ty(ptr)), TypeKind::Pointer);
884        unsafe {
885            let store = llvm::LLVMRustBuildAtomicStore(
886                self.llbuilder,
887                val,
888                ptr,
889                AtomicOrdering::from_generic(order),
890            );
891            // LLVM requires the alignment of atomic stores to be at least the size of the type.
892            llvm::LLVMSetAlignment(store, size.bytes() as c_uint);
893        }
894    }
895
896    fn gep(&mut self, ty: &'ll Type, ptr: &'ll Value, indices: &[&'ll Value]) -> &'ll Value {
897        unsafe {
898            llvm::LLVMBuildGEPWithNoWrapFlags(
899                self.llbuilder,
900                ty,
901                ptr,
902                indices.as_ptr(),
903                indices.len() as c_uint,
904                UNNAMED,
905                GEPNoWrapFlags::default(),
906            )
907        }
908    }
909
910    fn inbounds_gep(
911        &mut self,
912        ty: &'ll Type,
913        ptr: &'ll Value,
914        indices: &[&'ll Value],
915    ) -> &'ll Value {
916        unsafe {
917            llvm::LLVMBuildGEPWithNoWrapFlags(
918                self.llbuilder,
919                ty,
920                ptr,
921                indices.as_ptr(),
922                indices.len() as c_uint,
923                UNNAMED,
924                GEPNoWrapFlags::InBounds,
925            )
926        }
927    }
928
929    fn inbounds_nuw_gep(
930        &mut self,
931        ty: &'ll Type,
932        ptr: &'ll Value,
933        indices: &[&'ll Value],
934    ) -> &'ll Value {
935        unsafe {
936            llvm::LLVMBuildGEPWithNoWrapFlags(
937                self.llbuilder,
938                ty,
939                ptr,
940                indices.as_ptr(),
941                indices.len() as c_uint,
942                UNNAMED,
943                GEPNoWrapFlags::InBounds | GEPNoWrapFlags::NUW,
944            )
945        }
946    }
947
948    /* Casts */
949    fn trunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
950        unsafe { llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
951    }
952
953    fn unchecked_utrunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
954        debug_assert_ne!(self.val_ty(val), dest_ty);
955
956        let trunc = self.trunc(val, dest_ty);
957        unsafe {
958            if llvm::LLVMIsAInstruction(trunc).is_some() {
959                llvm::LLVMSetNUW(trunc, TRUE);
960            }
961        }
962        trunc
963    }
964
965    fn unchecked_strunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
966        debug_assert_ne!(self.val_ty(val), dest_ty);
967
968        let trunc = self.trunc(val, dest_ty);
969        unsafe {
970            if llvm::LLVMIsAInstruction(trunc).is_some() {
971                llvm::LLVMSetNSW(trunc, TRUE);
972            }
973        }
974        trunc
975    }
976
977    fn sext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
978        unsafe { llvm::LLVMBuildSExt(self.llbuilder, val, dest_ty, UNNAMED) }
979    }
980
981    fn fptoui_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
982        self.call_intrinsic("llvm.fptoui.sat", &[dest_ty, self.val_ty(val)], &[val])
983    }
984
985    fn fptosi_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
986        self.call_intrinsic("llvm.fptosi.sat", &[dest_ty, self.val_ty(val)], &[val])
987    }
988
989    fn fptoui(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
990        // On WebAssembly the `fptoui` and `fptosi` instructions currently have
991        // poor codegen. The reason for this is that the corresponding wasm
992        // instructions, `i32.trunc_f32_s` for example, will trap when the float
993        // is out-of-bounds, infinity, or nan. This means that LLVM
994        // automatically inserts control flow around `fptoui` and `fptosi`
995        // because the LLVM instruction `fptoui` is defined as producing a
996        // poison value, not having UB on out-of-bounds values.
997        //
998        // This method, however, is only used with non-saturating casts that
999        // have UB on out-of-bounds values. This means that it's ok if we use
1000        // the raw wasm instruction since out-of-bounds values can do whatever
1001        // we like. To ensure that LLVM picks the right instruction we choose
1002        // the raw wasm intrinsic functions which avoid LLVM inserting all the
1003        // other control flow automatically.
1004        if self.sess().target.is_like_wasm {
1005            let src_ty = self.cx.val_ty(val);
1006            if self.cx.type_kind(src_ty) != TypeKind::Vector {
1007                let float_width = self.cx.float_width(src_ty);
1008                let int_width = self.cx.int_width(dest_ty);
1009                if matches!((int_width, float_width), (32 | 64, 32 | 64)) {
1010                    return self.call_intrinsic(
1011                        "llvm.wasm.trunc.unsigned",
1012                        &[dest_ty, src_ty],
1013                        &[val],
1014                    );
1015                }
1016            }
1017        }
1018        unsafe { llvm::LLVMBuildFPToUI(self.llbuilder, val, dest_ty, UNNAMED) }
1019    }
1020
1021    fn fptosi(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1022        // see `fptoui` above for why wasm is different here
1023        if self.sess().target.is_like_wasm {
1024            let src_ty = self.cx.val_ty(val);
1025            if self.cx.type_kind(src_ty) != TypeKind::Vector {
1026                let float_width = self.cx.float_width(src_ty);
1027                let int_width = self.cx.int_width(dest_ty);
1028                if matches!((int_width, float_width), (32 | 64, 32 | 64)) {
1029                    return self.call_intrinsic(
1030                        "llvm.wasm.trunc.signed",
1031                        &[dest_ty, src_ty],
1032                        &[val],
1033                    );
1034                }
1035            }
1036        }
1037        unsafe { llvm::LLVMBuildFPToSI(self.llbuilder, val, dest_ty, UNNAMED) }
1038    }
1039
1040    fn uitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1041        unsafe { llvm::LLVMBuildUIToFP(self.llbuilder, val, dest_ty, UNNAMED) }
1042    }
1043
1044    fn sitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1045        unsafe { llvm::LLVMBuildSIToFP(self.llbuilder, val, dest_ty, UNNAMED) }
1046    }
1047
1048    fn fptrunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1049        unsafe { llvm::LLVMBuildFPTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
1050    }
1051
1052    fn fpext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1053        unsafe { llvm::LLVMBuildFPExt(self.llbuilder, val, dest_ty, UNNAMED) }
1054    }
1055
1056    fn ptrtoint(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1057        unsafe { llvm::LLVMBuildPtrToInt(self.llbuilder, val, dest_ty, UNNAMED) }
1058    }
1059
1060    fn inttoptr(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1061        unsafe { llvm::LLVMBuildIntToPtr(self.llbuilder, val, dest_ty, UNNAMED) }
1062    }
1063
1064    fn bitcast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1065        unsafe { llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty, UNNAMED) }
1066    }
1067
1068    fn intcast(&mut self, val: &'ll Value, dest_ty: &'ll Type, is_signed: bool) -> &'ll Value {
1069        unsafe {
1070            llvm::LLVMBuildIntCast2(self.llbuilder, val, dest_ty, is_signed.to_llvm_bool(), UNNAMED)
1071        }
1072    }
1073
1074    fn pointercast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1075        unsafe { llvm::LLVMBuildPointerCast(self.llbuilder, val, dest_ty, UNNAMED) }
1076    }
1077
1078    /* Comparisons */
1079    fn icmp(&mut self, op: IntPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1080        let op = llvm::IntPredicate::from_generic(op);
1081        unsafe { llvm::LLVMBuildICmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
1082    }
1083
1084    fn fcmp(&mut self, op: RealPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1085        let op = llvm::RealPredicate::from_generic(op);
1086        unsafe { llvm::LLVMBuildFCmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
1087    }
1088
1089    fn three_way_compare(
1090        &mut self,
1091        ty: Ty<'tcx>,
1092        lhs: Self::Value,
1093        rhs: Self::Value,
1094    ) -> Option<Self::Value> {
1095        // FIXME: See comment on the definition of `three_way_compare`.
1096        if crate::llvm_util::get_version() < (20, 0, 0) {
1097            return None;
1098        }
1099
1100        let size = ty.primitive_size(self.tcx);
1101        let name = if ty.is_signed() { "llvm.scmp" } else { "llvm.ucmp" };
1102
1103        Some(self.call_intrinsic(name, &[self.type_i8(), self.type_ix(size.bits())], &[lhs, rhs]))
1104    }
1105
1106    /* Miscellaneous instructions */
1107    fn memcpy(
1108        &mut self,
1109        dst: &'ll Value,
1110        dst_align: Align,
1111        src: &'ll Value,
1112        src_align: Align,
1113        size: &'ll Value,
1114        flags: MemFlags,
1115    ) {
1116        assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memcpy not supported");
1117        let size = self.intcast(size, self.type_isize(), false);
1118        let is_volatile = flags.contains(MemFlags::VOLATILE);
1119        unsafe {
1120            llvm::LLVMRustBuildMemCpy(
1121                self.llbuilder,
1122                dst,
1123                dst_align.bytes() as c_uint,
1124                src,
1125                src_align.bytes() as c_uint,
1126                size,
1127                is_volatile,
1128            );
1129        }
1130    }
1131
1132    fn memmove(
1133        &mut self,
1134        dst: &'ll Value,
1135        dst_align: Align,
1136        src: &'ll Value,
1137        src_align: Align,
1138        size: &'ll Value,
1139        flags: MemFlags,
1140    ) {
1141        assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memmove not supported");
1142        let size = self.intcast(size, self.type_isize(), false);
1143        let is_volatile = flags.contains(MemFlags::VOLATILE);
1144        unsafe {
1145            llvm::LLVMRustBuildMemMove(
1146                self.llbuilder,
1147                dst,
1148                dst_align.bytes() as c_uint,
1149                src,
1150                src_align.bytes() as c_uint,
1151                size,
1152                is_volatile,
1153            );
1154        }
1155    }
1156
1157    fn memset(
1158        &mut self,
1159        ptr: &'ll Value,
1160        fill_byte: &'ll Value,
1161        size: &'ll Value,
1162        align: Align,
1163        flags: MemFlags,
1164    ) {
1165        assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memset not supported");
1166        let is_volatile = flags.contains(MemFlags::VOLATILE);
1167        unsafe {
1168            llvm::LLVMRustBuildMemSet(
1169                self.llbuilder,
1170                ptr,
1171                align.bytes() as c_uint,
1172                fill_byte,
1173                size,
1174                is_volatile,
1175            );
1176        }
1177    }
1178
1179    fn select(
1180        &mut self,
1181        cond: &'ll Value,
1182        then_val: &'ll Value,
1183        else_val: &'ll Value,
1184    ) -> &'ll Value {
1185        unsafe { llvm::LLVMBuildSelect(self.llbuilder, cond, then_val, else_val, UNNAMED) }
1186    }
1187
1188    fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
1189        unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
1190    }
1191
1192    fn extract_element(&mut self, vec: &'ll Value, idx: &'ll Value) -> &'ll Value {
1193        unsafe { llvm::LLVMBuildExtractElement(self.llbuilder, vec, idx, UNNAMED) }
1194    }
1195
1196    fn vector_splat(&mut self, num_elts: usize, elt: &'ll Value) -> &'ll Value {
1197        unsafe {
1198            let elt_ty = self.cx.val_ty(elt);
1199            let undef = llvm::LLVMGetUndef(self.type_vector(elt_ty, num_elts as u64));
1200            let vec = self.insert_element(undef, elt, self.cx.const_i32(0));
1201            let vec_i32_ty = self.type_vector(self.type_i32(), num_elts as u64);
1202            self.shuffle_vector(vec, undef, self.const_null(vec_i32_ty))
1203        }
1204    }
1205
1206    fn extract_value(&mut self, agg_val: &'ll Value, idx: u64) -> &'ll Value {
1207        assert_eq!(idx as c_uint as u64, idx);
1208        unsafe { llvm::LLVMBuildExtractValue(self.llbuilder, agg_val, idx as c_uint, UNNAMED) }
1209    }
1210
1211    fn insert_value(&mut self, agg_val: &'ll Value, elt: &'ll Value, idx: u64) -> &'ll Value {
1212        assert_eq!(idx as c_uint as u64, idx);
1213        unsafe { llvm::LLVMBuildInsertValue(self.llbuilder, agg_val, elt, idx as c_uint, UNNAMED) }
1214    }
1215
1216    fn set_personality_fn(&mut self, personality: &'ll Value) {
1217        unsafe {
1218            llvm::LLVMSetPersonalityFn(self.llfn(), personality);
1219        }
1220    }
1221
1222    fn cleanup_landing_pad(&mut self, pers_fn: &'ll Value) -> (&'ll Value, &'ll Value) {
1223        let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1224        let landing_pad = self.landing_pad(ty, pers_fn, 0);
1225        unsafe {
1226            llvm::LLVMSetCleanup(landing_pad, llvm::TRUE);
1227        }
1228        (self.extract_value(landing_pad, 0), self.extract_value(landing_pad, 1))
1229    }
1230
1231    fn filter_landing_pad(&mut self, pers_fn: &'ll Value) {
1232        let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1233        let landing_pad = self.landing_pad(ty, pers_fn, 1);
1234        self.add_clause(landing_pad, self.const_array(self.type_ptr(), &[]));
1235    }
1236
1237    fn resume(&mut self, exn0: &'ll Value, exn1: &'ll Value) {
1238        let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1239        let mut exn = self.const_poison(ty);
1240        exn = self.insert_value(exn, exn0, 0);
1241        exn = self.insert_value(exn, exn1, 1);
1242        unsafe {
1243            llvm::LLVMBuildResume(self.llbuilder, exn);
1244        }
1245    }
1246
1247    fn cleanup_pad(&mut self, parent: Option<&'ll Value>, args: &[&'ll Value]) -> Funclet<'ll> {
1248        let ret = unsafe {
1249            llvm::LLVMBuildCleanupPad(
1250                self.llbuilder,
1251                parent,
1252                args.as_ptr(),
1253                args.len() as c_uint,
1254                c"cleanuppad".as_ptr(),
1255            )
1256        };
1257        Funclet::new(ret.expect("LLVM does not have support for cleanuppad"))
1258    }
1259
1260    fn cleanup_ret(&mut self, funclet: &Funclet<'ll>, unwind: Option<&'ll BasicBlock>) {
1261        unsafe {
1262            llvm::LLVMBuildCleanupRet(self.llbuilder, funclet.cleanuppad(), unwind)
1263                .expect("LLVM does not have support for cleanupret");
1264        }
1265    }
1266
1267    fn catch_pad(&mut self, parent: &'ll Value, args: &[&'ll Value]) -> Funclet<'ll> {
1268        let ret = unsafe {
1269            llvm::LLVMBuildCatchPad(
1270                self.llbuilder,
1271                parent,
1272                args.as_ptr(),
1273                args.len() as c_uint,
1274                c"catchpad".as_ptr(),
1275            )
1276        };
1277        Funclet::new(ret.expect("LLVM does not have support for catchpad"))
1278    }
1279
1280    fn catch_switch(
1281        &mut self,
1282        parent: Option<&'ll Value>,
1283        unwind: Option<&'ll BasicBlock>,
1284        handlers: &[&'ll BasicBlock],
1285    ) -> &'ll Value {
1286        let ret = unsafe {
1287            llvm::LLVMBuildCatchSwitch(
1288                self.llbuilder,
1289                parent,
1290                unwind,
1291                handlers.len() as c_uint,
1292                c"catchswitch".as_ptr(),
1293            )
1294        };
1295        let ret = ret.expect("LLVM does not have support for catchswitch");
1296        for handler in handlers {
1297            unsafe {
1298                llvm::LLVMAddHandler(ret, handler);
1299            }
1300        }
1301        ret
1302    }
1303
1304    // Atomic Operations
1305    fn atomic_cmpxchg(
1306        &mut self,
1307        dst: &'ll Value,
1308        cmp: &'ll Value,
1309        src: &'ll Value,
1310        order: rustc_middle::ty::AtomicOrdering,
1311        failure_order: rustc_middle::ty::AtomicOrdering,
1312        weak: bool,
1313    ) -> (&'ll Value, &'ll Value) {
1314        unsafe {
1315            let value = llvm::LLVMBuildAtomicCmpXchg(
1316                self.llbuilder,
1317                dst,
1318                cmp,
1319                src,
1320                AtomicOrdering::from_generic(order),
1321                AtomicOrdering::from_generic(failure_order),
1322                llvm::FALSE, // SingleThreaded
1323            );
1324            llvm::LLVMSetWeak(value, weak.to_llvm_bool());
1325            let val = self.extract_value(value, 0);
1326            let success = self.extract_value(value, 1);
1327            (val, success)
1328        }
1329    }
1330
1331    fn atomic_rmw(
1332        &mut self,
1333        op: rustc_codegen_ssa::common::AtomicRmwBinOp,
1334        dst: &'ll Value,
1335        src: &'ll Value,
1336        order: rustc_middle::ty::AtomicOrdering,
1337        ret_ptr: bool,
1338    ) -> &'ll Value {
1339        // FIXME: If `ret_ptr` is true and `src` is not a pointer, we *should* tell LLVM that the
1340        // LHS is a pointer and the operation should be provenance-preserving, but LLVM does not
1341        // currently support that (https://github.com/llvm/llvm-project/issues/120837).
1342        let mut res = unsafe {
1343            llvm::LLVMBuildAtomicRMW(
1344                self.llbuilder,
1345                AtomicRmwBinOp::from_generic(op),
1346                dst,
1347                src,
1348                AtomicOrdering::from_generic(order),
1349                llvm::FALSE, // SingleThreaded
1350            )
1351        };
1352        if ret_ptr && self.val_ty(res) != self.type_ptr() {
1353            res = self.inttoptr(res, self.type_ptr());
1354        }
1355        res
1356    }
1357
1358    fn atomic_fence(
1359        &mut self,
1360        order: rustc_middle::ty::AtomicOrdering,
1361        scope: SynchronizationScope,
1362    ) {
1363        let single_threaded = match scope {
1364            SynchronizationScope::SingleThread => true,
1365            SynchronizationScope::CrossThread => false,
1366        };
1367        unsafe {
1368            llvm::LLVMBuildFence(
1369                self.llbuilder,
1370                AtomicOrdering::from_generic(order),
1371                single_threaded.to_llvm_bool(),
1372                UNNAMED,
1373            );
1374        }
1375    }
1376
1377    fn set_invariant_load(&mut self, load: &'ll Value) {
1378        unsafe {
1379            let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, ptr::null(), 0);
1380            self.set_metadata(load, llvm::MD_invariant_load, md);
1381        }
1382    }
1383
1384    fn lifetime_start(&mut self, ptr: &'ll Value, size: Size) {
1385        self.call_lifetime_intrinsic("llvm.lifetime.start", ptr, size);
1386    }
1387
1388    fn lifetime_end(&mut self, ptr: &'ll Value, size: Size) {
1389        self.call_lifetime_intrinsic("llvm.lifetime.end", ptr, size);
1390    }
1391
1392    fn call(
1393        &mut self,
1394        llty: &'ll Type,
1395        fn_attrs: Option<&CodegenFnAttrs>,
1396        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1397        llfn: &'ll Value,
1398        args: &[&'ll Value],
1399        funclet: Option<&Funclet<'ll>>,
1400        instance: Option<Instance<'tcx>>,
1401    ) -> &'ll Value {
1402        debug!("call {:?} with args ({:?})", llfn, args);
1403
1404        let args = self.check_call("call", llty, llfn, args);
1405        let funclet_bundle = funclet.map(|funclet| funclet.bundle());
1406        let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
1407        if let Some(funclet_bundle) = funclet_bundle {
1408            bundles.push(funclet_bundle);
1409        }
1410
1411        // Emit CFI pointer type membership test
1412        self.cfi_type_test(fn_attrs, fn_abi, instance, llfn);
1413
1414        // Emit KCFI operand bundle
1415        let kcfi_bundle = self.kcfi_operand_bundle(fn_attrs, fn_abi, instance, llfn);
1416        if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
1417            bundles.push(kcfi_bundle);
1418        }
1419
1420        let call = unsafe {
1421            llvm::LLVMBuildCallWithOperandBundles(
1422                self.llbuilder,
1423                llty,
1424                llfn,
1425                args.as_ptr() as *const &llvm::Value,
1426                args.len() as c_uint,
1427                bundles.as_ptr(),
1428                bundles.len() as c_uint,
1429                c"".as_ptr(),
1430            )
1431        };
1432        if let Some(fn_abi) = fn_abi {
1433            fn_abi.apply_attrs_callsite(self, call);
1434        }
1435        call
1436    }
1437
1438    fn tail_call(
1439        &mut self,
1440        llty: Self::Type,
1441        fn_attrs: Option<&CodegenFnAttrs>,
1442        fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
1443        llfn: Self::Value,
1444        args: &[Self::Value],
1445        funclet: Option<&Self::Funclet>,
1446        instance: Option<Instance<'tcx>>,
1447    ) {
1448        let call = self.call(llty, fn_attrs, Some(fn_abi), llfn, args, funclet, instance);
1449        llvm::LLVMSetTailCallKind(call, llvm::TailCallKind::MustTail);
1450
1451        match &fn_abi.ret.mode {
1452            PassMode::Ignore | PassMode::Indirect { .. } => self.ret_void(),
1453            PassMode::Direct(_) | PassMode::Pair { .. } => self.ret(call),
1454            mode @ PassMode::Cast { .. } => {
1455                bug!("Encountered `PassMode::{mode:?}` during codegen")
1456            }
1457        }
1458    }
1459
1460    fn zext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1461        unsafe { llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty, UNNAMED) }
1462    }
1463
1464    fn apply_attrs_to_cleanup_callsite(&mut self, llret: &'ll Value) {
1465        // Cleanup is always the cold path.
1466        let cold_inline = llvm::AttributeKind::Cold.create_attr(self.llcx);
1467        attributes::apply_to_callsite(llret, llvm::AttributePlace::Function, &[cold_inline]);
1468    }
1469}
1470
1471impl<'ll> StaticBuilderMethods for Builder<'_, 'll, '_> {
1472    fn get_static(&mut self, def_id: DefId) -> &'ll Value {
1473        // Forward to the `get_static` method of `CodegenCx`
1474        let global = self.cx().get_static(def_id);
1475        if self.cx().tcx.is_thread_local_static(def_id) {
1476            let pointer =
1477                self.call_intrinsic("llvm.threadlocal.address", &[self.val_ty(global)], &[global]);
1478            // Cast to default address space if globals are in a different addrspace
1479            self.pointercast(pointer, self.type_ptr())
1480        } else {
1481            // Cast to default address space if globals are in a different addrspace
1482            self.cx().const_pointercast(global, self.type_ptr())
1483        }
1484    }
1485}
1486
1487impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1488    pub(crate) fn llfn(&self) -> &'ll Value {
1489        unsafe { llvm::LLVMGetBasicBlockParent(self.llbb()) }
1490    }
1491}
1492
1493impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1494    fn position_at_start(&mut self, llbb: &'ll BasicBlock) {
1495        unsafe {
1496            llvm::LLVMRustPositionBuilderAtStart(self.llbuilder, llbb);
1497        }
1498    }
1499}
1500impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1501    fn align_metadata(&mut self, load: &'ll Value, align: Align) {
1502        unsafe {
1503            let md = [llvm::LLVMValueAsMetadata(self.cx.const_u64(align.bytes()))];
1504            let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, md.as_ptr(), md.len());
1505            self.set_metadata(load, llvm::MD_align, md);
1506        }
1507    }
1508
1509    fn noundef_metadata(&mut self, load: &'ll Value) {
1510        unsafe {
1511            let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, ptr::null(), 0);
1512            self.set_metadata(load, llvm::MD_noundef, md);
1513        }
1514    }
1515
1516    pub(crate) fn set_unpredictable(&mut self, inst: &'ll Value) {
1517        unsafe {
1518            let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, ptr::null(), 0);
1519            self.set_metadata(inst, llvm::MD_unpredictable, md);
1520        }
1521    }
1522}
1523impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1524    pub(crate) fn minnum(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1525        unsafe { llvm::LLVMRustBuildMinNum(self.llbuilder, lhs, rhs) }
1526    }
1527
1528    pub(crate) fn maxnum(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1529        unsafe { llvm::LLVMRustBuildMaxNum(self.llbuilder, lhs, rhs) }
1530    }
1531
1532    pub(crate) fn insert_element(
1533        &mut self,
1534        vec: &'ll Value,
1535        elt: &'ll Value,
1536        idx: &'ll Value,
1537    ) -> &'ll Value {
1538        unsafe { llvm::LLVMBuildInsertElement(self.llbuilder, vec, elt, idx, UNNAMED) }
1539    }
1540
1541    pub(crate) fn shuffle_vector(
1542        &mut self,
1543        v1: &'ll Value,
1544        v2: &'ll Value,
1545        mask: &'ll Value,
1546    ) -> &'ll Value {
1547        unsafe { llvm::LLVMBuildShuffleVector(self.llbuilder, v1, v2, mask, UNNAMED) }
1548    }
1549
1550    pub(crate) fn vector_reduce_fadd(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1551        unsafe { llvm::LLVMRustBuildVectorReduceFAdd(self.llbuilder, acc, src) }
1552    }
1553    pub(crate) fn vector_reduce_fmul(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1554        unsafe { llvm::LLVMRustBuildVectorReduceFMul(self.llbuilder, acc, src) }
1555    }
1556    pub(crate) fn vector_reduce_fadd_reassoc(
1557        &mut self,
1558        acc: &'ll Value,
1559        src: &'ll Value,
1560    ) -> &'ll Value {
1561        unsafe {
1562            let instr = llvm::LLVMRustBuildVectorReduceFAdd(self.llbuilder, acc, src);
1563            llvm::LLVMRustSetAllowReassoc(instr);
1564            instr
1565        }
1566    }
1567    pub(crate) fn vector_reduce_fmul_reassoc(
1568        &mut self,
1569        acc: &'ll Value,
1570        src: &'ll Value,
1571    ) -> &'ll Value {
1572        unsafe {
1573            let instr = llvm::LLVMRustBuildVectorReduceFMul(self.llbuilder, acc, src);
1574            llvm::LLVMRustSetAllowReassoc(instr);
1575            instr
1576        }
1577    }
1578    pub(crate) fn vector_reduce_add(&mut self, src: &'ll Value) -> &'ll Value {
1579        unsafe { llvm::LLVMRustBuildVectorReduceAdd(self.llbuilder, src) }
1580    }
1581    pub(crate) fn vector_reduce_mul(&mut self, src: &'ll Value) -> &'ll Value {
1582        unsafe { llvm::LLVMRustBuildVectorReduceMul(self.llbuilder, src) }
1583    }
1584    pub(crate) fn vector_reduce_and(&mut self, src: &'ll Value) -> &'ll Value {
1585        unsafe { llvm::LLVMRustBuildVectorReduceAnd(self.llbuilder, src) }
1586    }
1587    pub(crate) fn vector_reduce_or(&mut self, src: &'ll Value) -> &'ll Value {
1588        unsafe { llvm::LLVMRustBuildVectorReduceOr(self.llbuilder, src) }
1589    }
1590    pub(crate) fn vector_reduce_xor(&mut self, src: &'ll Value) -> &'ll Value {
1591        unsafe { llvm::LLVMRustBuildVectorReduceXor(self.llbuilder, src) }
1592    }
1593    pub(crate) fn vector_reduce_fmin(&mut self, src: &'ll Value) -> &'ll Value {
1594        unsafe {
1595            llvm::LLVMRustBuildVectorReduceFMin(self.llbuilder, src, /*NoNaNs:*/ false)
1596        }
1597    }
1598    pub(crate) fn vector_reduce_fmax(&mut self, src: &'ll Value) -> &'ll Value {
1599        unsafe {
1600            llvm::LLVMRustBuildVectorReduceFMax(self.llbuilder, src, /*NoNaNs:*/ false)
1601        }
1602    }
1603    pub(crate) fn vector_reduce_min(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1604        unsafe { llvm::LLVMRustBuildVectorReduceMin(self.llbuilder, src, is_signed) }
1605    }
1606    pub(crate) fn vector_reduce_max(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1607        unsafe { llvm::LLVMRustBuildVectorReduceMax(self.llbuilder, src, is_signed) }
1608    }
1609
1610    pub(crate) fn add_clause(&mut self, landing_pad: &'ll Value, clause: &'ll Value) {
1611        unsafe {
1612            llvm::LLVMAddClause(landing_pad, clause);
1613        }
1614    }
1615
1616    pub(crate) fn catch_ret(
1617        &mut self,
1618        funclet: &Funclet<'ll>,
1619        unwind: &'ll BasicBlock,
1620    ) -> &'ll Value {
1621        let ret = unsafe { llvm::LLVMBuildCatchRet(self.llbuilder, funclet.cleanuppad(), unwind) };
1622        ret.expect("LLVM does not have support for catchret")
1623    }
1624
1625    fn check_call<'b>(
1626        &mut self,
1627        typ: &str,
1628        fn_ty: &'ll Type,
1629        llfn: &'ll Value,
1630        args: &'b [&'ll Value],
1631    ) -> Cow<'b, [&'ll Value]> {
1632        assert!(
1633            self.cx.type_kind(fn_ty) == TypeKind::Function,
1634            "builder::{typ} not passed a function, but {fn_ty:?}"
1635        );
1636
1637        let param_tys = self.cx.func_params_types(fn_ty);
1638
1639        let all_args_match = iter::zip(&param_tys, args.iter().map(|&v| self.cx.val_ty(v)))
1640            .all(|(expected_ty, actual_ty)| *expected_ty == actual_ty);
1641
1642        if all_args_match {
1643            return Cow::Borrowed(args);
1644        }
1645
1646        let casted_args: Vec<_> = iter::zip(param_tys, args)
1647            .enumerate()
1648            .map(|(i, (expected_ty, &actual_val))| {
1649                let actual_ty = self.cx.val_ty(actual_val);
1650                if expected_ty != actual_ty {
1651                    debug!(
1652                        "type mismatch in function call of {:?}. \
1653                            Expected {:?} for param {}, got {:?}; injecting bitcast",
1654                        llfn, expected_ty, i, actual_ty
1655                    );
1656                    self.bitcast(actual_val, expected_ty)
1657                } else {
1658                    actual_val
1659                }
1660            })
1661            .collect();
1662
1663        Cow::Owned(casted_args)
1664    }
1665
1666    pub(crate) fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
1667        unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
1668    }
1669}
1670
1671impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1672    pub(crate) fn call_intrinsic(
1673        &mut self,
1674        base_name: impl Into<Cow<'static, str>>,
1675        type_params: &[&'ll Type],
1676        args: &[&'ll Value],
1677    ) -> &'ll Value {
1678        let (ty, f) = self.cx.get_intrinsic(base_name.into(), type_params);
1679        self.call(ty, None, None, f, args, None, None)
1680    }
1681
1682    fn call_lifetime_intrinsic(&mut self, intrinsic: &'static str, ptr: &'ll Value, size: Size) {
1683        let size = size.bytes();
1684        if size == 0 {
1685            return;
1686        }
1687
1688        if !self.cx().sess().emit_lifetime_markers() {
1689            return;
1690        }
1691
1692        if crate::llvm_util::get_version() >= (22, 0, 0) {
1693            self.call_intrinsic(intrinsic, &[self.val_ty(ptr)], &[ptr]);
1694        } else {
1695            self.call_intrinsic(intrinsic, &[self.val_ty(ptr)], &[self.cx.const_u64(size), ptr]);
1696        }
1697    }
1698}
1699impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1700    pub(crate) fn phi(
1701        &mut self,
1702        ty: &'ll Type,
1703        vals: &[&'ll Value],
1704        bbs: &[&'ll BasicBlock],
1705    ) -> &'ll Value {
1706        assert_eq!(vals.len(), bbs.len());
1707        let phi = unsafe { llvm::LLVMBuildPhi(self.llbuilder, ty, UNNAMED) };
1708        unsafe {
1709            llvm::LLVMAddIncoming(phi, vals.as_ptr(), bbs.as_ptr(), vals.len() as c_uint);
1710            phi
1711        }
1712    }
1713
1714    fn add_incoming_to_phi(&mut self, phi: &'ll Value, val: &'ll Value, bb: &'ll BasicBlock) {
1715        unsafe {
1716            llvm::LLVMAddIncoming(phi, &val, &bb, 1 as c_uint);
1717        }
1718    }
1719}
1720impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1721    pub(crate) fn landing_pad(
1722        &mut self,
1723        ty: &'ll Type,
1724        pers_fn: &'ll Value,
1725        num_clauses: usize,
1726    ) -> &'ll Value {
1727        // Use LLVMSetPersonalityFn to set the personality. It supports arbitrary Consts while,
1728        // LLVMBuildLandingPad requires the argument to be a Function (as of LLVM 12). The
1729        // personality lives on the parent function anyway.
1730        self.set_personality_fn(pers_fn);
1731        unsafe {
1732            llvm::LLVMBuildLandingPad(self.llbuilder, ty, None, num_clauses as c_uint, UNNAMED)
1733        }
1734    }
1735
1736    pub(crate) fn callbr(
1737        &mut self,
1738        llty: &'ll Type,
1739        fn_attrs: Option<&CodegenFnAttrs>,
1740        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1741        llfn: &'ll Value,
1742        args: &[&'ll Value],
1743        default_dest: &'ll BasicBlock,
1744        indirect_dest: &[&'ll BasicBlock],
1745        funclet: Option<&Funclet<'ll>>,
1746        instance: Option<Instance<'tcx>>,
1747    ) -> &'ll Value {
1748        debug!("invoke {:?} with args ({:?})", llfn, args);
1749
1750        let args = self.check_call("callbr", llty, llfn, args);
1751        let funclet_bundle = funclet.map(|funclet| funclet.bundle());
1752        let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
1753        if let Some(funclet_bundle) = funclet_bundle {
1754            bundles.push(funclet_bundle);
1755        }
1756
1757        // Emit CFI pointer type membership test
1758        self.cfi_type_test(fn_attrs, fn_abi, instance, llfn);
1759
1760        // Emit KCFI operand bundle
1761        let kcfi_bundle = self.kcfi_operand_bundle(fn_attrs, fn_abi, instance, llfn);
1762        if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
1763            bundles.push(kcfi_bundle);
1764        }
1765
1766        let callbr = unsafe {
1767            llvm::LLVMBuildCallBr(
1768                self.llbuilder,
1769                llty,
1770                llfn,
1771                default_dest,
1772                indirect_dest.as_ptr(),
1773                indirect_dest.len() as c_uint,
1774                args.as_ptr(),
1775                args.len() as c_uint,
1776                bundles.as_ptr(),
1777                bundles.len() as c_uint,
1778                UNNAMED,
1779            )
1780        };
1781        if let Some(fn_abi) = fn_abi {
1782            fn_abi.apply_attrs_callsite(self, callbr);
1783        }
1784        callbr
1785    }
1786
1787    // Emits CFI pointer type membership tests.
1788    fn cfi_type_test(
1789        &mut self,
1790        fn_attrs: Option<&CodegenFnAttrs>,
1791        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1792        instance: Option<Instance<'tcx>>,
1793        llfn: &'ll Value,
1794    ) {
1795        let is_indirect_call = unsafe { llvm::LLVMRustIsNonGVFunctionPointerTy(llfn) };
1796        if self.tcx.sess.is_sanitizer_cfi_enabled()
1797            && let Some(fn_abi) = fn_abi
1798            && is_indirect_call
1799        {
1800            if let Some(fn_attrs) = fn_attrs
1801                && fn_attrs.no_sanitize.contains(SanitizerSet::CFI)
1802            {
1803                return;
1804            }
1805
1806            let mut options = cfi::TypeIdOptions::empty();
1807            if self.tcx.sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1808                options.insert(cfi::TypeIdOptions::GENERALIZE_POINTERS);
1809            }
1810            if self.tcx.sess.is_sanitizer_cfi_normalize_integers_enabled() {
1811                options.insert(cfi::TypeIdOptions::NORMALIZE_INTEGERS);
1812            }
1813
1814            let typeid = if let Some(instance) = instance {
1815                cfi::typeid_for_instance(self.tcx, instance, options)
1816            } else {
1817                cfi::typeid_for_fnabi(self.tcx, fn_abi, options)
1818            };
1819            let typeid_metadata = self.cx.create_metadata(typeid.as_bytes());
1820            let dbg_loc = self.get_dbg_loc();
1821
1822            // Test whether the function pointer is associated with the type identifier using the
1823            // llvm.type.test intrinsic. The LowerTypeTests link-time optimization pass replaces
1824            // calls to this intrinsic with code to test type membership.
1825            let typeid = self.get_metadata_value(typeid_metadata);
1826            let cond = self.call_intrinsic("llvm.type.test", &[], &[llfn, typeid]);
1827            let bb_pass = self.append_sibling_block("type_test.pass");
1828            let bb_fail = self.append_sibling_block("type_test.fail");
1829            self.cond_br(cond, bb_pass, bb_fail);
1830
1831            self.switch_to_block(bb_fail);
1832            if let Some(dbg_loc) = dbg_loc {
1833                self.set_dbg_loc(dbg_loc);
1834            }
1835            self.abort();
1836            self.unreachable();
1837
1838            self.switch_to_block(bb_pass);
1839            if let Some(dbg_loc) = dbg_loc {
1840                self.set_dbg_loc(dbg_loc);
1841            }
1842        }
1843    }
1844
1845    // Emits KCFI operand bundles.
1846    fn kcfi_operand_bundle(
1847        &mut self,
1848        fn_attrs: Option<&CodegenFnAttrs>,
1849        fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1850        instance: Option<Instance<'tcx>>,
1851        llfn: &'ll Value,
1852    ) -> Option<llvm::OperandBundleBox<'ll>> {
1853        let is_indirect_call = unsafe { llvm::LLVMRustIsNonGVFunctionPointerTy(llfn) };
1854        let kcfi_bundle = if self.tcx.sess.is_sanitizer_kcfi_enabled()
1855            && let Some(fn_abi) = fn_abi
1856            && is_indirect_call
1857        {
1858            if let Some(fn_attrs) = fn_attrs
1859                && fn_attrs.no_sanitize.contains(SanitizerSet::KCFI)
1860            {
1861                return None;
1862            }
1863
1864            let mut options = kcfi::TypeIdOptions::empty();
1865            if self.tcx.sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1866                options.insert(kcfi::TypeIdOptions::GENERALIZE_POINTERS);
1867            }
1868            if self.tcx.sess.is_sanitizer_cfi_normalize_integers_enabled() {
1869                options.insert(kcfi::TypeIdOptions::NORMALIZE_INTEGERS);
1870            }
1871
1872            let kcfi_typeid = if let Some(instance) = instance {
1873                kcfi::typeid_for_instance(self.tcx, instance, options)
1874            } else {
1875                kcfi::typeid_for_fnabi(self.tcx, fn_abi, options)
1876            };
1877
1878            Some(llvm::OperandBundleBox::new("kcfi", &[self.const_u32(kcfi_typeid)]))
1879        } else {
1880            None
1881        };
1882        kcfi_bundle
1883    }
1884
1885    /// Emits a call to `llvm.instrprof.increment`. Used by coverage instrumentation.
1886    #[instrument(level = "debug", skip(self))]
1887    pub(crate) fn instrprof_increment(
1888        &mut self,
1889        fn_name: &'ll Value,
1890        hash: &'ll Value,
1891        num_counters: &'ll Value,
1892        index: &'ll Value,
1893    ) {
1894        self.call_intrinsic("llvm.instrprof.increment", &[], &[fn_name, hash, num_counters, index]);
1895    }
1896}