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, False, GEPNoWrapFlags, Metadata, True,
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 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 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 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
192pub(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 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 self.cfi_type_test(fn_attrs, fn_abi, instance, llfn);
427
428 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 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 let sub = self.sub(lhs, rhs);
567 let cmp = self.icmp(IntPredicate::IntULT, lhs, rhs);
568 return (sub, cmp);
569 }
570 OverflowOp::Add => {
571 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 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::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 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 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 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) == llvm::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 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 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 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::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 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 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 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(
1071 self.llbuilder,
1072 val,
1073 dest_ty,
1074 if is_signed { True } else { False },
1075 UNNAMED,
1076 )
1077 }
1078 }
1079
1080 fn pointercast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1081 unsafe { llvm::LLVMBuildPointerCast(self.llbuilder, val, dest_ty, UNNAMED) }
1082 }
1083
1084 fn icmp(&mut self, op: IntPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1086 let op = llvm::IntPredicate::from_generic(op);
1087 unsafe { llvm::LLVMBuildICmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
1088 }
1089
1090 fn fcmp(&mut self, op: RealPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1091 let op = llvm::RealPredicate::from_generic(op);
1092 unsafe { llvm::LLVMBuildFCmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
1093 }
1094
1095 fn three_way_compare(
1096 &mut self,
1097 ty: Ty<'tcx>,
1098 lhs: Self::Value,
1099 rhs: Self::Value,
1100 ) -> Option<Self::Value> {
1101 if crate::llvm_util::get_version() < (20, 0, 0) {
1103 return None;
1104 }
1105
1106 let size = ty.primitive_size(self.tcx);
1107 let name = if ty.is_signed() { "llvm.scmp" } else { "llvm.ucmp" };
1108
1109 Some(self.call_intrinsic(name, &[self.type_i8(), self.type_ix(size.bits())], &[lhs, rhs]))
1110 }
1111
1112 fn memcpy(
1114 &mut self,
1115 dst: &'ll Value,
1116 dst_align: Align,
1117 src: &'ll Value,
1118 src_align: Align,
1119 size: &'ll Value,
1120 flags: MemFlags,
1121 ) {
1122 assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memcpy not supported");
1123 let size = self.intcast(size, self.type_isize(), false);
1124 let is_volatile = flags.contains(MemFlags::VOLATILE);
1125 unsafe {
1126 llvm::LLVMRustBuildMemCpy(
1127 self.llbuilder,
1128 dst,
1129 dst_align.bytes() as c_uint,
1130 src,
1131 src_align.bytes() as c_uint,
1132 size,
1133 is_volatile,
1134 );
1135 }
1136 }
1137
1138 fn memmove(
1139 &mut self,
1140 dst: &'ll Value,
1141 dst_align: Align,
1142 src: &'ll Value,
1143 src_align: Align,
1144 size: &'ll Value,
1145 flags: MemFlags,
1146 ) {
1147 assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memmove not supported");
1148 let size = self.intcast(size, self.type_isize(), false);
1149 let is_volatile = flags.contains(MemFlags::VOLATILE);
1150 unsafe {
1151 llvm::LLVMRustBuildMemMove(
1152 self.llbuilder,
1153 dst,
1154 dst_align.bytes() as c_uint,
1155 src,
1156 src_align.bytes() as c_uint,
1157 size,
1158 is_volatile,
1159 );
1160 }
1161 }
1162
1163 fn memset(
1164 &mut self,
1165 ptr: &'ll Value,
1166 fill_byte: &'ll Value,
1167 size: &'ll Value,
1168 align: Align,
1169 flags: MemFlags,
1170 ) {
1171 assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memset not supported");
1172 let is_volatile = flags.contains(MemFlags::VOLATILE);
1173 unsafe {
1174 llvm::LLVMRustBuildMemSet(
1175 self.llbuilder,
1176 ptr,
1177 align.bytes() as c_uint,
1178 fill_byte,
1179 size,
1180 is_volatile,
1181 );
1182 }
1183 }
1184
1185 fn select(
1186 &mut self,
1187 cond: &'ll Value,
1188 then_val: &'ll Value,
1189 else_val: &'ll Value,
1190 ) -> &'ll Value {
1191 unsafe { llvm::LLVMBuildSelect(self.llbuilder, cond, then_val, else_val, UNNAMED) }
1192 }
1193
1194 fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
1195 unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
1196 }
1197
1198 fn extract_element(&mut self, vec: &'ll Value, idx: &'ll Value) -> &'ll Value {
1199 unsafe { llvm::LLVMBuildExtractElement(self.llbuilder, vec, idx, UNNAMED) }
1200 }
1201
1202 fn vector_splat(&mut self, num_elts: usize, elt: &'ll Value) -> &'ll Value {
1203 unsafe {
1204 let elt_ty = self.cx.val_ty(elt);
1205 let undef = llvm::LLVMGetUndef(self.type_vector(elt_ty, num_elts as u64));
1206 let vec = self.insert_element(undef, elt, self.cx.const_i32(0));
1207 let vec_i32_ty = self.type_vector(self.type_i32(), num_elts as u64);
1208 self.shuffle_vector(vec, undef, self.const_null(vec_i32_ty))
1209 }
1210 }
1211
1212 fn extract_value(&mut self, agg_val: &'ll Value, idx: u64) -> &'ll Value {
1213 assert_eq!(idx as c_uint as u64, idx);
1214 unsafe { llvm::LLVMBuildExtractValue(self.llbuilder, agg_val, idx as c_uint, UNNAMED) }
1215 }
1216
1217 fn insert_value(&mut self, agg_val: &'ll Value, elt: &'ll Value, idx: u64) -> &'ll Value {
1218 assert_eq!(idx as c_uint as u64, idx);
1219 unsafe { llvm::LLVMBuildInsertValue(self.llbuilder, agg_val, elt, idx as c_uint, UNNAMED) }
1220 }
1221
1222 fn set_personality_fn(&mut self, personality: &'ll Value) {
1223 unsafe {
1224 llvm::LLVMSetPersonalityFn(self.llfn(), personality);
1225 }
1226 }
1227
1228 fn cleanup_landing_pad(&mut self, pers_fn: &'ll Value) -> (&'ll Value, &'ll Value) {
1229 let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1230 let landing_pad = self.landing_pad(ty, pers_fn, 0);
1231 unsafe {
1232 llvm::LLVMSetCleanup(landing_pad, llvm::True);
1233 }
1234 (self.extract_value(landing_pad, 0), self.extract_value(landing_pad, 1))
1235 }
1236
1237 fn filter_landing_pad(&mut self, pers_fn: &'ll Value) {
1238 let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1239 let landing_pad = self.landing_pad(ty, pers_fn, 1);
1240 self.add_clause(landing_pad, self.const_array(self.type_ptr(), &[]));
1241 }
1242
1243 fn resume(&mut self, exn0: &'ll Value, exn1: &'ll Value) {
1244 let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1245 let mut exn = self.const_poison(ty);
1246 exn = self.insert_value(exn, exn0, 0);
1247 exn = self.insert_value(exn, exn1, 1);
1248 unsafe {
1249 llvm::LLVMBuildResume(self.llbuilder, exn);
1250 }
1251 }
1252
1253 fn cleanup_pad(&mut self, parent: Option<&'ll Value>, args: &[&'ll Value]) -> Funclet<'ll> {
1254 let ret = unsafe {
1255 llvm::LLVMBuildCleanupPad(
1256 self.llbuilder,
1257 parent,
1258 args.as_ptr(),
1259 args.len() as c_uint,
1260 c"cleanuppad".as_ptr(),
1261 )
1262 };
1263 Funclet::new(ret.expect("LLVM does not have support for cleanuppad"))
1264 }
1265
1266 fn cleanup_ret(&mut self, funclet: &Funclet<'ll>, unwind: Option<&'ll BasicBlock>) {
1267 unsafe {
1268 llvm::LLVMBuildCleanupRet(self.llbuilder, funclet.cleanuppad(), unwind)
1269 .expect("LLVM does not have support for cleanupret");
1270 }
1271 }
1272
1273 fn catch_pad(&mut self, parent: &'ll Value, args: &[&'ll Value]) -> Funclet<'ll> {
1274 let ret = unsafe {
1275 llvm::LLVMBuildCatchPad(
1276 self.llbuilder,
1277 parent,
1278 args.as_ptr(),
1279 args.len() as c_uint,
1280 c"catchpad".as_ptr(),
1281 )
1282 };
1283 Funclet::new(ret.expect("LLVM does not have support for catchpad"))
1284 }
1285
1286 fn catch_switch(
1287 &mut self,
1288 parent: Option<&'ll Value>,
1289 unwind: Option<&'ll BasicBlock>,
1290 handlers: &[&'ll BasicBlock],
1291 ) -> &'ll Value {
1292 let ret = unsafe {
1293 llvm::LLVMBuildCatchSwitch(
1294 self.llbuilder,
1295 parent,
1296 unwind,
1297 handlers.len() as c_uint,
1298 c"catchswitch".as_ptr(),
1299 )
1300 };
1301 let ret = ret.expect("LLVM does not have support for catchswitch");
1302 for handler in handlers {
1303 unsafe {
1304 llvm::LLVMAddHandler(ret, handler);
1305 }
1306 }
1307 ret
1308 }
1309
1310 fn atomic_cmpxchg(
1312 &mut self,
1313 dst: &'ll Value,
1314 cmp: &'ll Value,
1315 src: &'ll Value,
1316 order: rustc_middle::ty::AtomicOrdering,
1317 failure_order: rustc_middle::ty::AtomicOrdering,
1318 weak: bool,
1319 ) -> (&'ll Value, &'ll Value) {
1320 let weak = if weak { llvm::True } else { llvm::False };
1321 unsafe {
1322 let value = llvm::LLVMBuildAtomicCmpXchg(
1323 self.llbuilder,
1324 dst,
1325 cmp,
1326 src,
1327 AtomicOrdering::from_generic(order),
1328 AtomicOrdering::from_generic(failure_order),
1329 llvm::False, );
1331 llvm::LLVMSetWeak(value, weak);
1332 let val = self.extract_value(value, 0);
1333 let success = self.extract_value(value, 1);
1334 (val, success)
1335 }
1336 }
1337
1338 fn atomic_rmw(
1339 &mut self,
1340 op: rustc_codegen_ssa::common::AtomicRmwBinOp,
1341 dst: &'ll Value,
1342 src: &'ll Value,
1343 order: rustc_middle::ty::AtomicOrdering,
1344 ret_ptr: bool,
1345 ) -> &'ll Value {
1346 let mut res = unsafe {
1350 llvm::LLVMBuildAtomicRMW(
1351 self.llbuilder,
1352 AtomicRmwBinOp::from_generic(op),
1353 dst,
1354 src,
1355 AtomicOrdering::from_generic(order),
1356 llvm::False, )
1358 };
1359 if ret_ptr && self.val_ty(res) != self.type_ptr() {
1360 res = self.inttoptr(res, self.type_ptr());
1361 }
1362 res
1363 }
1364
1365 fn atomic_fence(
1366 &mut self,
1367 order: rustc_middle::ty::AtomicOrdering,
1368 scope: SynchronizationScope,
1369 ) {
1370 let single_threaded = match scope {
1371 SynchronizationScope::SingleThread => llvm::True,
1372 SynchronizationScope::CrossThread => llvm::False,
1373 };
1374 unsafe {
1375 llvm::LLVMBuildFence(
1376 self.llbuilder,
1377 AtomicOrdering::from_generic(order),
1378 single_threaded,
1379 UNNAMED,
1380 );
1381 }
1382 }
1383
1384 fn set_invariant_load(&mut self, load: &'ll Value) {
1385 unsafe {
1386 let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, ptr::null(), 0);
1387 self.set_metadata(load, llvm::MD_invariant_load, md);
1388 }
1389 }
1390
1391 fn lifetime_start(&mut self, ptr: &'ll Value, size: Size) {
1392 self.call_lifetime_intrinsic("llvm.lifetime.start", ptr, size);
1393 }
1394
1395 fn lifetime_end(&mut self, ptr: &'ll Value, size: Size) {
1396 self.call_lifetime_intrinsic("llvm.lifetime.end", ptr, size);
1397 }
1398
1399 fn call(
1400 &mut self,
1401 llty: &'ll Type,
1402 fn_attrs: Option<&CodegenFnAttrs>,
1403 fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1404 llfn: &'ll Value,
1405 args: &[&'ll Value],
1406 funclet: Option<&Funclet<'ll>>,
1407 instance: Option<Instance<'tcx>>,
1408 ) -> &'ll Value {
1409 debug!("call {:?} with args ({:?})", llfn, args);
1410
1411 let args = self.check_call("call", llty, llfn, args);
1412 let funclet_bundle = funclet.map(|funclet| funclet.bundle());
1413 let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
1414 if let Some(funclet_bundle) = funclet_bundle {
1415 bundles.push(funclet_bundle);
1416 }
1417
1418 self.cfi_type_test(fn_attrs, fn_abi, instance, llfn);
1420
1421 let kcfi_bundle = self.kcfi_operand_bundle(fn_attrs, fn_abi, instance, llfn);
1423 if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
1424 bundles.push(kcfi_bundle);
1425 }
1426
1427 let call = unsafe {
1428 llvm::LLVMBuildCallWithOperandBundles(
1429 self.llbuilder,
1430 llty,
1431 llfn,
1432 args.as_ptr() as *const &llvm::Value,
1433 args.len() as c_uint,
1434 bundles.as_ptr(),
1435 bundles.len() as c_uint,
1436 c"".as_ptr(),
1437 )
1438 };
1439 if let Some(fn_abi) = fn_abi {
1440 fn_abi.apply_attrs_callsite(self, call);
1441 }
1442 call
1443 }
1444
1445 fn tail_call(
1446 &mut self,
1447 llty: Self::Type,
1448 fn_attrs: Option<&CodegenFnAttrs>,
1449 fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
1450 llfn: Self::Value,
1451 args: &[Self::Value],
1452 funclet: Option<&Self::Funclet>,
1453 instance: Option<Instance<'tcx>>,
1454 ) {
1455 let call = self.call(llty, fn_attrs, Some(fn_abi), llfn, args, funclet, instance);
1456 llvm::LLVMRustSetTailCallKind(call, llvm::TailCallKind::MustTail);
1457
1458 match &fn_abi.ret.mode {
1459 PassMode::Ignore | PassMode::Indirect { .. } => self.ret_void(),
1460 PassMode::Direct(_) | PassMode::Pair { .. } => self.ret(call),
1461 mode @ PassMode::Cast { .. } => {
1462 bug!("Encountered `PassMode::{mode:?}` during codegen")
1463 }
1464 }
1465 }
1466
1467 fn zext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1468 unsafe { llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty, UNNAMED) }
1469 }
1470
1471 fn apply_attrs_to_cleanup_callsite(&mut self, llret: &'ll Value) {
1472 let cold_inline = llvm::AttributeKind::Cold.create_attr(self.llcx);
1474 attributes::apply_to_callsite(llret, llvm::AttributePlace::Function, &[cold_inline]);
1475 }
1476}
1477
1478impl<'ll> StaticBuilderMethods for Builder<'_, 'll, '_> {
1479 fn get_static(&mut self, def_id: DefId) -> &'ll Value {
1480 let global = self.cx().get_static(def_id);
1482 if self.cx().tcx.is_thread_local_static(def_id) {
1483 let pointer =
1484 self.call_intrinsic("llvm.threadlocal.address", &[self.val_ty(global)], &[global]);
1485 self.pointercast(pointer, self.type_ptr())
1487 } else {
1488 self.cx().const_pointercast(global, self.type_ptr())
1490 }
1491 }
1492}
1493
1494impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1495 pub(crate) fn llfn(&self) -> &'ll Value {
1496 unsafe { llvm::LLVMGetBasicBlockParent(self.llbb()) }
1497 }
1498}
1499
1500impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1501 fn position_at_start(&mut self, llbb: &'ll BasicBlock) {
1502 unsafe {
1503 llvm::LLVMRustPositionBuilderAtStart(self.llbuilder, llbb);
1504 }
1505 }
1506}
1507impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1508 fn align_metadata(&mut self, load: &'ll Value, align: Align) {
1509 unsafe {
1510 let md = [llvm::LLVMValueAsMetadata(self.cx.const_u64(align.bytes()))];
1511 let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, md.as_ptr(), md.len());
1512 self.set_metadata(load, llvm::MD_align, md);
1513 }
1514 }
1515
1516 fn noundef_metadata(&mut self, load: &'ll Value) {
1517 unsafe {
1518 let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, ptr::null(), 0);
1519 self.set_metadata(load, llvm::MD_noundef, md);
1520 }
1521 }
1522
1523 pub(crate) fn set_unpredictable(&mut self, inst: &'ll Value) {
1524 unsafe {
1525 let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, ptr::null(), 0);
1526 self.set_metadata(inst, llvm::MD_unpredictable, md);
1527 }
1528 }
1529}
1530impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1531 pub(crate) fn minnum(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1532 unsafe { llvm::LLVMRustBuildMinNum(self.llbuilder, lhs, rhs) }
1533 }
1534
1535 pub(crate) fn maxnum(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1536 unsafe { llvm::LLVMRustBuildMaxNum(self.llbuilder, lhs, rhs) }
1537 }
1538
1539 pub(crate) fn insert_element(
1540 &mut self,
1541 vec: &'ll Value,
1542 elt: &'ll Value,
1543 idx: &'ll Value,
1544 ) -> &'ll Value {
1545 unsafe { llvm::LLVMBuildInsertElement(self.llbuilder, vec, elt, idx, UNNAMED) }
1546 }
1547
1548 pub(crate) fn shuffle_vector(
1549 &mut self,
1550 v1: &'ll Value,
1551 v2: &'ll Value,
1552 mask: &'ll Value,
1553 ) -> &'ll Value {
1554 unsafe { llvm::LLVMBuildShuffleVector(self.llbuilder, v1, v2, mask, UNNAMED) }
1555 }
1556
1557 pub(crate) fn vector_reduce_fadd(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1558 unsafe { llvm::LLVMRustBuildVectorReduceFAdd(self.llbuilder, acc, src) }
1559 }
1560 pub(crate) fn vector_reduce_fmul(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1561 unsafe { llvm::LLVMRustBuildVectorReduceFMul(self.llbuilder, acc, src) }
1562 }
1563 pub(crate) fn vector_reduce_fadd_reassoc(
1564 &mut self,
1565 acc: &'ll Value,
1566 src: &'ll Value,
1567 ) -> &'ll Value {
1568 unsafe {
1569 let instr = llvm::LLVMRustBuildVectorReduceFAdd(self.llbuilder, acc, src);
1570 llvm::LLVMRustSetAllowReassoc(instr);
1571 instr
1572 }
1573 }
1574 pub(crate) fn vector_reduce_fmul_reassoc(
1575 &mut self,
1576 acc: &'ll Value,
1577 src: &'ll Value,
1578 ) -> &'ll Value {
1579 unsafe {
1580 let instr = llvm::LLVMRustBuildVectorReduceFMul(self.llbuilder, acc, src);
1581 llvm::LLVMRustSetAllowReassoc(instr);
1582 instr
1583 }
1584 }
1585 pub(crate) fn vector_reduce_add(&mut self, src: &'ll Value) -> &'ll Value {
1586 unsafe { llvm::LLVMRustBuildVectorReduceAdd(self.llbuilder, src) }
1587 }
1588 pub(crate) fn vector_reduce_mul(&mut self, src: &'ll Value) -> &'ll Value {
1589 unsafe { llvm::LLVMRustBuildVectorReduceMul(self.llbuilder, src) }
1590 }
1591 pub(crate) fn vector_reduce_and(&mut self, src: &'ll Value) -> &'ll Value {
1592 unsafe { llvm::LLVMRustBuildVectorReduceAnd(self.llbuilder, src) }
1593 }
1594 pub(crate) fn vector_reduce_or(&mut self, src: &'ll Value) -> &'ll Value {
1595 unsafe { llvm::LLVMRustBuildVectorReduceOr(self.llbuilder, src) }
1596 }
1597 pub(crate) fn vector_reduce_xor(&mut self, src: &'ll Value) -> &'ll Value {
1598 unsafe { llvm::LLVMRustBuildVectorReduceXor(self.llbuilder, src) }
1599 }
1600 pub(crate) fn vector_reduce_fmin(&mut self, src: &'ll Value) -> &'ll Value {
1601 unsafe {
1602 llvm::LLVMRustBuildVectorReduceFMin(self.llbuilder, src, false)
1603 }
1604 }
1605 pub(crate) fn vector_reduce_fmax(&mut self, src: &'ll Value) -> &'ll Value {
1606 unsafe {
1607 llvm::LLVMRustBuildVectorReduceFMax(self.llbuilder, src, false)
1608 }
1609 }
1610 pub(crate) fn vector_reduce_min(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1611 unsafe { llvm::LLVMRustBuildVectorReduceMin(self.llbuilder, src, is_signed) }
1612 }
1613 pub(crate) fn vector_reduce_max(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1614 unsafe { llvm::LLVMRustBuildVectorReduceMax(self.llbuilder, src, is_signed) }
1615 }
1616
1617 pub(crate) fn add_clause(&mut self, landing_pad: &'ll Value, clause: &'ll Value) {
1618 unsafe {
1619 llvm::LLVMAddClause(landing_pad, clause);
1620 }
1621 }
1622
1623 pub(crate) fn catch_ret(
1624 &mut self,
1625 funclet: &Funclet<'ll>,
1626 unwind: &'ll BasicBlock,
1627 ) -> &'ll Value {
1628 let ret = unsafe { llvm::LLVMBuildCatchRet(self.llbuilder, funclet.cleanuppad(), unwind) };
1629 ret.expect("LLVM does not have support for catchret")
1630 }
1631
1632 fn check_call<'b>(
1633 &mut self,
1634 typ: &str,
1635 fn_ty: &'ll Type,
1636 llfn: &'ll Value,
1637 args: &'b [&'ll Value],
1638 ) -> Cow<'b, [&'ll Value]> {
1639 assert!(
1640 self.cx.type_kind(fn_ty) == TypeKind::Function,
1641 "builder::{typ} not passed a function, but {fn_ty:?}"
1642 );
1643
1644 let param_tys = self.cx.func_params_types(fn_ty);
1645
1646 let all_args_match = iter::zip(¶m_tys, args.iter().map(|&v| self.cx.val_ty(v)))
1647 .all(|(expected_ty, actual_ty)| *expected_ty == actual_ty);
1648
1649 if all_args_match {
1650 return Cow::Borrowed(args);
1651 }
1652
1653 let casted_args: Vec<_> = iter::zip(param_tys, args)
1654 .enumerate()
1655 .map(|(i, (expected_ty, &actual_val))| {
1656 let actual_ty = self.cx.val_ty(actual_val);
1657 if expected_ty != actual_ty {
1658 debug!(
1659 "type mismatch in function call of {:?}. \
1660 Expected {:?} for param {}, got {:?}; injecting bitcast",
1661 llfn, expected_ty, i, actual_ty
1662 );
1663 self.bitcast(actual_val, expected_ty)
1664 } else {
1665 actual_val
1666 }
1667 })
1668 .collect();
1669
1670 Cow::Owned(casted_args)
1671 }
1672
1673 pub(crate) fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
1674 unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
1675 }
1676}
1677
1678impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1679 pub(crate) fn call_intrinsic(
1680 &mut self,
1681 base_name: impl Into<Cow<'static, str>>,
1682 type_params: &[&'ll Type],
1683 args: &[&'ll Value],
1684 ) -> &'ll Value {
1685 let (ty, f) = self.cx.get_intrinsic(base_name.into(), type_params);
1686 self.call(ty, None, None, f, args, None, None)
1687 }
1688
1689 fn call_lifetime_intrinsic(&mut self, intrinsic: &'static str, ptr: &'ll Value, size: Size) {
1690 let size = size.bytes();
1691 if size == 0 {
1692 return;
1693 }
1694
1695 if !self.cx().sess().emit_lifetime_markers() {
1696 return;
1697 }
1698
1699 self.call_intrinsic(intrinsic, &[self.val_ty(ptr)], &[self.cx.const_u64(size), ptr]);
1700 }
1701}
1702impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1703 pub(crate) fn phi(
1704 &mut self,
1705 ty: &'ll Type,
1706 vals: &[&'ll Value],
1707 bbs: &[&'ll BasicBlock],
1708 ) -> &'ll Value {
1709 assert_eq!(vals.len(), bbs.len());
1710 let phi = unsafe { llvm::LLVMBuildPhi(self.llbuilder, ty, UNNAMED) };
1711 unsafe {
1712 llvm::LLVMAddIncoming(phi, vals.as_ptr(), bbs.as_ptr(), vals.len() as c_uint);
1713 phi
1714 }
1715 }
1716
1717 fn add_incoming_to_phi(&mut self, phi: &'ll Value, val: &'ll Value, bb: &'ll BasicBlock) {
1718 unsafe {
1719 llvm::LLVMAddIncoming(phi, &val, &bb, 1 as c_uint);
1720 }
1721 }
1722}
1723impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1724 pub(crate) fn landing_pad(
1725 &mut self,
1726 ty: &'ll Type,
1727 pers_fn: &'ll Value,
1728 num_clauses: usize,
1729 ) -> &'ll Value {
1730 self.set_personality_fn(pers_fn);
1734 unsafe {
1735 llvm::LLVMBuildLandingPad(self.llbuilder, ty, None, num_clauses as c_uint, UNNAMED)
1736 }
1737 }
1738
1739 pub(crate) fn callbr(
1740 &mut self,
1741 llty: &'ll Type,
1742 fn_attrs: Option<&CodegenFnAttrs>,
1743 fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1744 llfn: &'ll Value,
1745 args: &[&'ll Value],
1746 default_dest: &'ll BasicBlock,
1747 indirect_dest: &[&'ll BasicBlock],
1748 funclet: Option<&Funclet<'ll>>,
1749 instance: Option<Instance<'tcx>>,
1750 ) -> &'ll Value {
1751 debug!("invoke {:?} with args ({:?})", llfn, args);
1752
1753 let args = self.check_call("callbr", llty, llfn, args);
1754 let funclet_bundle = funclet.map(|funclet| funclet.bundle());
1755 let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
1756 if let Some(funclet_bundle) = funclet_bundle {
1757 bundles.push(funclet_bundle);
1758 }
1759
1760 self.cfi_type_test(fn_attrs, fn_abi, instance, llfn);
1762
1763 let kcfi_bundle = self.kcfi_operand_bundle(fn_attrs, fn_abi, instance, llfn);
1765 if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
1766 bundles.push(kcfi_bundle);
1767 }
1768
1769 let callbr = unsafe {
1770 llvm::LLVMBuildCallBr(
1771 self.llbuilder,
1772 llty,
1773 llfn,
1774 default_dest,
1775 indirect_dest.as_ptr(),
1776 indirect_dest.len() as c_uint,
1777 args.as_ptr(),
1778 args.len() as c_uint,
1779 bundles.as_ptr(),
1780 bundles.len() as c_uint,
1781 UNNAMED,
1782 )
1783 };
1784 if let Some(fn_abi) = fn_abi {
1785 fn_abi.apply_attrs_callsite(self, callbr);
1786 }
1787 callbr
1788 }
1789
1790 fn cfi_type_test(
1792 &mut self,
1793 fn_attrs: Option<&CodegenFnAttrs>,
1794 fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1795 instance: Option<Instance<'tcx>>,
1796 llfn: &'ll Value,
1797 ) {
1798 let is_indirect_call = unsafe { llvm::LLVMRustIsNonGVFunctionPointerTy(llfn) };
1799 if self.tcx.sess.is_sanitizer_cfi_enabled()
1800 && let Some(fn_abi) = fn_abi
1801 && is_indirect_call
1802 {
1803 if let Some(fn_attrs) = fn_attrs
1804 && fn_attrs.no_sanitize.contains(SanitizerSet::CFI)
1805 {
1806 return;
1807 }
1808
1809 let mut options = cfi::TypeIdOptions::empty();
1810 if self.tcx.sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1811 options.insert(cfi::TypeIdOptions::GENERALIZE_POINTERS);
1812 }
1813 if self.tcx.sess.is_sanitizer_cfi_normalize_integers_enabled() {
1814 options.insert(cfi::TypeIdOptions::NORMALIZE_INTEGERS);
1815 }
1816
1817 let typeid = if let Some(instance) = instance {
1818 cfi::typeid_for_instance(self.tcx, instance, options)
1819 } else {
1820 cfi::typeid_for_fnabi(self.tcx, fn_abi, options)
1821 };
1822 let typeid_metadata = self.cx.create_metadata(typeid.as_bytes());
1823 let dbg_loc = self.get_dbg_loc();
1824
1825 let typeid = self.get_metadata_value(typeid_metadata);
1829 let cond = self.call_intrinsic("llvm.type.test", &[], &[llfn, typeid]);
1830 let bb_pass = self.append_sibling_block("type_test.pass");
1831 let bb_fail = self.append_sibling_block("type_test.fail");
1832 self.cond_br(cond, bb_pass, bb_fail);
1833
1834 self.switch_to_block(bb_fail);
1835 if let Some(dbg_loc) = dbg_loc {
1836 self.set_dbg_loc(dbg_loc);
1837 }
1838 self.abort();
1839 self.unreachable();
1840
1841 self.switch_to_block(bb_pass);
1842 if let Some(dbg_loc) = dbg_loc {
1843 self.set_dbg_loc(dbg_loc);
1844 }
1845 }
1846 }
1847
1848 fn kcfi_operand_bundle(
1850 &mut self,
1851 fn_attrs: Option<&CodegenFnAttrs>,
1852 fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1853 instance: Option<Instance<'tcx>>,
1854 llfn: &'ll Value,
1855 ) -> Option<llvm::OperandBundleBox<'ll>> {
1856 let is_indirect_call = unsafe { llvm::LLVMRustIsNonGVFunctionPointerTy(llfn) };
1857 let kcfi_bundle = if self.tcx.sess.is_sanitizer_kcfi_enabled()
1858 && let Some(fn_abi) = fn_abi
1859 && is_indirect_call
1860 {
1861 if let Some(fn_attrs) = fn_attrs
1862 && fn_attrs.no_sanitize.contains(SanitizerSet::KCFI)
1863 {
1864 return None;
1865 }
1866
1867 let mut options = kcfi::TypeIdOptions::empty();
1868 if self.tcx.sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1869 options.insert(kcfi::TypeIdOptions::GENERALIZE_POINTERS);
1870 }
1871 if self.tcx.sess.is_sanitizer_cfi_normalize_integers_enabled() {
1872 options.insert(kcfi::TypeIdOptions::NORMALIZE_INTEGERS);
1873 }
1874
1875 let kcfi_typeid = if let Some(instance) = instance {
1876 kcfi::typeid_for_instance(self.tcx, instance, options)
1877 } else {
1878 kcfi::typeid_for_fnabi(self.tcx, fn_abi, options)
1879 };
1880
1881 Some(llvm::OperandBundleBox::new("kcfi", &[self.const_u32(kcfi_typeid)]))
1882 } else {
1883 None
1884 };
1885 kcfi_bundle
1886 }
1887
1888 #[instrument(level = "debug", skip(self))]
1890 pub(crate) fn instrprof_increment(
1891 &mut self,
1892 fn_name: &'ll Value,
1893 hash: &'ll Value,
1894 num_counters: &'ll Value,
1895 index: &'ll Value,
1896 ) {
1897 self.call_intrinsic("llvm.instrprof.increment", &[], &[fn_name, hash, num_counters, index]);
1898 }
1899}