1use std::borrow::{Borrow, Cow};
2use std::ops::Deref;
3use std::{iter, ptr};
4
5pub(crate) mod autodiff;
6pub(crate) mod gpu_offload;
7
8use libc::{c_char, c_uint, size_t};
9use rustc_abi as abi;
10use rustc_abi::{Align, Size, WrappingRange};
11use rustc_codegen_ssa::MemFlags;
12use rustc_codegen_ssa::common::{IntPredicate, RealPredicate, SynchronizationScope, TypeKind};
13use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
14use rustc_codegen_ssa::mir::place::PlaceRef;
15use rustc_codegen_ssa::traits::*;
16use rustc_data_structures::small_c_str::SmallCStr;
17use rustc_hir::def_id::DefId;
18use rustc_middle::bug;
19use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
20use rustc_middle::ty::layout::{
21 FnAbiError, FnAbiOfHelpers, FnAbiRequest, HasTypingEnv, LayoutError, LayoutOfHelpers,
22 TyAndLayout,
23};
24use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
25use rustc_sanitizers::{cfi, kcfi};
26use rustc_session::config::OptLevel;
27use rustc_span::Span;
28use rustc_target::callconv::{FnAbi, PassMode};
29use rustc_target::spec::{HasTargetSpec, SanitizerSet, Target};
30use smallvec::SmallVec;
31use tracing::{debug, instrument};
32
33use crate::abi::FnAbiLlvmExt;
34use crate::attributes;
35use crate::common::Funclet;
36use crate::context::{CodegenCx, FullCx, GenericCx, SCx};
37use crate::llvm::{
38 self, AtomicOrdering, AtomicRmwBinOp, BasicBlock, GEPNoWrapFlags, Metadata, TRUE, ToLlvmBool,
39};
40use crate::type_::Type;
41use crate::type_of::LayoutLlvmExt;
42use crate::value::Value;
43
44#[must_use]
45pub(crate) struct GenericBuilder<'a, 'll, CX: Borrow<SCx<'ll>>> {
46 pub llbuilder: &'ll mut llvm::Builder<'ll>,
47 pub cx: &'a GenericCx<'ll, CX>,
48}
49
50pub(crate) type SBuilder<'a, 'll> = GenericBuilder<'a, 'll, SCx<'ll>>;
51pub(crate) type Builder<'a, 'll, 'tcx> = GenericBuilder<'a, 'll, FullCx<'ll, 'tcx>>;
52
53impl<'a, 'll, CX: Borrow<SCx<'ll>>> Drop for GenericBuilder<'a, 'll, CX> {
54 fn drop(&mut self) {
55 unsafe {
56 llvm::LLVMDisposeBuilder(&mut *(self.llbuilder as *mut _));
57 }
58 }
59}
60
61impl<'a, 'll> SBuilder<'a, 'll> {
62 pub(crate) fn call(
63 &mut self,
64 llty: &'ll Type,
65 llfn: &'ll Value,
66 args: &[&'ll Value],
67 funclet: Option<&Funclet<'ll>>,
68 ) -> &'ll Value {
69 debug!("call {:?} with args ({:?})", llfn, args);
70
71 let args = self.check_call("call", llty, llfn, args);
72 let funclet_bundle = funclet.map(|funclet| funclet.bundle());
73 let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
74 if let Some(funclet_bundle) = funclet_bundle {
75 bundles.push(funclet_bundle);
76 }
77
78 let call = unsafe {
79 llvm::LLVMBuildCallWithOperandBundles(
80 self.llbuilder,
81 llty,
82 llfn,
83 args.as_ptr() as *const &llvm::Value,
84 args.len() as c_uint,
85 bundles.as_ptr(),
86 bundles.len() as c_uint,
87 c"".as_ptr(),
88 )
89 };
90 call
91 }
92}
93
94impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
95 fn with_cx(scx: &'a GenericCx<'ll, CX>) -> Self {
96 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).is_true() {
721 if let Some(init) = llvm::LLVMGetInitializer(global) {
722 if self.val_ty(init) == llty {
723 const_llval = Some(init);
724 }
725 }
726 }
727 }
728
729 let llval = const_llval.unwrap_or_else(|| {
730 let load = self.load(llty, place.val.llval, place.val.align);
731 if let abi::BackendRepr::Scalar(scalar) = place.layout.backend_repr {
732 scalar_load_metadata(self, load, scalar, place.layout, Size::ZERO);
733 self.to_immediate_scalar(load, scalar)
734 } else {
735 load
736 }
737 });
738 OperandValue::Immediate(llval)
739 } else if let abi::BackendRepr::ScalarPair(a, b) = place.layout.backend_repr {
740 let b_offset = a.size(self).align_to(b.align(self).abi);
741
742 let mut load = |i, scalar: abi::Scalar, layout, align, offset| {
743 let llptr = if i == 0 {
744 place.val.llval
745 } else {
746 self.inbounds_ptradd(place.val.llval, self.const_usize(b_offset.bytes()))
747 };
748 let llty = place.layout.scalar_pair_element_llvm_type(self, i, false);
749 let load = self.load(llty, llptr, align);
750 scalar_load_metadata(self, load, scalar, layout, offset);
751 self.to_immediate_scalar(load, scalar)
752 };
753
754 OperandValue::Pair(
755 load(0, a, place.layout, place.val.align, Size::ZERO),
756 load(1, b, place.layout, place.val.align.restrict_for_offset(b_offset), b_offset),
757 )
758 } else {
759 OperandValue::Ref(place.val)
760 };
761
762 OperandRef { val, layout: place.layout }
763 }
764
765 fn write_operand_repeatedly(
766 &mut self,
767 cg_elem: OperandRef<'tcx, &'ll Value>,
768 count: u64,
769 dest: PlaceRef<'tcx, &'ll Value>,
770 ) {
771 let zero = self.const_usize(0);
772 let count = self.const_usize(count);
773
774 let header_bb = self.append_sibling_block("repeat_loop_header");
775 let body_bb = self.append_sibling_block("repeat_loop_body");
776 let next_bb = self.append_sibling_block("repeat_loop_next");
777
778 self.br(header_bb);
779
780 let mut header_bx = Self::build(self.cx, header_bb);
781 let i = header_bx.phi(self.val_ty(zero), &[zero], &[self.llbb()]);
782
783 let keep_going = header_bx.icmp(IntPredicate::IntULT, i, count);
784 header_bx.cond_br(keep_going, body_bb, next_bb);
785
786 let mut body_bx = Self::build(self.cx, body_bb);
787 let dest_elem = dest.project_index(&mut body_bx, i);
788 cg_elem.val.store(&mut body_bx, dest_elem);
789
790 let next = body_bx.unchecked_uadd(i, self.const_usize(1));
791 body_bx.br(header_bb);
792 header_bx.add_incoming_to_phi(i, next, body_bb);
793
794 *self = Self::build(self.cx, next_bb);
795 }
796
797 fn range_metadata(&mut self, load: &'ll Value, range: WrappingRange) {
798 if self.cx.sess().opts.optimize == OptLevel::No {
799 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(self.llbuilder, val, dest_ty, is_signed.to_llvm_bool(), UNNAMED)
1071 }
1072 }
1073
1074 fn pointercast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1075 unsafe { llvm::LLVMBuildPointerCast(self.llbuilder, val, dest_ty, UNNAMED) }
1076 }
1077
1078 fn icmp(&mut self, op: IntPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1080 let op = llvm::IntPredicate::from_generic(op);
1081 unsafe { llvm::LLVMBuildICmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
1082 }
1083
1084 fn fcmp(&mut self, op: RealPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1085 let op = llvm::RealPredicate::from_generic(op);
1086 unsafe { llvm::LLVMBuildFCmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
1087 }
1088
1089 fn three_way_compare(
1090 &mut self,
1091 ty: Ty<'tcx>,
1092 lhs: Self::Value,
1093 rhs: Self::Value,
1094 ) -> Option<Self::Value> {
1095 if crate::llvm_util::get_version() < (20, 0, 0) {
1097 return None;
1098 }
1099
1100 let size = ty.primitive_size(self.tcx);
1101 let name = if ty.is_signed() { "llvm.scmp" } else { "llvm.ucmp" };
1102
1103 Some(self.call_intrinsic(name, &[self.type_i8(), self.type_ix(size.bits())], &[lhs, rhs]))
1104 }
1105
1106 fn memcpy(
1108 &mut self,
1109 dst: &'ll Value,
1110 dst_align: Align,
1111 src: &'ll Value,
1112 src_align: Align,
1113 size: &'ll Value,
1114 flags: MemFlags,
1115 ) {
1116 assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memcpy not supported");
1117 let size = self.intcast(size, self.type_isize(), false);
1118 let is_volatile = flags.contains(MemFlags::VOLATILE);
1119 unsafe {
1120 llvm::LLVMRustBuildMemCpy(
1121 self.llbuilder,
1122 dst,
1123 dst_align.bytes() as c_uint,
1124 src,
1125 src_align.bytes() as c_uint,
1126 size,
1127 is_volatile,
1128 );
1129 }
1130 }
1131
1132 fn memmove(
1133 &mut self,
1134 dst: &'ll Value,
1135 dst_align: Align,
1136 src: &'ll Value,
1137 src_align: Align,
1138 size: &'ll Value,
1139 flags: MemFlags,
1140 ) {
1141 assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memmove not supported");
1142 let size = self.intcast(size, self.type_isize(), false);
1143 let is_volatile = flags.contains(MemFlags::VOLATILE);
1144 unsafe {
1145 llvm::LLVMRustBuildMemMove(
1146 self.llbuilder,
1147 dst,
1148 dst_align.bytes() as c_uint,
1149 src,
1150 src_align.bytes() as c_uint,
1151 size,
1152 is_volatile,
1153 );
1154 }
1155 }
1156
1157 fn memset(
1158 &mut self,
1159 ptr: &'ll Value,
1160 fill_byte: &'ll Value,
1161 size: &'ll Value,
1162 align: Align,
1163 flags: MemFlags,
1164 ) {
1165 assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memset not supported");
1166 let is_volatile = flags.contains(MemFlags::VOLATILE);
1167 unsafe {
1168 llvm::LLVMRustBuildMemSet(
1169 self.llbuilder,
1170 ptr,
1171 align.bytes() as c_uint,
1172 fill_byte,
1173 size,
1174 is_volatile,
1175 );
1176 }
1177 }
1178
1179 fn select(
1180 &mut self,
1181 cond: &'ll Value,
1182 then_val: &'ll Value,
1183 else_val: &'ll Value,
1184 ) -> &'ll Value {
1185 unsafe { llvm::LLVMBuildSelect(self.llbuilder, cond, then_val, else_val, UNNAMED) }
1186 }
1187
1188 fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
1189 unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
1190 }
1191
1192 fn extract_element(&mut self, vec: &'ll Value, idx: &'ll Value) -> &'ll Value {
1193 unsafe { llvm::LLVMBuildExtractElement(self.llbuilder, vec, idx, UNNAMED) }
1194 }
1195
1196 fn vector_splat(&mut self, num_elts: usize, elt: &'ll Value) -> &'ll Value {
1197 unsafe {
1198 let elt_ty = self.cx.val_ty(elt);
1199 let undef = llvm::LLVMGetUndef(self.type_vector(elt_ty, num_elts as u64));
1200 let vec = self.insert_element(undef, elt, self.cx.const_i32(0));
1201 let vec_i32_ty = self.type_vector(self.type_i32(), num_elts as u64);
1202 self.shuffle_vector(vec, undef, self.const_null(vec_i32_ty))
1203 }
1204 }
1205
1206 fn extract_value(&mut self, agg_val: &'ll Value, idx: u64) -> &'ll Value {
1207 assert_eq!(idx as c_uint as u64, idx);
1208 unsafe { llvm::LLVMBuildExtractValue(self.llbuilder, agg_val, idx as c_uint, UNNAMED) }
1209 }
1210
1211 fn insert_value(&mut self, agg_val: &'ll Value, elt: &'ll Value, idx: u64) -> &'ll Value {
1212 assert_eq!(idx as c_uint as u64, idx);
1213 unsafe { llvm::LLVMBuildInsertValue(self.llbuilder, agg_val, elt, idx as c_uint, UNNAMED) }
1214 }
1215
1216 fn set_personality_fn(&mut self, personality: &'ll Value) {
1217 unsafe {
1218 llvm::LLVMSetPersonalityFn(self.llfn(), personality);
1219 }
1220 }
1221
1222 fn cleanup_landing_pad(&mut self, pers_fn: &'ll Value) -> (&'ll Value, &'ll Value) {
1223 let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1224 let landing_pad = self.landing_pad(ty, pers_fn, 0);
1225 unsafe {
1226 llvm::LLVMSetCleanup(landing_pad, llvm::TRUE);
1227 }
1228 (self.extract_value(landing_pad, 0), self.extract_value(landing_pad, 1))
1229 }
1230
1231 fn filter_landing_pad(&mut self, pers_fn: &'ll Value) {
1232 let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1233 let landing_pad = self.landing_pad(ty, pers_fn, 1);
1234 self.add_clause(landing_pad, self.const_array(self.type_ptr(), &[]));
1235 }
1236
1237 fn resume(&mut self, exn0: &'ll Value, exn1: &'ll Value) {
1238 let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1239 let mut exn = self.const_poison(ty);
1240 exn = self.insert_value(exn, exn0, 0);
1241 exn = self.insert_value(exn, exn1, 1);
1242 unsafe {
1243 llvm::LLVMBuildResume(self.llbuilder, exn);
1244 }
1245 }
1246
1247 fn cleanup_pad(&mut self, parent: Option<&'ll Value>, args: &[&'ll Value]) -> Funclet<'ll> {
1248 let ret = unsafe {
1249 llvm::LLVMBuildCleanupPad(
1250 self.llbuilder,
1251 parent,
1252 args.as_ptr(),
1253 args.len() as c_uint,
1254 c"cleanuppad".as_ptr(),
1255 )
1256 };
1257 Funclet::new(ret.expect("LLVM does not have support for cleanuppad"))
1258 }
1259
1260 fn cleanup_ret(&mut self, funclet: &Funclet<'ll>, unwind: Option<&'ll BasicBlock>) {
1261 unsafe {
1262 llvm::LLVMBuildCleanupRet(self.llbuilder, funclet.cleanuppad(), unwind)
1263 .expect("LLVM does not have support for cleanupret");
1264 }
1265 }
1266
1267 fn catch_pad(&mut self, parent: &'ll Value, args: &[&'ll Value]) -> Funclet<'ll> {
1268 let ret = unsafe {
1269 llvm::LLVMBuildCatchPad(
1270 self.llbuilder,
1271 parent,
1272 args.as_ptr(),
1273 args.len() as c_uint,
1274 c"catchpad".as_ptr(),
1275 )
1276 };
1277 Funclet::new(ret.expect("LLVM does not have support for catchpad"))
1278 }
1279
1280 fn catch_switch(
1281 &mut self,
1282 parent: Option<&'ll Value>,
1283 unwind: Option<&'ll BasicBlock>,
1284 handlers: &[&'ll BasicBlock],
1285 ) -> &'ll Value {
1286 let ret = unsafe {
1287 llvm::LLVMBuildCatchSwitch(
1288 self.llbuilder,
1289 parent,
1290 unwind,
1291 handlers.len() as c_uint,
1292 c"catchswitch".as_ptr(),
1293 )
1294 };
1295 let ret = ret.expect("LLVM does not have support for catchswitch");
1296 for handler in handlers {
1297 unsafe {
1298 llvm::LLVMAddHandler(ret, handler);
1299 }
1300 }
1301 ret
1302 }
1303
1304 fn atomic_cmpxchg(
1306 &mut self,
1307 dst: &'ll Value,
1308 cmp: &'ll Value,
1309 src: &'ll Value,
1310 order: rustc_middle::ty::AtomicOrdering,
1311 failure_order: rustc_middle::ty::AtomicOrdering,
1312 weak: bool,
1313 ) -> (&'ll Value, &'ll Value) {
1314 unsafe {
1315 let value = llvm::LLVMBuildAtomicCmpXchg(
1316 self.llbuilder,
1317 dst,
1318 cmp,
1319 src,
1320 AtomicOrdering::from_generic(order),
1321 AtomicOrdering::from_generic(failure_order),
1322 llvm::FALSE, );
1324 llvm::LLVMSetWeak(value, weak.to_llvm_bool());
1325 let val = self.extract_value(value, 0);
1326 let success = self.extract_value(value, 1);
1327 (val, success)
1328 }
1329 }
1330
1331 fn atomic_rmw(
1332 &mut self,
1333 op: rustc_codegen_ssa::common::AtomicRmwBinOp,
1334 dst: &'ll Value,
1335 src: &'ll Value,
1336 order: rustc_middle::ty::AtomicOrdering,
1337 ret_ptr: bool,
1338 ) -> &'ll Value {
1339 let mut res = unsafe {
1343 llvm::LLVMBuildAtomicRMW(
1344 self.llbuilder,
1345 AtomicRmwBinOp::from_generic(op),
1346 dst,
1347 src,
1348 AtomicOrdering::from_generic(order),
1349 llvm::FALSE, )
1351 };
1352 if ret_ptr && self.val_ty(res) != self.type_ptr() {
1353 res = self.inttoptr(res, self.type_ptr());
1354 }
1355 res
1356 }
1357
1358 fn atomic_fence(
1359 &mut self,
1360 order: rustc_middle::ty::AtomicOrdering,
1361 scope: SynchronizationScope,
1362 ) {
1363 let single_threaded = match scope {
1364 SynchronizationScope::SingleThread => true,
1365 SynchronizationScope::CrossThread => false,
1366 };
1367 unsafe {
1368 llvm::LLVMBuildFence(
1369 self.llbuilder,
1370 AtomicOrdering::from_generic(order),
1371 single_threaded.to_llvm_bool(),
1372 UNNAMED,
1373 );
1374 }
1375 }
1376
1377 fn set_invariant_load(&mut self, load: &'ll Value) {
1378 unsafe {
1379 let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, ptr::null(), 0);
1380 self.set_metadata(load, llvm::MD_invariant_load, md);
1381 }
1382 }
1383
1384 fn lifetime_start(&mut self, ptr: &'ll Value, size: Size) {
1385 self.call_lifetime_intrinsic("llvm.lifetime.start", ptr, size);
1386 }
1387
1388 fn lifetime_end(&mut self, ptr: &'ll Value, size: Size) {
1389 self.call_lifetime_intrinsic("llvm.lifetime.end", ptr, size);
1390 }
1391
1392 fn call(
1393 &mut self,
1394 llty: &'ll Type,
1395 fn_call_attrs: Option<&CodegenFnAttrs>,
1396 fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1397 llfn: &'ll Value,
1398 args: &[&'ll Value],
1399 funclet: Option<&Funclet<'ll>>,
1400 instance: Option<Instance<'tcx>>,
1401 ) -> &'ll Value {
1402 debug!("call {:?} with args ({:?})", llfn, args);
1403
1404 let args = self.check_call("call", llty, llfn, args);
1405 let funclet_bundle = funclet.map(|funclet| funclet.bundle());
1406 let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
1407 if let Some(funclet_bundle) = funclet_bundle {
1408 bundles.push(funclet_bundle);
1409 }
1410
1411 self.cfi_type_test(fn_call_attrs, fn_abi, instance, llfn);
1413
1414 let kcfi_bundle = self.kcfi_operand_bundle(fn_call_attrs, fn_abi, instance, llfn);
1416 if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
1417 bundles.push(kcfi_bundle);
1418 }
1419
1420 let call = unsafe {
1421 llvm::LLVMBuildCallWithOperandBundles(
1422 self.llbuilder,
1423 llty,
1424 llfn,
1425 args.as_ptr() as *const &llvm::Value,
1426 args.len() as c_uint,
1427 bundles.as_ptr(),
1428 bundles.len() as c_uint,
1429 c"".as_ptr(),
1430 )
1431 };
1432
1433 if let Some(instance) = instance {
1434 let fn_defn_attrs = self.cx.tcx.codegen_fn_attrs(instance.def_id());
1436 if let Some(fn_call_attrs) = fn_call_attrs
1437 && !fn_call_attrs.target_features.is_empty()
1438 && let Some(inlining_rule) = attributes::inline_attr(&self.cx, instance)
1442 && self.cx.tcx.is_target_feature_call_safe(
1443 &fn_call_attrs.target_features,
1444 &fn_defn_attrs.target_features,
1445 )
1446 {
1447 attributes::apply_to_callsite(
1448 call,
1449 llvm::AttributePlace::Function,
1450 &[inlining_rule],
1451 );
1452 }
1453 }
1454
1455 if let Some(fn_abi) = fn_abi {
1456 fn_abi.apply_attrs_callsite(self, call);
1457 }
1458 call
1459 }
1460
1461 fn tail_call(
1462 &mut self,
1463 llty: Self::Type,
1464 fn_attrs: Option<&CodegenFnAttrs>,
1465 fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
1466 llfn: Self::Value,
1467 args: &[Self::Value],
1468 funclet: Option<&Self::Funclet>,
1469 instance: Option<Instance<'tcx>>,
1470 ) {
1471 let call = self.call(llty, fn_attrs, Some(fn_abi), llfn, args, funclet, instance);
1472 llvm::LLVMSetTailCallKind(call, llvm::TailCallKind::MustTail);
1473
1474 match &fn_abi.ret.mode {
1475 PassMode::Ignore | PassMode::Indirect { .. } => self.ret_void(),
1476 PassMode::Direct(_) | PassMode::Pair { .. } => self.ret(call),
1477 mode @ PassMode::Cast { .. } => {
1478 bug!("Encountered `PassMode::{mode:?}` during codegen")
1479 }
1480 }
1481 }
1482
1483 fn zext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1484 unsafe { llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty, UNNAMED) }
1485 }
1486
1487 fn apply_attrs_to_cleanup_callsite(&mut self, llret: &'ll Value) {
1488 let cold_inline = llvm::AttributeKind::Cold.create_attr(self.llcx);
1490 attributes::apply_to_callsite(llret, llvm::AttributePlace::Function, &[cold_inline]);
1491 }
1492}
1493
1494impl<'ll> StaticBuilderMethods for Builder<'_, 'll, '_> {
1495 fn get_static(&mut self, def_id: DefId) -> &'ll Value {
1496 let global = self.cx().get_static(def_id);
1498 if self.cx().tcx.is_thread_local_static(def_id) {
1499 let pointer =
1500 self.call_intrinsic("llvm.threadlocal.address", &[self.val_ty(global)], &[global]);
1501 self.pointercast(pointer, self.type_ptr())
1503 } else {
1504 self.cx().const_pointercast(global, self.type_ptr())
1506 }
1507 }
1508}
1509
1510impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1511 pub(crate) fn llfn(&self) -> &'ll Value {
1512 unsafe { llvm::LLVMGetBasicBlockParent(self.llbb()) }
1513 }
1514}
1515
1516impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1517 fn position_at_start(&mut self, llbb: &'ll BasicBlock) {
1518 unsafe {
1519 llvm::LLVMRustPositionBuilderAtStart(self.llbuilder, llbb);
1520 }
1521 }
1522}
1523impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1524 fn align_metadata(&mut self, load: &'ll Value, align: Align) {
1525 unsafe {
1526 let md = [llvm::LLVMValueAsMetadata(self.cx.const_u64(align.bytes()))];
1527 let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, md.as_ptr(), md.len());
1528 self.set_metadata(load, llvm::MD_align, md);
1529 }
1530 }
1531
1532 fn noundef_metadata(&mut self, load: &'ll Value) {
1533 unsafe {
1534 let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, ptr::null(), 0);
1535 self.set_metadata(load, llvm::MD_noundef, md);
1536 }
1537 }
1538
1539 pub(crate) fn set_unpredictable(&mut self, inst: &'ll Value) {
1540 unsafe {
1541 let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, ptr::null(), 0);
1542 self.set_metadata(inst, llvm::MD_unpredictable, md);
1543 }
1544 }
1545}
1546impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1547 pub(crate) fn minnum(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1548 unsafe { llvm::LLVMRustBuildMinNum(self.llbuilder, lhs, rhs) }
1549 }
1550
1551 pub(crate) fn maxnum(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1552 unsafe { llvm::LLVMRustBuildMaxNum(self.llbuilder, lhs, rhs) }
1553 }
1554
1555 pub(crate) fn insert_element(
1556 &mut self,
1557 vec: &'ll Value,
1558 elt: &'ll Value,
1559 idx: &'ll Value,
1560 ) -> &'ll Value {
1561 unsafe { llvm::LLVMBuildInsertElement(self.llbuilder, vec, elt, idx, UNNAMED) }
1562 }
1563
1564 pub(crate) fn shuffle_vector(
1565 &mut self,
1566 v1: &'ll Value,
1567 v2: &'ll Value,
1568 mask: &'ll Value,
1569 ) -> &'ll Value {
1570 unsafe { llvm::LLVMBuildShuffleVector(self.llbuilder, v1, v2, mask, UNNAMED) }
1571 }
1572
1573 pub(crate) fn vector_reduce_fadd(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1574 unsafe { llvm::LLVMRustBuildVectorReduceFAdd(self.llbuilder, acc, src) }
1575 }
1576 pub(crate) fn vector_reduce_fmul(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1577 unsafe { llvm::LLVMRustBuildVectorReduceFMul(self.llbuilder, acc, src) }
1578 }
1579 pub(crate) fn vector_reduce_fadd_reassoc(
1580 &mut self,
1581 acc: &'ll Value,
1582 src: &'ll Value,
1583 ) -> &'ll Value {
1584 unsafe {
1585 let instr = llvm::LLVMRustBuildVectorReduceFAdd(self.llbuilder, acc, src);
1586 llvm::LLVMRustSetAllowReassoc(instr);
1587 instr
1588 }
1589 }
1590 pub(crate) fn vector_reduce_fmul_reassoc(
1591 &mut self,
1592 acc: &'ll Value,
1593 src: &'ll Value,
1594 ) -> &'ll Value {
1595 unsafe {
1596 let instr = llvm::LLVMRustBuildVectorReduceFMul(self.llbuilder, acc, src);
1597 llvm::LLVMRustSetAllowReassoc(instr);
1598 instr
1599 }
1600 }
1601 pub(crate) fn vector_reduce_add(&mut self, src: &'ll Value) -> &'ll Value {
1602 unsafe { llvm::LLVMRustBuildVectorReduceAdd(self.llbuilder, src) }
1603 }
1604 pub(crate) fn vector_reduce_mul(&mut self, src: &'ll Value) -> &'ll Value {
1605 unsafe { llvm::LLVMRustBuildVectorReduceMul(self.llbuilder, src) }
1606 }
1607 pub(crate) fn vector_reduce_and(&mut self, src: &'ll Value) -> &'ll Value {
1608 unsafe { llvm::LLVMRustBuildVectorReduceAnd(self.llbuilder, src) }
1609 }
1610 pub(crate) fn vector_reduce_or(&mut self, src: &'ll Value) -> &'ll Value {
1611 unsafe { llvm::LLVMRustBuildVectorReduceOr(self.llbuilder, src) }
1612 }
1613 pub(crate) fn vector_reduce_xor(&mut self, src: &'ll Value) -> &'ll Value {
1614 unsafe { llvm::LLVMRustBuildVectorReduceXor(self.llbuilder, src) }
1615 }
1616 pub(crate) fn vector_reduce_fmin(&mut self, src: &'ll Value) -> &'ll Value {
1617 unsafe {
1618 llvm::LLVMRustBuildVectorReduceFMin(self.llbuilder, src, false)
1619 }
1620 }
1621 pub(crate) fn vector_reduce_fmax(&mut self, src: &'ll Value) -> &'ll Value {
1622 unsafe {
1623 llvm::LLVMRustBuildVectorReduceFMax(self.llbuilder, src, false)
1624 }
1625 }
1626 pub(crate) fn vector_reduce_min(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1627 unsafe { llvm::LLVMRustBuildVectorReduceMin(self.llbuilder, src, is_signed) }
1628 }
1629 pub(crate) fn vector_reduce_max(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1630 unsafe { llvm::LLVMRustBuildVectorReduceMax(self.llbuilder, src, is_signed) }
1631 }
1632
1633 pub(crate) fn add_clause(&mut self, landing_pad: &'ll Value, clause: &'ll Value) {
1634 unsafe {
1635 llvm::LLVMAddClause(landing_pad, clause);
1636 }
1637 }
1638
1639 pub(crate) fn catch_ret(
1640 &mut self,
1641 funclet: &Funclet<'ll>,
1642 unwind: &'ll BasicBlock,
1643 ) -> &'ll Value {
1644 let ret = unsafe { llvm::LLVMBuildCatchRet(self.llbuilder, funclet.cleanuppad(), unwind) };
1645 ret.expect("LLVM does not have support for catchret")
1646 }
1647
1648 fn check_call<'b>(
1649 &mut self,
1650 typ: &str,
1651 fn_ty: &'ll Type,
1652 llfn: &'ll Value,
1653 args: &'b [&'ll Value],
1654 ) -> Cow<'b, [&'ll Value]> {
1655 assert!(
1656 self.cx.type_kind(fn_ty) == TypeKind::Function,
1657 "builder::{typ} not passed a function, but {fn_ty:?}"
1658 );
1659
1660 let param_tys = self.cx.func_params_types(fn_ty);
1661
1662 let all_args_match = iter::zip(¶m_tys, args.iter().map(|&v| self.cx.val_ty(v)))
1663 .all(|(expected_ty, actual_ty)| *expected_ty == actual_ty);
1664
1665 if all_args_match {
1666 return Cow::Borrowed(args);
1667 }
1668
1669 let casted_args: Vec<_> = iter::zip(param_tys, args)
1670 .enumerate()
1671 .map(|(i, (expected_ty, &actual_val))| {
1672 let actual_ty = self.cx.val_ty(actual_val);
1673 if expected_ty != actual_ty {
1674 debug!(
1675 "type mismatch in function call of {:?}. \
1676 Expected {:?} for param {}, got {:?}; injecting bitcast",
1677 llfn, expected_ty, i, actual_ty
1678 );
1679 self.bitcast(actual_val, expected_ty)
1680 } else {
1681 actual_val
1682 }
1683 })
1684 .collect();
1685
1686 Cow::Owned(casted_args)
1687 }
1688
1689 pub(crate) fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
1690 unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
1691 }
1692}
1693
1694impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1695 pub(crate) fn call_intrinsic(
1696 &mut self,
1697 base_name: impl Into<Cow<'static, str>>,
1698 type_params: &[&'ll Type],
1699 args: &[&'ll Value],
1700 ) -> &'ll Value {
1701 let (ty, f) = self.cx.get_intrinsic(base_name.into(), type_params);
1702 self.call(ty, None, None, f, args, None, None)
1703 }
1704
1705 fn call_lifetime_intrinsic(&mut self, intrinsic: &'static str, ptr: &'ll Value, size: Size) {
1706 let size = size.bytes();
1707 if size == 0 {
1708 return;
1709 }
1710
1711 if !self.cx().sess().emit_lifetime_markers() {
1712 return;
1713 }
1714
1715 if crate::llvm_util::get_version() >= (22, 0, 0) {
1716 self.call_intrinsic(intrinsic, &[self.val_ty(ptr)], &[ptr]);
1717 } else {
1718 self.call_intrinsic(intrinsic, &[self.val_ty(ptr)], &[self.cx.const_u64(size), ptr]);
1719 }
1720 }
1721}
1722impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1723 pub(crate) fn phi(
1724 &mut self,
1725 ty: &'ll Type,
1726 vals: &[&'ll Value],
1727 bbs: &[&'ll BasicBlock],
1728 ) -> &'ll Value {
1729 assert_eq!(vals.len(), bbs.len());
1730 let phi = unsafe { llvm::LLVMBuildPhi(self.llbuilder, ty, UNNAMED) };
1731 unsafe {
1732 llvm::LLVMAddIncoming(phi, vals.as_ptr(), bbs.as_ptr(), vals.len() as c_uint);
1733 phi
1734 }
1735 }
1736
1737 fn add_incoming_to_phi(&mut self, phi: &'ll Value, val: &'ll Value, bb: &'ll BasicBlock) {
1738 unsafe {
1739 llvm::LLVMAddIncoming(phi, &val, &bb, 1 as c_uint);
1740 }
1741 }
1742}
1743impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1744 pub(crate) fn landing_pad(
1745 &mut self,
1746 ty: &'ll Type,
1747 pers_fn: &'ll Value,
1748 num_clauses: usize,
1749 ) -> &'ll Value {
1750 self.set_personality_fn(pers_fn);
1754 unsafe {
1755 llvm::LLVMBuildLandingPad(self.llbuilder, ty, None, num_clauses as c_uint, UNNAMED)
1756 }
1757 }
1758
1759 pub(crate) fn callbr(
1760 &mut self,
1761 llty: &'ll Type,
1762 fn_attrs: Option<&CodegenFnAttrs>,
1763 fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1764 llfn: &'ll Value,
1765 args: &[&'ll Value],
1766 default_dest: &'ll BasicBlock,
1767 indirect_dest: &[&'ll BasicBlock],
1768 funclet: Option<&Funclet<'ll>>,
1769 instance: Option<Instance<'tcx>>,
1770 ) -> &'ll Value {
1771 debug!("invoke {:?} with args ({:?})", llfn, args);
1772
1773 let args = self.check_call("callbr", llty, llfn, args);
1774 let funclet_bundle = funclet.map(|funclet| funclet.bundle());
1775 let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
1776 if let Some(funclet_bundle) = funclet_bundle {
1777 bundles.push(funclet_bundle);
1778 }
1779
1780 self.cfi_type_test(fn_attrs, fn_abi, instance, llfn);
1782
1783 let kcfi_bundle = self.kcfi_operand_bundle(fn_attrs, fn_abi, instance, llfn);
1785 if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
1786 bundles.push(kcfi_bundle);
1787 }
1788
1789 let callbr = unsafe {
1790 llvm::LLVMBuildCallBr(
1791 self.llbuilder,
1792 llty,
1793 llfn,
1794 default_dest,
1795 indirect_dest.as_ptr(),
1796 indirect_dest.len() as c_uint,
1797 args.as_ptr(),
1798 args.len() as c_uint,
1799 bundles.as_ptr(),
1800 bundles.len() as c_uint,
1801 UNNAMED,
1802 )
1803 };
1804 if let Some(fn_abi) = fn_abi {
1805 fn_abi.apply_attrs_callsite(self, callbr);
1806 }
1807 callbr
1808 }
1809
1810 fn cfi_type_test(
1812 &mut self,
1813 fn_attrs: Option<&CodegenFnAttrs>,
1814 fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1815 instance: Option<Instance<'tcx>>,
1816 llfn: &'ll Value,
1817 ) {
1818 let is_indirect_call = unsafe { llvm::LLVMRustIsNonGVFunctionPointerTy(llfn) };
1819 if self.tcx.sess.is_sanitizer_cfi_enabled()
1820 && let Some(fn_abi) = fn_abi
1821 && is_indirect_call
1822 {
1823 if let Some(fn_attrs) = fn_attrs
1824 && fn_attrs.no_sanitize.contains(SanitizerSet::CFI)
1825 {
1826 return;
1827 }
1828
1829 let mut options = cfi::TypeIdOptions::empty();
1830 if self.tcx.sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1831 options.insert(cfi::TypeIdOptions::GENERALIZE_POINTERS);
1832 }
1833 if self.tcx.sess.is_sanitizer_cfi_normalize_integers_enabled() {
1834 options.insert(cfi::TypeIdOptions::NORMALIZE_INTEGERS);
1835 }
1836
1837 let typeid = if let Some(instance) = instance {
1838 cfi::typeid_for_instance(self.tcx, instance, options)
1839 } else {
1840 cfi::typeid_for_fnabi(self.tcx, fn_abi, options)
1841 };
1842 let typeid_metadata = self.cx.create_metadata(typeid.as_bytes());
1843 let dbg_loc = self.get_dbg_loc();
1844
1845 let typeid = self.get_metadata_value(typeid_metadata);
1849 let cond = self.call_intrinsic("llvm.type.test", &[], &[llfn, typeid]);
1850 let bb_pass = self.append_sibling_block("type_test.pass");
1851 let bb_fail = self.append_sibling_block("type_test.fail");
1852 self.cond_br(cond, bb_pass, bb_fail);
1853
1854 self.switch_to_block(bb_fail);
1855 if let Some(dbg_loc) = dbg_loc {
1856 self.set_dbg_loc(dbg_loc);
1857 }
1858 self.abort();
1859 self.unreachable();
1860
1861 self.switch_to_block(bb_pass);
1862 if let Some(dbg_loc) = dbg_loc {
1863 self.set_dbg_loc(dbg_loc);
1864 }
1865 }
1866 }
1867
1868 fn kcfi_operand_bundle(
1870 &mut self,
1871 fn_attrs: Option<&CodegenFnAttrs>,
1872 fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1873 instance: Option<Instance<'tcx>>,
1874 llfn: &'ll Value,
1875 ) -> Option<llvm::OperandBundleBox<'ll>> {
1876 let is_indirect_call = unsafe { llvm::LLVMRustIsNonGVFunctionPointerTy(llfn) };
1877 let kcfi_bundle = if self.tcx.sess.is_sanitizer_kcfi_enabled()
1878 && let Some(fn_abi) = fn_abi
1879 && is_indirect_call
1880 {
1881 if let Some(fn_attrs) = fn_attrs
1882 && fn_attrs.no_sanitize.contains(SanitizerSet::KCFI)
1883 {
1884 return None;
1885 }
1886
1887 let mut options = kcfi::TypeIdOptions::empty();
1888 if self.tcx.sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1889 options.insert(kcfi::TypeIdOptions::GENERALIZE_POINTERS);
1890 }
1891 if self.tcx.sess.is_sanitizer_cfi_normalize_integers_enabled() {
1892 options.insert(kcfi::TypeIdOptions::NORMALIZE_INTEGERS);
1893 }
1894
1895 let kcfi_typeid = if let Some(instance) = instance {
1896 kcfi::typeid_for_instance(self.tcx, instance, options)
1897 } else {
1898 kcfi::typeid_for_fnabi(self.tcx, fn_abi, options)
1899 };
1900
1901 Some(llvm::OperandBundleBox::new("kcfi", &[self.const_u32(kcfi_typeid)]))
1902 } else {
1903 None
1904 };
1905 kcfi_bundle
1906 }
1907
1908 #[instrument(level = "debug", skip(self))]
1910 pub(crate) fn instrprof_increment(
1911 &mut self,
1912 fn_name: &'ll Value,
1913 hash: &'ll Value,
1914 num_counters: &'ll Value,
1915 index: &'ll Value,
1916 ) {
1917 self.call_intrinsic("llvm.instrprof.increment", &[], &[fn_name, hash, num_counters, index]);
1918 }
1919}