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 as abi;
11use rustc_abi::{Align, Size, WrappingRange};
12use rustc_codegen_ssa::MemFlags;
13use rustc_codegen_ssa::common::{IntPredicate, RealPredicate, SynchronizationScope, TypeKind};
14use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
15use rustc_codegen_ssa::mir::place::PlaceRef;
16use rustc_codegen_ssa::traits::*;
17use rustc_data_structures::small_c_str::SmallCStr;
18use rustc_hir::def_id::DefId;
19use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
20use rustc_middle::ty::layout::{
21 FnAbiError, FnAbiOfHelpers, FnAbiRequest, HasTypingEnv, LayoutError, LayoutOfHelpers,
22 TyAndLayout,
23};
24use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
25use rustc_sanitizers::{cfi, kcfi};
26use rustc_session::config::OptLevel;
27use rustc_span::Span;
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}
48
49pub(crate) type SBuilder<'a, 'll> = GenericBuilder<'a, 'll, SCx<'ll>>;
50pub(crate) type Builder<'a, 'll, 'tcx> = GenericBuilder<'a, 'll, FullCx<'ll, 'tcx>>;
51
52impl<'a, 'll, CX: Borrow<SCx<'ll>>> Drop for GenericBuilder<'a, 'll, CX> {
53 fn drop(&mut self) {
54 unsafe {
55 llvm::LLVMDisposeBuilder(&mut *(self.llbuilder as *mut _));
56 }
57 }
58}
59
60impl<'a, 'll> SBuilder<'a, 'll> {
61 pub(crate) fn call(
62 &mut self,
63 llty: &'ll Type,
64 llfn: &'ll Value,
65 args: &[&'ll Value],
66 funclet: Option<&Funclet<'ll>>,
67 ) -> &'ll Value {
68 debug!("call {:?} with args ({:?})", llfn, args);
69
70 let args = self.check_call("call", llty, llfn, args);
71 let funclet_bundle = funclet.map(|funclet| funclet.bundle());
72 let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
73 if let Some(funclet_bundle) = funclet_bundle {
74 bundles.push(funclet_bundle);
75 }
76
77 let call = unsafe {
78 llvm::LLVMBuildCallWithOperandBundles(
79 self.llbuilder,
80 llty,
81 llfn,
82 args.as_ptr() as *const &llvm::Value,
83 args.len() as c_uint,
84 bundles.as_ptr(),
85 bundles.len() as c_uint,
86 c"".as_ptr(),
87 )
88 };
89 call
90 }
91}
92
93impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
94 fn with_cx(scx: &'a GenericCx<'ll, CX>) -> Self {
95 let llbuilder = unsafe { llvm::LLVMCreateBuilderInContext(scx.deref().borrow().llcx) };
97 GenericBuilder { llbuilder, cx: scx }
98 }
99
100 pub(crate) fn bitcast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
101 unsafe { llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty, UNNAMED) }
102 }
103
104 pub(crate) fn ret_void(&mut self) {
105 llvm::LLVMBuildRetVoid(self.llbuilder);
106 }
107
108 pub(crate) fn ret(&mut self, v: &'ll Value) {
109 unsafe {
110 llvm::LLVMBuildRet(self.llbuilder, v);
111 }
112 }
113
114 pub(crate) fn build(cx: &'a GenericCx<'ll, CX>, llbb: &'ll BasicBlock) -> Self {
115 let bx = Self::with_cx(cx);
116 unsafe {
117 llvm::LLVMPositionBuilderAtEnd(bx.llbuilder, llbb);
118 }
119 bx
120 }
121
122 pub(crate) fn direct_alloca(&mut self, ty: &'ll Type, align: Align, name: &str) -> &'ll Value {
127 let val = unsafe {
128 let alloca = llvm::LLVMBuildAlloca(self.llbuilder, ty, UNNAMED);
129 llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
130 llvm::LLVMBuildPointerCast(self.llbuilder, alloca, self.cx.type_ptr(), UNNAMED)
132 };
133 if name != "" {
134 let name = std::ffi::CString::new(name).unwrap();
135 llvm::set_value_name(val, &name.as_bytes());
136 }
137 val
138 }
139
140 pub(crate) fn inbounds_gep(
141 &mut self,
142 ty: &'ll Type,
143 ptr: &'ll Value,
144 indices: &[&'ll Value],
145 ) -> &'ll Value {
146 unsafe {
147 llvm::LLVMBuildGEPWithNoWrapFlags(
148 self.llbuilder,
149 ty,
150 ptr,
151 indices.as_ptr(),
152 indices.len() as c_uint,
153 UNNAMED,
154 GEPNoWrapFlags::InBounds,
155 )
156 }
157 }
158
159 pub(crate) fn store(&mut self, val: &'ll Value, ptr: &'ll Value, align: Align) -> &'ll Value {
160 debug!("Store {:?} -> {:?}", val, ptr);
161 assert_eq!(self.cx.type_kind(self.cx.val_ty(ptr)), TypeKind::Pointer);
162 unsafe {
163 let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
164 llvm::LLVMSetAlignment(store, align.bytes() as c_uint);
165 store
166 }
167 }
168
169 pub(crate) fn load(&mut self, ty: &'ll Type, ptr: &'ll Value, align: Align) -> &'ll Value {
170 unsafe {
171 let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
172 llvm::LLVMSetAlignment(load, align.bytes() as c_uint);
173 load
174 }
175 }
176
177 fn memset(&mut self, ptr: &'ll Value, fill_byte: &'ll Value, size: &'ll Value, align: Align) {
178 unsafe {
179 llvm::LLVMRustBuildMemSet(
180 self.llbuilder,
181 ptr,
182 align.bytes() as c_uint,
183 fill_byte,
184 size,
185 false,
186 );
187 }
188 }
189}
190
191pub(crate) const UNNAMED: *const c_char = c"".as_ptr();
195
196impl<'ll, CX: Borrow<SCx<'ll>>> BackendTypes for GenericBuilder<'_, 'll, CX> {
197 type Value = <GenericCx<'ll, CX> as BackendTypes>::Value;
198 type Metadata = <GenericCx<'ll, CX> as BackendTypes>::Metadata;
199 type Function = <GenericCx<'ll, CX> as BackendTypes>::Function;
200 type BasicBlock = <GenericCx<'ll, CX> as BackendTypes>::BasicBlock;
201 type Type = <GenericCx<'ll, CX> as BackendTypes>::Type;
202 type Funclet = <GenericCx<'ll, CX> as BackendTypes>::Funclet;
203
204 type DIScope = <GenericCx<'ll, CX> as BackendTypes>::DIScope;
205 type DILocation = <GenericCx<'ll, CX> as BackendTypes>::DILocation;
206 type DIVariable = <GenericCx<'ll, CX> as BackendTypes>::DIVariable;
207}
208
209impl abi::HasDataLayout for Builder<'_, '_, '_> {
210 fn data_layout(&self) -> &abi::TargetDataLayout {
211 self.cx.data_layout()
212 }
213}
214
215impl<'tcx> ty::layout::HasTyCtxt<'tcx> for Builder<'_, '_, 'tcx> {
216 #[inline]
217 fn tcx(&self) -> TyCtxt<'tcx> {
218 self.cx.tcx
219 }
220}
221
222impl<'tcx> ty::layout::HasTypingEnv<'tcx> for Builder<'_, '_, 'tcx> {
223 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
224 self.cx.typing_env()
225 }
226}
227
228impl HasTargetSpec for Builder<'_, '_, '_> {
229 #[inline]
230 fn target_spec(&self) -> &Target {
231 self.cx.target_spec()
232 }
233}
234
235impl<'tcx> LayoutOfHelpers<'tcx> for Builder<'_, '_, 'tcx> {
236 #[inline]
237 fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
238 self.cx.handle_layout_err(err, span, ty)
239 }
240}
241
242impl<'tcx> FnAbiOfHelpers<'tcx> for Builder<'_, '_, 'tcx> {
243 #[inline]
244 fn handle_fn_abi_err(
245 &self,
246 err: FnAbiError<'tcx>,
247 span: Span,
248 fn_abi_request: FnAbiRequest<'tcx>,
249 ) -> ! {
250 self.cx.handle_fn_abi_err(err, span, fn_abi_request)
251 }
252}
253
254impl<'ll, 'tcx> Deref for Builder<'_, 'll, 'tcx> {
255 type Target = CodegenCx<'ll, 'tcx>;
256
257 #[inline]
258 fn deref(&self) -> &Self::Target {
259 self.cx
260 }
261}
262
263macro_rules! math_builder_methods {
264 ($($name:ident($($arg:ident),*) => $llvm_capi:ident),+ $(,)?) => {
265 $(fn $name(&mut self, $($arg: &'ll Value),*) -> &'ll Value {
266 unsafe {
267 llvm::$llvm_capi(self.llbuilder, $($arg,)* UNNAMED)
268 }
269 })+
270 }
271}
272
273macro_rules! set_math_builder_methods {
274 ($($name:ident($($arg:ident),*) => ($llvm_capi:ident, $llvm_set_math:ident)),+ $(,)?) => {
275 $(fn $name(&mut self, $($arg: &'ll Value),*) -> &'ll Value {
276 unsafe {
277 let instr = llvm::$llvm_capi(self.llbuilder, $($arg,)* UNNAMED);
278 llvm::$llvm_set_math(instr);
279 instr
280 }
281 })+
282 }
283}
284
285impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> {
286 type CodegenCx = CodegenCx<'ll, 'tcx>;
287
288 fn build(cx: &'a CodegenCx<'ll, 'tcx>, llbb: &'ll BasicBlock) -> Self {
289 let bx = Builder::with_cx(cx);
290 unsafe {
291 llvm::LLVMPositionBuilderAtEnd(bx.llbuilder, llbb);
292 }
293 bx
294 }
295
296 fn cx(&self) -> &CodegenCx<'ll, 'tcx> {
297 self.cx
298 }
299
300 fn llbb(&self) -> &'ll BasicBlock {
301 unsafe { llvm::LLVMGetInsertBlock(self.llbuilder) }
302 }
303
304 fn set_span(&mut self, _span: Span) {}
305
306 fn append_block(cx: &'a CodegenCx<'ll, 'tcx>, llfn: &'ll Value, name: &str) -> &'ll BasicBlock {
307 unsafe {
308 let name = SmallCStr::new(name);
309 llvm::LLVMAppendBasicBlockInContext(cx.llcx, llfn, name.as_ptr())
310 }
311 }
312
313 fn append_sibling_block(&mut self, name: &str) -> &'ll BasicBlock {
314 Self::append_block(self.cx, self.llfn(), name)
315 }
316
317 fn switch_to_block(&mut self, llbb: Self::BasicBlock) {
318 *self = Self::build(self.cx, llbb)
319 }
320
321 fn ret_void(&mut self) {
322 llvm::LLVMBuildRetVoid(self.llbuilder);
323 }
324
325 fn ret(&mut self, v: &'ll Value) {
326 unsafe {
327 llvm::LLVMBuildRet(self.llbuilder, v);
328 }
329 }
330
331 fn br(&mut self, dest: &'ll BasicBlock) {
332 unsafe {
333 llvm::LLVMBuildBr(self.llbuilder, dest);
334 }
335 }
336
337 fn cond_br(
338 &mut self,
339 cond: &'ll Value,
340 then_llbb: &'ll BasicBlock,
341 else_llbb: &'ll BasicBlock,
342 ) {
343 unsafe {
344 llvm::LLVMBuildCondBr(self.llbuilder, cond, then_llbb, else_llbb);
345 }
346 }
347
348 fn switch(
349 &mut self,
350 v: &'ll Value,
351 else_llbb: &'ll BasicBlock,
352 cases: impl ExactSizeIterator<Item = (u128, &'ll BasicBlock)>,
353 ) {
354 let switch =
355 unsafe { llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, cases.len() as c_uint) };
356 for (on_val, dest) in cases {
357 let on_val = self.const_uint_big(self.val_ty(v), on_val);
358 unsafe { llvm::LLVMAddCase(switch, on_val, dest) }
359 }
360 }
361
362 fn switch_with_weights(
363 &mut self,
364 v: Self::Value,
365 else_llbb: Self::BasicBlock,
366 else_is_cold: bool,
367 cases: impl ExactSizeIterator<Item = (u128, Self::BasicBlock, bool)>,
368 ) {
369 if self.cx.sess().opts.optimize == rustc_session::config::OptLevel::No {
370 self.switch(v, else_llbb, cases.map(|(val, dest, _)| (val, dest)));
371 return;
372 }
373
374 let id = self.cx.create_metadata(b"branch_weights");
375
376 let cold_weight = llvm::LLVMValueAsMetadata(self.cx.const_u32(1));
381 let hot_weight = llvm::LLVMValueAsMetadata(self.cx.const_u32(2000));
382 let weight =
383 |is_cold: bool| -> &Metadata { if is_cold { cold_weight } else { hot_weight } };
384
385 let mut md: SmallVec<[&Metadata; 16]> = SmallVec::with_capacity(cases.len() + 2);
386 md.push(id);
387 md.push(weight(else_is_cold));
388
389 let switch =
390 unsafe { llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, cases.len() as c_uint) };
391 for (on_val, dest, is_cold) in cases {
392 let on_val = self.const_uint_big(self.val_ty(v), on_val);
393 unsafe { llvm::LLVMAddCase(switch, on_val, dest) }
394 md.push(weight(is_cold));
395 }
396
397 self.cx.set_metadata_node(switch, llvm::MD_prof, &md);
398 }
399
400 fn invoke(
401 &mut self,
402 llty: &'ll Type,
403 fn_attrs: Option<&CodegenFnAttrs>,
404 fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
405 llfn: &'ll Value,
406 args: &[&'ll Value],
407 then: &'ll BasicBlock,
408 catch: &'ll BasicBlock,
409 funclet: Option<&Funclet<'ll>>,
410 instance: Option<Instance<'tcx>>,
411 ) -> &'ll Value {
412 debug!("invoke {:?} with args ({:?})", llfn, args);
413
414 let args = self.check_call("invoke", llty, llfn, args);
415 let funclet_bundle = funclet.map(|funclet| funclet.bundle());
416 let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
417 if let Some(funclet_bundle) = funclet_bundle {
418 bundles.push(funclet_bundle);
419 }
420
421 self.cfi_type_test(fn_attrs, fn_abi, instance, llfn);
423
424 let kcfi_bundle = self.kcfi_operand_bundle(fn_attrs, fn_abi, instance, llfn);
426 if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
427 bundles.push(kcfi_bundle);
428 }
429
430 let invoke = unsafe {
431 llvm::LLVMBuildInvokeWithOperandBundles(
432 self.llbuilder,
433 llty,
434 llfn,
435 args.as_ptr(),
436 args.len() as c_uint,
437 then,
438 catch,
439 bundles.as_ptr(),
440 bundles.len() as c_uint,
441 UNNAMED,
442 )
443 };
444 if let Some(fn_abi) = fn_abi {
445 fn_abi.apply_attrs_callsite(self, invoke);
446 }
447 invoke
448 }
449
450 fn unreachable(&mut self) {
451 unsafe {
452 llvm::LLVMBuildUnreachable(self.llbuilder);
453 }
454 }
455
456 math_builder_methods! {
457 add(a, b) => LLVMBuildAdd,
458 fadd(a, b) => LLVMBuildFAdd,
459 sub(a, b) => LLVMBuildSub,
460 fsub(a, b) => LLVMBuildFSub,
461 mul(a, b) => LLVMBuildMul,
462 fmul(a, b) => LLVMBuildFMul,
463 udiv(a, b) => LLVMBuildUDiv,
464 exactudiv(a, b) => LLVMBuildExactUDiv,
465 sdiv(a, b) => LLVMBuildSDiv,
466 exactsdiv(a, b) => LLVMBuildExactSDiv,
467 fdiv(a, b) => LLVMBuildFDiv,
468 urem(a, b) => LLVMBuildURem,
469 srem(a, b) => LLVMBuildSRem,
470 frem(a, b) => LLVMBuildFRem,
471 shl(a, b) => LLVMBuildShl,
472 lshr(a, b) => LLVMBuildLShr,
473 ashr(a, b) => LLVMBuildAShr,
474 and(a, b) => LLVMBuildAnd,
475 or(a, b) => LLVMBuildOr,
476 xor(a, b) => LLVMBuildXor,
477 neg(x) => LLVMBuildNeg,
478 fneg(x) => LLVMBuildFNeg,
479 not(x) => LLVMBuildNot,
480 unchecked_sadd(x, y) => LLVMBuildNSWAdd,
481 unchecked_uadd(x, y) => LLVMBuildNUWAdd,
482 unchecked_ssub(x, y) => LLVMBuildNSWSub,
483 unchecked_usub(x, y) => LLVMBuildNUWSub,
484 unchecked_smul(x, y) => LLVMBuildNSWMul,
485 unchecked_umul(x, y) => LLVMBuildNUWMul,
486 }
487
488 fn unchecked_suadd(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
489 unsafe {
490 let add = llvm::LLVMBuildAdd(self.llbuilder, a, b, UNNAMED);
491 if llvm::LLVMIsAInstruction(add).is_some() {
492 llvm::LLVMSetNUW(add, TRUE);
493 llvm::LLVMSetNSW(add, TRUE);
494 }
495 add
496 }
497 }
498 fn unchecked_susub(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
499 unsafe {
500 let sub = llvm::LLVMBuildSub(self.llbuilder, a, b, UNNAMED);
501 if llvm::LLVMIsAInstruction(sub).is_some() {
502 llvm::LLVMSetNUW(sub, TRUE);
503 llvm::LLVMSetNSW(sub, TRUE);
504 }
505 sub
506 }
507 }
508 fn unchecked_sumul(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
509 unsafe {
510 let mul = llvm::LLVMBuildMul(self.llbuilder, a, b, UNNAMED);
511 if llvm::LLVMIsAInstruction(mul).is_some() {
512 llvm::LLVMSetNUW(mul, TRUE);
513 llvm::LLVMSetNSW(mul, TRUE);
514 }
515 mul
516 }
517 }
518
519 fn or_disjoint(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
520 unsafe {
521 let or = llvm::LLVMBuildOr(self.llbuilder, a, b, UNNAMED);
522
523 if llvm::LLVMIsAInstruction(or).is_some() {
527 llvm::LLVMSetIsDisjoint(or, TRUE);
528 }
529 or
530 }
531 }
532
533 set_math_builder_methods! {
534 fadd_fast(x, y) => (LLVMBuildFAdd, LLVMRustSetFastMath),
535 fsub_fast(x, y) => (LLVMBuildFSub, LLVMRustSetFastMath),
536 fmul_fast(x, y) => (LLVMBuildFMul, LLVMRustSetFastMath),
537 fdiv_fast(x, y) => (LLVMBuildFDiv, LLVMRustSetFastMath),
538 frem_fast(x, y) => (LLVMBuildFRem, LLVMRustSetFastMath),
539 fadd_algebraic(x, y) => (LLVMBuildFAdd, LLVMRustSetAlgebraicMath),
540 fsub_algebraic(x, y) => (LLVMBuildFSub, LLVMRustSetAlgebraicMath),
541 fmul_algebraic(x, y) => (LLVMBuildFMul, LLVMRustSetAlgebraicMath),
542 fdiv_algebraic(x, y) => (LLVMBuildFDiv, LLVMRustSetAlgebraicMath),
543 frem_algebraic(x, y) => (LLVMBuildFRem, LLVMRustSetAlgebraicMath),
544 }
545
546 fn checked_binop(
547 &mut self,
548 oop: OverflowOp,
549 ty: Ty<'tcx>,
550 lhs: Self::Value,
551 rhs: Self::Value,
552 ) -> (Self::Value, Self::Value) {
553 let (size, signed) = ty.int_size_and_signed(self.tcx);
554 let width = size.bits();
555
556 if !signed {
557 match oop {
558 OverflowOp::Sub => {
559 let sub = self.sub(lhs, rhs);
563 let cmp = self.icmp(IntPredicate::IntULT, lhs, rhs);
564 return (sub, cmp);
565 }
566 OverflowOp::Add => {
567 let add = self.add(lhs, rhs);
570 let cmp = self.icmp(IntPredicate::IntULT, add, lhs);
571 return (add, cmp);
572 }
573 OverflowOp::Mul => {}
574 }
575 }
576
577 let oop_str = match oop {
578 OverflowOp::Add => "add",
579 OverflowOp::Sub => "sub",
580 OverflowOp::Mul => "mul",
581 };
582
583 let name = format!("llvm.{}{oop_str}.with.overflow", if signed { 's' } else { 'u' });
584
585 let res = self.call_intrinsic(name, &[self.type_ix(width)], &[lhs, rhs]);
586 (self.extract_value(res, 0), self.extract_value(res, 1))
587 }
588
589 fn from_immediate(&mut self, val: Self::Value) -> Self::Value {
590 if self.cx().val_ty(val) == self.cx().type_i1() {
591 self.zext(val, self.cx().type_i8())
592 } else {
593 val
594 }
595 }
596
597 fn to_immediate_scalar(&mut self, val: Self::Value, scalar: abi::Scalar) -> Self::Value {
598 if scalar.is_bool() {
599 return self.unchecked_utrunc(val, self.cx().type_i1());
600 }
601 val
602 }
603
604 fn alloca(&mut self, size: Size, align: Align) -> &'ll Value {
605 let mut bx = Builder::with_cx(self.cx);
606 bx.position_at_start(unsafe { llvm::LLVMGetFirstBasicBlock(self.llfn()) });
607 let ty = self.cx().type_array(self.cx().type_i8(), size.bytes());
608 unsafe {
609 let alloca = llvm::LLVMBuildAlloca(bx.llbuilder, ty, UNNAMED);
610 llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
611 llvm::LLVMBuildPointerCast(bx.llbuilder, alloca, self.cx().type_ptr(), UNNAMED)
613 }
614 }
615
616 fn load(&mut self, ty: &'ll Type, ptr: &'ll Value, align: Align) -> &'ll Value {
617 unsafe {
618 let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
619 let align = align.min(self.cx().tcx.sess.target.max_reliable_alignment());
620 llvm::LLVMSetAlignment(load, align.bytes() as c_uint);
621 load
622 }
623 }
624
625 fn volatile_load(&mut self, ty: &'ll Type, ptr: &'ll Value) -> &'ll Value {
626 unsafe {
627 let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
628 llvm::LLVMSetVolatile(load, llvm::TRUE);
629 load
630 }
631 }
632
633 fn atomic_load(
634 &mut self,
635 ty: &'ll Type,
636 ptr: &'ll Value,
637 order: rustc_middle::ty::AtomicOrdering,
638 size: Size,
639 ) -> &'ll Value {
640 unsafe {
641 let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
642 llvm::LLVMSetOrdering(load, AtomicOrdering::from_generic(order));
644 llvm::LLVMSetAlignment(load, size.bytes() as c_uint);
646 load
647 }
648 }
649
650 #[instrument(level = "trace", skip(self))]
651 fn load_operand(&mut self, place: PlaceRef<'tcx, &'ll Value>) -> OperandRef<'tcx, &'ll Value> {
652 if place.layout.is_unsized() {
653 let tail = self.tcx.struct_tail_for_codegen(place.layout.ty, self.typing_env());
654 if matches!(tail.kind(), ty::Foreign(..)) {
655 panic!("unsized locals must not be `extern` types");
659 }
660 }
661 assert_eq!(place.val.llextra.is_some(), place.layout.is_unsized());
662
663 if place.layout.is_zst() {
664 return OperandRef::zero_sized(place.layout);
665 }
666
667 #[instrument(level = "trace", skip(bx))]
668 fn scalar_load_metadata<'a, 'll, 'tcx>(
669 bx: &mut Builder<'a, 'll, 'tcx>,
670 load: &'ll Value,
671 scalar: abi::Scalar,
672 layout: TyAndLayout<'tcx>,
673 offset: Size,
674 ) {
675 if bx.cx.sess().opts.optimize == OptLevel::No {
676 return;
678 }
679
680 if !scalar.is_uninit_valid() {
681 bx.noundef_metadata(load);
682 }
683
684 match scalar.primitive() {
685 abi::Primitive::Int(..) => {
686 if !scalar.is_always_valid(bx) {
687 bx.range_metadata(load, scalar.valid_range(bx));
688 }
689 }
690 abi::Primitive::Pointer(_) => {
691 if !scalar.valid_range(bx).contains(0) {
692 bx.nonnull_metadata(load);
693 }
694
695 if let Some(pointee) = layout.pointee_info_at(bx, offset)
696 && let Some(_) = pointee.safe
697 {
698 bx.align_metadata(load, pointee.align);
699 }
700 }
701 abi::Primitive::Float(_) => {}
702 }
703 }
704
705 let val = if let Some(_) = place.val.llextra {
706 OperandValue::Ref(place.val)
708 } else if place.layout.is_llvm_immediate() {
709 let mut const_llval = None;
710 let llty = place.layout.llvm_type(self);
711 if let Some(global) = llvm::LLVMIsAGlobalVariable(place.val.llval) {
712 if llvm::LLVMIsGlobalConstant(global).is_true() {
713 if let Some(init) = llvm::LLVMGetInitializer(global) {
714 if self.val_ty(init) == llty {
715 const_llval = Some(init);
716 }
717 }
718 }
719 }
720
721 let llval = const_llval.unwrap_or_else(|| {
722 let load = self.load(llty, place.val.llval, place.val.align);
723 if let abi::BackendRepr::Scalar(scalar) = place.layout.backend_repr {
724 scalar_load_metadata(self, load, scalar, place.layout, Size::ZERO);
725 self.to_immediate_scalar(load, scalar)
726 } else {
727 load
728 }
729 });
730 OperandValue::Immediate(llval)
731 } else if let abi::BackendRepr::ScalarPair(a, b) = place.layout.backend_repr {
732 let b_offset = a.size(self).align_to(b.align(self).abi);
733
734 let mut load = |i, scalar: abi::Scalar, layout, align, offset| {
735 let llptr = if i == 0 {
736 place.val.llval
737 } else {
738 self.inbounds_ptradd(place.val.llval, self.const_usize(b_offset.bytes()))
739 };
740 let llty = place.layout.scalar_pair_element_llvm_type(self, i, false);
741 let load = self.load(llty, llptr, align);
742 scalar_load_metadata(self, load, scalar, layout, offset);
743 self.to_immediate_scalar(load, scalar)
744 };
745
746 OperandValue::Pair(
747 load(0, a, place.layout, place.val.align, Size::ZERO),
748 load(1, b, place.layout, place.val.align.restrict_for_offset(b_offset), b_offset),
749 )
750 } else {
751 OperandValue::Ref(place.val)
752 };
753
754 OperandRef { val, layout: place.layout, move_annotation: None }
755 }
756
757 fn write_operand_repeatedly(
758 &mut self,
759 cg_elem: OperandRef<'tcx, &'ll Value>,
760 count: u64,
761 dest: PlaceRef<'tcx, &'ll Value>,
762 ) {
763 let zero = self.const_usize(0);
764 let count = self.const_usize(count);
765
766 let header_bb = self.append_sibling_block("repeat_loop_header");
767 let body_bb = self.append_sibling_block("repeat_loop_body");
768 let next_bb = self.append_sibling_block("repeat_loop_next");
769
770 self.br(header_bb);
771
772 let mut header_bx = Self::build(self.cx, header_bb);
773 let i = header_bx.phi(self.val_ty(zero), &[zero], &[self.llbb()]);
774
775 let keep_going = header_bx.icmp(IntPredicate::IntULT, i, count);
776 header_bx.cond_br(keep_going, body_bb, next_bb);
777
778 let mut body_bx = Self::build(self.cx, body_bb);
779 let dest_elem = dest.project_index(&mut body_bx, i);
780 cg_elem.val.store(&mut body_bx, dest_elem);
781
782 let next = body_bx.unchecked_uadd(i, self.const_usize(1));
783 body_bx.br(header_bb);
784 header_bx.add_incoming_to_phi(i, next, body_bb);
785
786 *self = Self::build(self.cx, next_bb);
787 }
788
789 fn range_metadata(&mut self, load: &'ll Value, range: WrappingRange) {
790 if self.cx.sess().opts.optimize == OptLevel::No {
791 return;
793 }
794
795 let llty = self.cx.val_ty(load);
796 let md = [
797 llvm::LLVMValueAsMetadata(self.cx.const_uint_big(llty, range.start)),
798 llvm::LLVMValueAsMetadata(self.cx.const_uint_big(llty, range.end.wrapping_add(1))),
799 ];
800 self.set_metadata_node(load, llvm::MD_range, &md);
801 }
802
803 fn nonnull_metadata(&mut self, load: &'ll Value) {
804 self.set_metadata_node(load, llvm::MD_nonnull, &[]);
805 }
806
807 fn store(&mut self, val: &'ll Value, ptr: &'ll Value, align: Align) -> &'ll Value {
808 self.store_with_flags(val, ptr, align, MemFlags::empty())
809 }
810
811 fn store_with_flags(
812 &mut self,
813 val: &'ll Value,
814 ptr: &'ll Value,
815 align: Align,
816 flags: MemFlags,
817 ) -> &'ll Value {
818 debug!("Store {:?} -> {:?} ({:?})", val, ptr, flags);
819 assert_eq!(self.cx.type_kind(self.cx.val_ty(ptr)), TypeKind::Pointer);
820 unsafe {
821 let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
822 let align = align.min(self.cx().tcx.sess.target.max_reliable_alignment());
823 let align =
824 if flags.contains(MemFlags::UNALIGNED) { 1 } else { align.bytes() as c_uint };
825 llvm::LLVMSetAlignment(store, align);
826 if flags.contains(MemFlags::VOLATILE) {
827 llvm::LLVMSetVolatile(store, llvm::TRUE);
828 }
829 if flags.contains(MemFlags::NONTEMPORAL) {
830 let use_nontemporal = matches!(
843 self.cx.tcx.sess.target.arch,
844 Arch::AArch64 | Arch::Arm | Arch::RiscV32 | Arch::RiscV64
845 );
846 if use_nontemporal {
847 let one = llvm::LLVMValueAsMetadata(self.cx.const_i32(1));
852 self.set_metadata_node(store, llvm::MD_nontemporal, &[one]);
853 }
854 }
855 store
856 }
857 }
858
859 fn atomic_store(
860 &mut self,
861 val: &'ll Value,
862 ptr: &'ll Value,
863 order: rustc_middle::ty::AtomicOrdering,
864 size: Size,
865 ) {
866 debug!("Store {:?} -> {:?}", val, ptr);
867 assert_eq!(self.cx.type_kind(self.cx.val_ty(ptr)), TypeKind::Pointer);
868 unsafe {
869 let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
870 llvm::LLVMSetOrdering(store, AtomicOrdering::from_generic(order));
872 llvm::LLVMSetAlignment(store, size.bytes() as c_uint);
874 }
875 }
876
877 fn gep(&mut self, ty: &'ll Type, ptr: &'ll Value, indices: &[&'ll Value]) -> &'ll Value {
878 unsafe {
879 llvm::LLVMBuildGEPWithNoWrapFlags(
880 self.llbuilder,
881 ty,
882 ptr,
883 indices.as_ptr(),
884 indices.len() as c_uint,
885 UNNAMED,
886 GEPNoWrapFlags::default(),
887 )
888 }
889 }
890
891 fn inbounds_gep(
892 &mut self,
893 ty: &'ll Type,
894 ptr: &'ll Value,
895 indices: &[&'ll Value],
896 ) -> &'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::InBounds,
906 )
907 }
908 }
909
910 fn inbounds_nuw_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 | GEPNoWrapFlags::NUW,
925 )
926 }
927 }
928
929 fn trunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
931 unsafe { llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
932 }
933
934 fn unchecked_utrunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
935 debug_assert_ne!(self.val_ty(val), dest_ty);
936
937 let trunc = self.trunc(val, dest_ty);
938 unsafe {
939 if llvm::LLVMIsAInstruction(trunc).is_some() {
940 llvm::LLVMSetNUW(trunc, TRUE);
941 }
942 }
943 trunc
944 }
945
946 fn unchecked_strunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
947 debug_assert_ne!(self.val_ty(val), dest_ty);
948
949 let trunc = self.trunc(val, dest_ty);
950 unsafe {
951 if llvm::LLVMIsAInstruction(trunc).is_some() {
952 llvm::LLVMSetNSW(trunc, TRUE);
953 }
954 }
955 trunc
956 }
957
958 fn sext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
959 unsafe { llvm::LLVMBuildSExt(self.llbuilder, val, dest_ty, UNNAMED) }
960 }
961
962 fn fptoui_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
963 self.call_intrinsic("llvm.fptoui.sat", &[dest_ty, self.val_ty(val)], &[val])
964 }
965
966 fn fptosi_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
967 self.call_intrinsic("llvm.fptosi.sat", &[dest_ty, self.val_ty(val)], &[val])
968 }
969
970 fn fptoui(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
971 if self.sess().target.is_like_wasm {
986 let src_ty = self.cx.val_ty(val);
987 if self.cx.type_kind(src_ty) != TypeKind::Vector {
988 let float_width = self.cx.float_width(src_ty);
989 let int_width = self.cx.int_width(dest_ty);
990 if matches!((int_width, float_width), (32 | 64, 32 | 64)) {
991 return self.call_intrinsic(
992 "llvm.wasm.trunc.unsigned",
993 &[dest_ty, src_ty],
994 &[val],
995 );
996 }
997 }
998 }
999 unsafe { llvm::LLVMBuildFPToUI(self.llbuilder, val, dest_ty, UNNAMED) }
1000 }
1001
1002 fn fptosi(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1003 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.signed",
1012 &[dest_ty, src_ty],
1013 &[val],
1014 );
1015 }
1016 }
1017 }
1018 unsafe { llvm::LLVMBuildFPToSI(self.llbuilder, val, dest_ty, UNNAMED) }
1019 }
1020
1021 fn uitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1022 unsafe { llvm::LLVMBuildUIToFP(self.llbuilder, val, dest_ty, UNNAMED) }
1023 }
1024
1025 fn sitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1026 unsafe { llvm::LLVMBuildSIToFP(self.llbuilder, val, dest_ty, UNNAMED) }
1027 }
1028
1029 fn fptrunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1030 unsafe { llvm::LLVMBuildFPTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
1031 }
1032
1033 fn fpext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1034 unsafe { llvm::LLVMBuildFPExt(self.llbuilder, val, dest_ty, UNNAMED) }
1035 }
1036
1037 fn ptrtoint(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1038 unsafe { llvm::LLVMBuildPtrToInt(self.llbuilder, val, dest_ty, UNNAMED) }
1039 }
1040
1041 fn inttoptr(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1042 unsafe { llvm::LLVMBuildIntToPtr(self.llbuilder, val, dest_ty, UNNAMED) }
1043 }
1044
1045 fn bitcast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1046 unsafe { llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty, UNNAMED) }
1047 }
1048
1049 fn intcast(&mut self, val: &'ll Value, dest_ty: &'ll Type, is_signed: bool) -> &'ll Value {
1050 unsafe {
1051 llvm::LLVMBuildIntCast2(self.llbuilder, val, dest_ty, is_signed.to_llvm_bool(), UNNAMED)
1052 }
1053 }
1054
1055 fn pointercast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1056 unsafe { llvm::LLVMBuildPointerCast(self.llbuilder, val, dest_ty, UNNAMED) }
1057 }
1058
1059 fn icmp(&mut self, op: IntPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1061 let op = llvm::IntPredicate::from_generic(op);
1062 unsafe { llvm::LLVMBuildICmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
1063 }
1064
1065 fn fcmp(&mut self, op: RealPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1066 let op = llvm::RealPredicate::from_generic(op);
1067 unsafe { llvm::LLVMBuildFCmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
1068 }
1069
1070 fn three_way_compare(
1071 &mut self,
1072 ty: Ty<'tcx>,
1073 lhs: Self::Value,
1074 rhs: Self::Value,
1075 ) -> Self::Value {
1076 let size = ty.primitive_size(self.tcx);
1077 let name = if ty.is_signed() { "llvm.scmp" } else { "llvm.ucmp" };
1078
1079 self.call_intrinsic(name, &[self.type_i8(), self.type_ix(size.bits())], &[lhs, rhs])
1080 }
1081
1082 fn memcpy(
1084 &mut self,
1085 dst: &'ll Value,
1086 dst_align: Align,
1087 src: &'ll Value,
1088 src_align: Align,
1089 size: &'ll Value,
1090 flags: MemFlags,
1091 tt: Option<FncTree>,
1092 ) {
1093 assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memcpy not supported");
1094 let size = self.intcast(size, self.type_isize(), false);
1095 let is_volatile = flags.contains(MemFlags::VOLATILE);
1096 let memcpy = unsafe {
1097 llvm::LLVMRustBuildMemCpy(
1098 self.llbuilder,
1099 dst,
1100 dst_align.bytes() as c_uint,
1101 src,
1102 src_align.bytes() as c_uint,
1103 size,
1104 is_volatile,
1105 )
1106 };
1107
1108 if let Some(tt) = tt {
1114 crate::typetree::add_tt(self.cx().llmod, self.cx().llcx, memcpy, tt);
1115 }
1116 }
1117
1118 fn memmove(
1119 &mut self,
1120 dst: &'ll Value,
1121 dst_align: Align,
1122 src: &'ll Value,
1123 src_align: Align,
1124 size: &'ll Value,
1125 flags: MemFlags,
1126 ) {
1127 assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memmove not supported");
1128 let size = self.intcast(size, self.type_isize(), false);
1129 let is_volatile = flags.contains(MemFlags::VOLATILE);
1130 unsafe {
1131 llvm::LLVMRustBuildMemMove(
1132 self.llbuilder,
1133 dst,
1134 dst_align.bytes() as c_uint,
1135 src,
1136 src_align.bytes() as c_uint,
1137 size,
1138 is_volatile,
1139 );
1140 }
1141 }
1142
1143 fn memset(
1144 &mut self,
1145 ptr: &'ll Value,
1146 fill_byte: &'ll Value,
1147 size: &'ll Value,
1148 align: Align,
1149 flags: MemFlags,
1150 ) {
1151 assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memset not supported");
1152 let is_volatile = flags.contains(MemFlags::VOLATILE);
1153 unsafe {
1154 llvm::LLVMRustBuildMemSet(
1155 self.llbuilder,
1156 ptr,
1157 align.bytes() as c_uint,
1158 fill_byte,
1159 size,
1160 is_volatile,
1161 );
1162 }
1163 }
1164
1165 fn select(
1166 &mut self,
1167 cond: &'ll Value,
1168 then_val: &'ll Value,
1169 else_val: &'ll Value,
1170 ) -> &'ll Value {
1171 unsafe { llvm::LLVMBuildSelect(self.llbuilder, cond, then_val, else_val, UNNAMED) }
1172 }
1173
1174 fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
1175 unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
1176 }
1177
1178 fn extract_element(&mut self, vec: &'ll Value, idx: &'ll Value) -> &'ll Value {
1179 unsafe { llvm::LLVMBuildExtractElement(self.llbuilder, vec, idx, UNNAMED) }
1180 }
1181
1182 fn vector_splat(&mut self, num_elts: usize, elt: &'ll Value) -> &'ll Value {
1183 unsafe {
1184 let elt_ty = self.cx.val_ty(elt);
1185 let undef = llvm::LLVMGetUndef(self.type_vector(elt_ty, num_elts as u64));
1186 let vec = self.insert_element(undef, elt, self.cx.const_i32(0));
1187 let vec_i32_ty = self.type_vector(self.type_i32(), num_elts as u64);
1188 self.shuffle_vector(vec, undef, self.const_null(vec_i32_ty))
1189 }
1190 }
1191
1192 fn extract_value(&mut self, agg_val: &'ll Value, idx: u64) -> &'ll Value {
1193 assert_eq!(idx as c_uint as u64, idx);
1194 unsafe { llvm::LLVMBuildExtractValue(self.llbuilder, agg_val, idx as c_uint, UNNAMED) }
1195 }
1196
1197 fn insert_value(&mut self, agg_val: &'ll Value, elt: &'ll Value, idx: u64) -> &'ll Value {
1198 assert_eq!(idx as c_uint as u64, idx);
1199 unsafe { llvm::LLVMBuildInsertValue(self.llbuilder, agg_val, elt, idx as c_uint, UNNAMED) }
1200 }
1201
1202 fn set_personality_fn(&mut self, personality: &'ll Value) {
1203 unsafe {
1204 llvm::LLVMSetPersonalityFn(self.llfn(), personality);
1205 }
1206 }
1207
1208 fn cleanup_landing_pad(&mut self, pers_fn: &'ll Value) -> (&'ll Value, &'ll Value) {
1209 let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1210 let landing_pad = self.landing_pad(ty, pers_fn, 0);
1211 unsafe {
1212 llvm::LLVMSetCleanup(landing_pad, llvm::TRUE);
1213 }
1214 (self.extract_value(landing_pad, 0), self.extract_value(landing_pad, 1))
1215 }
1216
1217 fn filter_landing_pad(&mut self, pers_fn: &'ll Value) {
1218 let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1219 let landing_pad = self.landing_pad(ty, pers_fn, 1);
1220 self.add_clause(landing_pad, self.const_array(self.type_ptr(), &[]));
1221 }
1222
1223 fn resume(&mut self, exn0: &'ll Value, exn1: &'ll Value) {
1224 let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1225 let mut exn = self.const_poison(ty);
1226 exn = self.insert_value(exn, exn0, 0);
1227 exn = self.insert_value(exn, exn1, 1);
1228 unsafe {
1229 llvm::LLVMBuildResume(self.llbuilder, exn);
1230 }
1231 }
1232
1233 fn cleanup_pad(&mut self, parent: Option<&'ll Value>, args: &[&'ll Value]) -> Funclet<'ll> {
1234 let ret = unsafe {
1235 llvm::LLVMBuildCleanupPad(
1236 self.llbuilder,
1237 parent,
1238 args.as_ptr(),
1239 args.len() as c_uint,
1240 c"cleanuppad".as_ptr(),
1241 )
1242 };
1243 Funclet::new(ret.expect("LLVM does not have support for cleanuppad"))
1244 }
1245
1246 fn cleanup_ret(&mut self, funclet: &Funclet<'ll>, unwind: Option<&'ll BasicBlock>) {
1247 unsafe {
1248 llvm::LLVMBuildCleanupRet(self.llbuilder, funclet.cleanuppad(), unwind)
1249 .expect("LLVM does not have support for cleanupret");
1250 }
1251 }
1252
1253 fn catch_pad(&mut self, parent: &'ll Value, args: &[&'ll Value]) -> Funclet<'ll> {
1254 let ret = unsafe {
1255 llvm::LLVMBuildCatchPad(
1256 self.llbuilder,
1257 parent,
1258 args.as_ptr(),
1259 args.len() as c_uint,
1260 c"catchpad".as_ptr(),
1261 )
1262 };
1263 Funclet::new(ret.expect("LLVM does not have support for catchpad"))
1264 }
1265
1266 fn catch_switch(
1267 &mut self,
1268 parent: Option<&'ll Value>,
1269 unwind: Option<&'ll BasicBlock>,
1270 handlers: &[&'ll BasicBlock],
1271 ) -> &'ll Value {
1272 let ret = unsafe {
1273 llvm::LLVMBuildCatchSwitch(
1274 self.llbuilder,
1275 parent,
1276 unwind,
1277 handlers.len() as c_uint,
1278 c"catchswitch".as_ptr(),
1279 )
1280 };
1281 let ret = ret.expect("LLVM does not have support for catchswitch");
1282 for handler in handlers {
1283 unsafe {
1284 llvm::LLVMAddHandler(ret, handler);
1285 }
1286 }
1287 ret
1288 }
1289
1290 fn atomic_cmpxchg(
1292 &mut self,
1293 dst: &'ll Value,
1294 cmp: &'ll Value,
1295 src: &'ll Value,
1296 order: rustc_middle::ty::AtomicOrdering,
1297 failure_order: rustc_middle::ty::AtomicOrdering,
1298 weak: bool,
1299 ) -> (&'ll Value, &'ll Value) {
1300 unsafe {
1301 let value = llvm::LLVMBuildAtomicCmpXchg(
1302 self.llbuilder,
1303 dst,
1304 cmp,
1305 src,
1306 AtomicOrdering::from_generic(order),
1307 AtomicOrdering::from_generic(failure_order),
1308 llvm::FALSE, );
1310 llvm::LLVMSetWeak(value, weak.to_llvm_bool());
1311 let val = self.extract_value(value, 0);
1312 let success = self.extract_value(value, 1);
1313 (val, success)
1314 }
1315 }
1316
1317 fn atomic_rmw(
1318 &mut self,
1319 op: rustc_codegen_ssa::common::AtomicRmwBinOp,
1320 dst: &'ll Value,
1321 src: &'ll Value,
1322 order: rustc_middle::ty::AtomicOrdering,
1323 ret_ptr: bool,
1324 ) -> &'ll Value {
1325 let mut res = unsafe {
1329 llvm::LLVMBuildAtomicRMW(
1330 self.llbuilder,
1331 AtomicRmwBinOp::from_generic(op),
1332 dst,
1333 src,
1334 AtomicOrdering::from_generic(order),
1335 llvm::FALSE, )
1337 };
1338 if ret_ptr && self.val_ty(res) != self.type_ptr() {
1339 res = self.inttoptr(res, self.type_ptr());
1340 }
1341 res
1342 }
1343
1344 fn atomic_fence(
1345 &mut self,
1346 order: rustc_middle::ty::AtomicOrdering,
1347 scope: SynchronizationScope,
1348 ) {
1349 let single_threaded = match scope {
1350 SynchronizationScope::SingleThread => true,
1351 SynchronizationScope::CrossThread => false,
1352 };
1353 unsafe {
1354 llvm::LLVMBuildFence(
1355 self.llbuilder,
1356 AtomicOrdering::from_generic(order),
1357 single_threaded.to_llvm_bool(),
1358 UNNAMED,
1359 );
1360 }
1361 }
1362
1363 fn set_invariant_load(&mut self, load: &'ll Value) {
1364 self.set_metadata_node(load, llvm::MD_invariant_load, &[]);
1365 }
1366
1367 fn lifetime_start(&mut self, ptr: &'ll Value, size: Size) {
1368 self.call_lifetime_intrinsic("llvm.lifetime.start", ptr, size);
1369 }
1370
1371 fn lifetime_end(&mut self, ptr: &'ll Value, size: Size) {
1372 self.call_lifetime_intrinsic("llvm.lifetime.end", ptr, size);
1373 }
1374
1375 fn call(
1376 &mut self,
1377 llty: &'ll Type,
1378 fn_call_attrs: Option<&CodegenFnAttrs>,
1379 fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1380 llfn: &'ll Value,
1381 args: &[&'ll Value],
1382 funclet: Option<&Funclet<'ll>>,
1383 instance: Option<Instance<'tcx>>,
1384 ) -> &'ll Value {
1385 debug!("call {:?} with args ({:?})", llfn, args);
1386
1387 let args = self.check_call("call", llty, llfn, args);
1388 let funclet_bundle = funclet.map(|funclet| funclet.bundle());
1389 let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
1390 if let Some(funclet_bundle) = funclet_bundle {
1391 bundles.push(funclet_bundle);
1392 }
1393
1394 self.cfi_type_test(fn_call_attrs, fn_abi, instance, llfn);
1396
1397 let kcfi_bundle = self.kcfi_operand_bundle(fn_call_attrs, fn_abi, instance, llfn);
1399 if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
1400 bundles.push(kcfi_bundle);
1401 }
1402
1403 let call = unsafe {
1404 llvm::LLVMBuildCallWithOperandBundles(
1405 self.llbuilder,
1406 llty,
1407 llfn,
1408 args.as_ptr() as *const &llvm::Value,
1409 args.len() as c_uint,
1410 bundles.as_ptr(),
1411 bundles.len() as c_uint,
1412 c"".as_ptr(),
1413 )
1414 };
1415
1416 if let Some(instance) = instance {
1417 let fn_defn_attrs = self.cx.tcx.codegen_fn_attrs(instance.def_id());
1419 if let Some(fn_call_attrs) = fn_call_attrs
1420 && !fn_call_attrs.target_features.is_empty()
1421 && let Some(inlining_rule) = attributes::inline_attr(&self.cx, self.cx.tcx, instance)
1425 && self.cx.tcx.is_target_feature_call_safe(
1426 &fn_call_attrs.target_features,
1427 &fn_defn_attrs.target_features,
1428 )
1429 {
1430 attributes::apply_to_callsite(
1431 call,
1432 llvm::AttributePlace::Function,
1433 &[inlining_rule],
1434 );
1435 }
1436 }
1437
1438 if let Some(fn_abi) = fn_abi {
1439 fn_abi.apply_attrs_callsite(self, call);
1440 }
1441 call
1442 }
1443
1444 fn tail_call(
1445 &mut self,
1446 llty: Self::Type,
1447 fn_attrs: Option<&CodegenFnAttrs>,
1448 fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
1449 llfn: Self::Value,
1450 args: &[Self::Value],
1451 funclet: Option<&Self::Funclet>,
1452 instance: Option<Instance<'tcx>>,
1453 ) {
1454 let call = self.call(llty, fn_attrs, Some(fn_abi), llfn, args, funclet, instance);
1455 llvm::LLVMSetTailCallKind(call, llvm::TailCallKind::MustTail);
1456
1457 match &fn_abi.ret.mode {
1458 PassMode::Ignore | PassMode::Indirect { .. } => self.ret_void(),
1459 PassMode::Direct(_) | PassMode::Pair { .. } | PassMode::Cast { .. } => self.ret(call),
1460 }
1461 }
1462
1463 fn zext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1464 unsafe { llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty, UNNAMED) }
1465 }
1466
1467 fn apply_attrs_to_cleanup_callsite(&mut self, llret: &'ll Value) {
1468 let cold_inline = llvm::AttributeKind::Cold.create_attr(self.llcx);
1470 attributes::apply_to_callsite(llret, llvm::AttributePlace::Function, &[cold_inline]);
1471 }
1472}
1473
1474impl<'ll> StaticBuilderMethods for Builder<'_, 'll, '_> {
1475 fn get_static(&mut self, def_id: DefId) -> &'ll Value {
1476 let global = self.cx().get_static(def_id);
1478 if self.cx().tcx.is_thread_local_static(def_id) {
1479 let pointer =
1480 self.call_intrinsic("llvm.threadlocal.address", &[self.val_ty(global)], &[global]);
1481 self.pointercast(pointer, self.type_ptr())
1483 } else {
1484 self.cx().const_pointercast(global, self.type_ptr())
1486 }
1487 }
1488}
1489
1490impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1491 pub(crate) fn llfn(&self) -> &'ll Value {
1492 unsafe { llvm::LLVMGetBasicBlockParent(self.llbb()) }
1493 }
1494}
1495
1496impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1497 fn position_at_start(&mut self, llbb: &'ll BasicBlock) {
1498 unsafe {
1499 llvm::LLVMRustPositionBuilderAtStart(self.llbuilder, llbb);
1500 }
1501 }
1502}
1503impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1504 fn align_metadata(&mut self, load: &'ll Value, align: Align) {
1505 let md = [llvm::LLVMValueAsMetadata(self.cx.const_u64(align.bytes()))];
1506 self.set_metadata_node(load, llvm::MD_align, &md);
1507 }
1508
1509 fn noundef_metadata(&mut self, load: &'ll Value) {
1510 self.set_metadata_node(load, llvm::MD_noundef, &[]);
1511 }
1512
1513 pub(crate) fn set_unpredictable(&mut self, inst: &'ll Value) {
1514 self.set_metadata_node(inst, llvm::MD_unpredictable, &[]);
1515 }
1516
1517 pub(crate) fn minnum(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1518 self.call_intrinsic("llvm.minnum", &[self.val_ty(lhs)], &[lhs, rhs])
1519 }
1520
1521 pub(crate) fn maxnum(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1522 self.call_intrinsic("llvm.maxnum", &[self.val_ty(lhs)], &[lhs, rhs])
1523 }
1524
1525 pub(crate) fn insert_element(
1526 &mut self,
1527 vec: &'ll Value,
1528 elt: &'ll Value,
1529 idx: &'ll Value,
1530 ) -> &'ll Value {
1531 unsafe { llvm::LLVMBuildInsertElement(self.llbuilder, vec, elt, idx, UNNAMED) }
1532 }
1533
1534 pub(crate) fn shuffle_vector(
1535 &mut self,
1536 v1: &'ll Value,
1537 v2: &'ll Value,
1538 mask: &'ll Value,
1539 ) -> &'ll Value {
1540 unsafe { llvm::LLVMBuildShuffleVector(self.llbuilder, v1, v2, mask, UNNAMED) }
1541 }
1542
1543 pub(crate) fn vector_reduce_fadd(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1544 self.call_intrinsic("llvm.vector.reduce.fadd", &[self.val_ty(src)], &[acc, src])
1545 }
1546 pub(crate) fn vector_reduce_fmul(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1547 self.call_intrinsic("llvm.vector.reduce.fmul", &[self.val_ty(src)], &[acc, src])
1548 }
1549 pub(crate) fn vector_reduce_fadd_reassoc(
1550 &mut self,
1551 acc: &'ll Value,
1552 src: &'ll Value,
1553 ) -> &'ll Value {
1554 unsafe {
1555 let instr =
1556 self.call_intrinsic("llvm.vector.reduce.fadd", &[self.val_ty(src)], &[acc, src]);
1557 llvm::LLVMRustSetAllowReassoc(instr);
1558 instr
1559 }
1560 }
1561 pub(crate) fn vector_reduce_fmul_reassoc(
1562 &mut self,
1563 acc: &'ll Value,
1564 src: &'ll Value,
1565 ) -> &'ll Value {
1566 unsafe {
1567 let instr =
1568 self.call_intrinsic("llvm.vector.reduce.fmul", &[self.val_ty(src)], &[acc, src]);
1569 llvm::LLVMRustSetAllowReassoc(instr);
1570 instr
1571 }
1572 }
1573 pub(crate) fn vector_reduce_add(&mut self, src: &'ll Value) -> &'ll Value {
1574 self.call_intrinsic("llvm.vector.reduce.add", &[self.val_ty(src)], &[src])
1575 }
1576 pub(crate) fn vector_reduce_mul(&mut self, src: &'ll Value) -> &'ll Value {
1577 self.call_intrinsic("llvm.vector.reduce.mul", &[self.val_ty(src)], &[src])
1578 }
1579 pub(crate) fn vector_reduce_and(&mut self, src: &'ll Value) -> &'ll Value {
1580 self.call_intrinsic("llvm.vector.reduce.and", &[self.val_ty(src)], &[src])
1581 }
1582 pub(crate) fn vector_reduce_or(&mut self, src: &'ll Value) -> &'ll Value {
1583 self.call_intrinsic("llvm.vector.reduce.or", &[self.val_ty(src)], &[src])
1584 }
1585 pub(crate) fn vector_reduce_xor(&mut self, src: &'ll Value) -> &'ll Value {
1586 self.call_intrinsic("llvm.vector.reduce.xor", &[self.val_ty(src)], &[src])
1587 }
1588 pub(crate) fn vector_reduce_fmin(&mut self, src: &'ll Value) -> &'ll Value {
1589 self.call_intrinsic("llvm.vector.reduce.fmin", &[self.val_ty(src)], &[src])
1590 }
1591 pub(crate) fn vector_reduce_fmax(&mut self, src: &'ll Value) -> &'ll Value {
1592 self.call_intrinsic("llvm.vector.reduce.fmax", &[self.val_ty(src)], &[src])
1593 }
1594 pub(crate) fn vector_reduce_min(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1595 self.call_intrinsic(
1596 if is_signed { "llvm.vector.reduce.smin" } else { "llvm.vector.reduce.umin" },
1597 &[self.val_ty(src)],
1598 &[src],
1599 )
1600 }
1601 pub(crate) fn vector_reduce_max(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1602 self.call_intrinsic(
1603 if is_signed { "llvm.vector.reduce.smax" } else { "llvm.vector.reduce.umax" },
1604 &[self.val_ty(src)],
1605 &[src],
1606 )
1607 }
1608}
1609impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
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(¶m_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 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 self.cfi_type_test(fn_attrs, fn_abi, instance, llfn);
1759
1760 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 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.sanitizers.disabled.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 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 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.sanitizers.disabled.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 #[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}