1 //! Codegen of intrinsics. This includes `extern "rust-intrinsic"`, `extern "platform-intrinsic"`
2 //! and LLVM intrinsics that have symbol names starting with `llvm.`.
4 macro_rules! intrinsic_pat {
19 macro_rules! intrinsic_arg {
20 (o $fx:expr, $arg:ident) => {};
21 (c $fx:expr, $arg:ident) => {
22 let $arg = codegen_operand($fx, $arg);
24 (v $fx:expr, $arg:ident) => {
25 let $arg = codegen_operand($fx, $arg).load_scalar($fx);
29 macro_rules! intrinsic_match {
30 ($fx:expr, $intrinsic:expr, $args:expr,
33 $($($name:tt).*)|+ $(if $cond:expr)?, ($($a:ident $arg:ident),*) $content:block;
37 $(intrinsic_pat!($($name).*))|* $(if $cond)? => {
38 if let [$($arg),*] = $args {
39 $(intrinsic_arg!($a $fx, $arg);)*
42 bug!("wrong number of args for intrinsic {:?}", $intrinsic);
55 pub(crate) use cpuid::codegen_cpuid_call;
56 pub(crate) use llvm::codegen_llvm_intrinsic_call;
58 use rustc_middle::ty::print::with_no_trimmed_paths;
59 use rustc_middle::ty::subst::SubstsRef;
60 use rustc_span::symbol::{kw, sym, Symbol};
62 use crate::prelude::*;
63 use cranelift_codegen::ir::AtomicRmwOp;
65 fn report_atomic_type_validation_error<'tcx>(
66 fx: &mut FunctionCx<'_, '_, 'tcx>,
74 "`{}` intrinsic: expected basic integer or raw pointer type, found `{:?}`",
78 // Prevent verifier error
79 crate::trap::trap_unreachable(fx, "compilation should not have succeeded");
82 pub(crate) fn clif_vector_type<'tcx>(tcx: TyCtxt<'tcx>, layout: TyAndLayout<'tcx>) -> Option<Type> {
83 let (element, count) = match layout.abi {
84 Abi::Vector { element, count } => (element, count),
88 match scalar_to_clif_type(tcx, element).by(u16::try_from(count).unwrap()) {
89 // Cranelift currently only implements icmp for 128bit vectors.
90 Some(vector_ty) if vector_ty.bits() == 128 => Some(vector_ty),
95 fn simd_for_each_lane<'tcx>(
96 fx: &mut FunctionCx<'_, '_, 'tcx>,
99 f: &dyn Fn(&mut FunctionCx<'_, '_, 'tcx>, Ty<'tcx>, Ty<'tcx>, Value) -> Value,
101 let layout = val.layout();
103 let (lane_count, lane_ty) = layout.ty.simd_size_and_type(fx.tcx);
104 let lane_layout = fx.layout_of(lane_ty);
105 let (ret_lane_count, ret_lane_ty) = ret.layout().ty.simd_size_and_type(fx.tcx);
106 let ret_lane_layout = fx.layout_of(ret_lane_ty);
107 assert_eq!(lane_count, ret_lane_count);
109 for lane_idx in 0..lane_count {
110 let lane = val.value_lane(fx, lane_idx).load_scalar(fx);
112 let res_lane = f(fx, lane_layout.ty, ret_lane_layout.ty, lane);
113 let res_lane = CValue::by_val(res_lane, ret_lane_layout);
115 ret.place_lane(fx, lane_idx).write_cvalue(fx, res_lane);
119 fn simd_pair_for_each_lane<'tcx>(
120 fx: &mut FunctionCx<'_, '_, 'tcx>,
124 f: &dyn Fn(&mut FunctionCx<'_, '_, 'tcx>, Ty<'tcx>, Ty<'tcx>, Value, Value) -> Value,
126 assert_eq!(x.layout(), y.layout());
127 let layout = x.layout();
129 let (lane_count, lane_ty) = layout.ty.simd_size_and_type(fx.tcx);
130 let lane_layout = fx.layout_of(lane_ty);
131 let (ret_lane_count, ret_lane_ty) = ret.layout().ty.simd_size_and_type(fx.tcx);
132 let ret_lane_layout = fx.layout_of(ret_lane_ty);
133 assert_eq!(lane_count, ret_lane_count);
135 for lane_idx in 0..lane_count {
136 let x_lane = x.value_lane(fx, lane_idx).load_scalar(fx);
137 let y_lane = y.value_lane(fx, lane_idx).load_scalar(fx);
139 let res_lane = f(fx, lane_layout.ty, ret_lane_layout.ty, x_lane, y_lane);
140 let res_lane = CValue::by_val(res_lane, ret_lane_layout);
142 ret.place_lane(fx, lane_idx).write_cvalue(fx, res_lane);
146 fn simd_reduce<'tcx>(
147 fx: &mut FunctionCx<'_, '_, 'tcx>,
151 f: &dyn Fn(&mut FunctionCx<'_, '_, 'tcx>, Ty<'tcx>, Value, Value) -> Value,
153 let (lane_count, lane_ty) = val.layout().ty.simd_size_and_type(fx.tcx);
154 let lane_layout = fx.layout_of(lane_ty);
155 assert_eq!(lane_layout, ret.layout());
157 let (mut res_val, start_lane) =
158 if let Some(acc) = acc { (acc, 0) } else { (val.value_lane(fx, 0).load_scalar(fx), 1) };
159 for lane_idx in start_lane..lane_count {
160 let lane = val.value_lane(fx, lane_idx).load_scalar(fx);
161 res_val = f(fx, lane_layout.ty, res_val, lane);
163 let res = CValue::by_val(res_val, lane_layout);
164 ret.write_cvalue(fx, res);
167 // FIXME move all uses to `simd_reduce`
168 fn simd_reduce_bool<'tcx>(
169 fx: &mut FunctionCx<'_, '_, 'tcx>,
172 f: &dyn Fn(&mut FunctionCx<'_, '_, 'tcx>, Value, Value) -> Value,
174 let (lane_count, _lane_ty) = val.layout().ty.simd_size_and_type(fx.tcx);
175 assert!(ret.layout().ty.is_bool());
177 let res_val = val.value_lane(fx, 0).load_scalar(fx);
178 let mut res_val = fx.bcx.ins().band_imm(res_val, 1); // mask to boolean
179 for lane_idx in 1..lane_count {
180 let lane = val.value_lane(fx, lane_idx).load_scalar(fx);
181 let lane = fx.bcx.ins().band_imm(lane, 1); // mask to boolean
182 res_val = f(fx, res_val, lane);
184 let res_val = if fx.bcx.func.dfg.value_type(res_val) != types::I8 {
185 fx.bcx.ins().ireduce(types::I8, res_val)
189 let res = CValue::by_val(res_val, ret.layout());
190 ret.write_cvalue(fx, res);
193 fn bool_to_zero_or_max_uint<'tcx>(
194 fx: &mut FunctionCx<'_, '_, 'tcx>,
198 let ty = fx.clif_type(ty).unwrap();
200 let int_ty = match ty {
201 types::F32 => types::I32,
202 types::F64 => types::I64,
206 let val = fx.bcx.ins().bint(int_ty, val);
207 let mut res = fx.bcx.ins().ineg(val);
210 res = fx.bcx.ins().bitcast(ty, res);
216 pub(crate) fn codegen_intrinsic_call<'tcx>(
217 fx: &mut FunctionCx<'_, '_, 'tcx>,
218 instance: Instance<'tcx>,
219 args: &[mir::Operand<'tcx>],
220 destination: Option<(CPlace<'tcx>, BasicBlock)>,
223 let intrinsic = fx.tcx.item_name(instance.def_id());
224 let substs = instance.substs;
226 let ret = match destination {
227 Some((place, _)) => place,
229 // Insert non returning intrinsics here
232 fx.bcx.ins().trap(TrapCode::User(0));
235 crate::base::codegen_panic(fx, "Transmuting to uninhabited type.", span);
237 _ => unimplemented!("unsupported instrinsic {}", intrinsic),
243 if intrinsic.as_str().starts_with("simd_") {
244 self::simd::codegen_simd_intrinsic_call(fx, intrinsic, substs, args, ret, span);
245 let ret_block = fx.get_block(destination.expect("SIMD intrinsics don't diverge").1);
246 fx.bcx.ins().jump(ret_block, &[]);
247 } else if codegen_float_intrinsic_call(fx, intrinsic, args, ret) {
248 let ret_block = fx.get_block(destination.expect("Float intrinsics don't diverge").1);
249 fx.bcx.ins().jump(ret_block, &[]);
251 codegen_regular_intrinsic_call(
264 fn codegen_float_intrinsic_call<'tcx>(
265 fx: &mut FunctionCx<'_, '_, 'tcx>,
267 args: &[mir::Operand<'tcx>],
270 let (name, arg_count, ty) = match intrinsic {
271 sym::expf32 => ("expf", 1, fx.tcx.types.f32),
272 sym::expf64 => ("exp", 1, fx.tcx.types.f64),
273 sym::exp2f32 => ("exp2f", 1, fx.tcx.types.f32),
274 sym::exp2f64 => ("exp2", 1, fx.tcx.types.f64),
275 sym::sqrtf32 => ("sqrtf", 1, fx.tcx.types.f32),
276 sym::sqrtf64 => ("sqrt", 1, fx.tcx.types.f64),
277 sym::powif32 => ("__powisf2", 2, fx.tcx.types.f32), // compiler-builtins
278 sym::powif64 => ("__powidf2", 2, fx.tcx.types.f64), // compiler-builtins
279 sym::powf32 => ("powf", 2, fx.tcx.types.f32),
280 sym::powf64 => ("pow", 2, fx.tcx.types.f64),
281 sym::logf32 => ("logf", 1, fx.tcx.types.f32),
282 sym::logf64 => ("log", 1, fx.tcx.types.f64),
283 sym::log2f32 => ("log2f", 1, fx.tcx.types.f32),
284 sym::log2f64 => ("log2", 1, fx.tcx.types.f64),
285 sym::log10f32 => ("log10f", 1, fx.tcx.types.f32),
286 sym::log10f64 => ("log10", 1, fx.tcx.types.f64),
287 sym::fabsf32 => ("fabsf", 1, fx.tcx.types.f32),
288 sym::fabsf64 => ("fabs", 1, fx.tcx.types.f64),
289 sym::fmaf32 => ("fmaf", 3, fx.tcx.types.f32),
290 sym::fmaf64 => ("fma", 3, fx.tcx.types.f64),
291 sym::copysignf32 => ("copysignf", 2, fx.tcx.types.f32),
292 sym::copysignf64 => ("copysign", 2, fx.tcx.types.f64),
293 sym::floorf32 => ("floorf", 1, fx.tcx.types.f32),
294 sym::floorf64 => ("floor", 1, fx.tcx.types.f64),
295 sym::ceilf32 => ("ceilf", 1, fx.tcx.types.f32),
296 sym::ceilf64 => ("ceil", 1, fx.tcx.types.f64),
297 sym::truncf32 => ("truncf", 1, fx.tcx.types.f32),
298 sym::truncf64 => ("trunc", 1, fx.tcx.types.f64),
299 sym::roundf32 => ("roundf", 1, fx.tcx.types.f32),
300 sym::roundf64 => ("round", 1, fx.tcx.types.f64),
301 sym::sinf32 => ("sinf", 1, fx.tcx.types.f32),
302 sym::sinf64 => ("sin", 1, fx.tcx.types.f64),
303 sym::cosf32 => ("cosf", 1, fx.tcx.types.f32),
304 sym::cosf64 => ("cos", 1, fx.tcx.types.f64),
308 if args.len() != arg_count {
309 bug!("wrong number of args for intrinsic {:?}", intrinsic);
313 let args = match args {
315 a = [codegen_operand(fx, x)];
319 b = [codegen_operand(fx, x), codegen_operand(fx, y)];
323 c = [codegen_operand(fx, x), codegen_operand(fx, y), codegen_operand(fx, z)];
329 let res = fx.easy_call(name, &args, ty);
330 ret.write_cvalue(fx, res);
335 fn codegen_regular_intrinsic_call<'tcx>(
336 fx: &mut FunctionCx<'_, '_, 'tcx>,
337 instance: Instance<'tcx>,
339 substs: SubstsRef<'tcx>,
340 args: &[mir::Operand<'tcx>],
343 destination: Option<(CPlace<'tcx>, BasicBlock)>,
345 let usize_layout = fx.layout_of(fx.tcx.types.usize);
350 fx.tcx.sess.span_fatal(span, &format!("unsupported intrinsic {}", intrinsic));
354 likely | unlikely, (c a) {
355 ret.write_cvalue(fx, a);
358 fx.bcx.ins().debugtrap();
360 copy | copy_nonoverlapping, (v src, v dst, v count) {
361 let elem_ty = substs.type_at(0);
362 let elem_size: u64 = fx.layout_of(elem_ty).size.bytes();
363 assert_eq!(args.len(), 3);
364 let byte_amount = if elem_size != 1 {
365 fx.bcx.ins().imul_imm(count, elem_size as i64)
370 if intrinsic == sym::copy_nonoverlapping {
371 // FIXME emit_small_memcpy
372 fx.bcx.call_memcpy(fx.target_config, dst, src, byte_amount);
374 // FIXME emit_small_memmove
375 fx.bcx.call_memmove(fx.target_config, dst, src, byte_amount);
378 // NOTE: the volatile variants have src and dst swapped
379 volatile_copy_memory | volatile_copy_nonoverlapping_memory, (v dst, v src, v count) {
380 let elem_ty = substs.type_at(0);
381 let elem_size: u64 = fx.layout_of(elem_ty).size.bytes();
382 assert_eq!(args.len(), 3);
383 let byte_amount = if elem_size != 1 {
384 fx.bcx.ins().imul_imm(count, elem_size as i64)
389 // FIXME make the copy actually volatile when using emit_small_mem{cpy,move}
390 if intrinsic == sym::volatile_copy_nonoverlapping_memory {
391 // FIXME emit_small_memcpy
392 fx.bcx.call_memcpy(fx.target_config, dst, src, byte_amount);
394 // FIXME emit_small_memmove
395 fx.bcx.call_memmove(fx.target_config, dst, src, byte_amount);
398 size_of_val, (c ptr) {
399 let layout = fx.layout_of(substs.type_at(0));
400 let size = if layout.is_unsized() {
401 let (_ptr, info) = ptr.load_scalar_pair(fx);
402 let (size, _align) = crate::unsize::size_and_align_of_dst(fx, layout, info);
408 .iconst(fx.pointer_type, layout.size.bytes() as i64)
410 ret.write_cvalue(fx, CValue::by_val(size, usize_layout));
412 min_align_of_val, (c ptr) {
413 let layout = fx.layout_of(substs.type_at(0));
414 let align = if layout.is_unsized() {
415 let (_ptr, info) = ptr.load_scalar_pair(fx);
416 let (_size, align) = crate::unsize::size_and_align_of_dst(fx, layout, info);
422 .iconst(fx.pointer_type, layout.align.abi.bytes() as i64)
424 ret.write_cvalue(fx, CValue::by_val(align, usize_layout));
427 unchecked_add | unchecked_sub | unchecked_mul | unchecked_div | exact_div | unchecked_rem
428 | unchecked_shl | unchecked_shr, (c x, c y) {
429 // FIXME trap on overflow
430 let bin_op = match intrinsic {
431 sym::unchecked_add => BinOp::Add,
432 sym::unchecked_sub => BinOp::Sub,
433 sym::unchecked_mul => BinOp::Mul,
434 sym::unchecked_div | sym::exact_div => BinOp::Div,
435 sym::unchecked_rem => BinOp::Rem,
436 sym::unchecked_shl => BinOp::Shl,
437 sym::unchecked_shr => BinOp::Shr,
440 let res = crate::num::codegen_int_binop(fx, bin_op, x, y);
441 ret.write_cvalue(fx, res);
443 add_with_overflow | sub_with_overflow | mul_with_overflow, (c x, c y) {
444 assert_eq!(x.layout().ty, y.layout().ty);
445 let bin_op = match intrinsic {
446 sym::add_with_overflow => BinOp::Add,
447 sym::sub_with_overflow => BinOp::Sub,
448 sym::mul_with_overflow => BinOp::Mul,
452 let res = crate::num::codegen_checked_int_binop(
458 ret.write_cvalue(fx, res);
460 saturating_add | saturating_sub, (c lhs, c rhs) {
461 assert_eq!(lhs.layout().ty, rhs.layout().ty);
462 let bin_op = match intrinsic {
463 sym::saturating_add => BinOp::Add,
464 sym::saturating_sub => BinOp::Sub,
468 let signed = type_sign(lhs.layout().ty);
470 let checked_res = crate::num::codegen_checked_int_binop(
477 let (val, has_overflow) = checked_res.load_scalar_pair(fx);
478 let clif_ty = fx.clif_type(lhs.layout().ty).unwrap();
480 let (min, max) = type_min_max_value(&mut fx.bcx, clif_ty, signed);
482 let val = match (intrinsic, signed) {
483 (sym::saturating_add, false) => fx.bcx.ins().select(has_overflow, max, val),
484 (sym::saturating_sub, false) => fx.bcx.ins().select(has_overflow, min, val),
485 (sym::saturating_add, true) => {
486 let rhs = rhs.load_scalar(fx);
487 let rhs_ge_zero = fx.bcx.ins().icmp_imm(IntCC::SignedGreaterThanOrEqual, rhs, 0);
488 let sat_val = fx.bcx.ins().select(rhs_ge_zero, max, min);
489 fx.bcx.ins().select(has_overflow, sat_val, val)
491 (sym::saturating_sub, true) => {
492 let rhs = rhs.load_scalar(fx);
493 let rhs_ge_zero = fx.bcx.ins().icmp_imm(IntCC::SignedGreaterThanOrEqual, rhs, 0);
494 let sat_val = fx.bcx.ins().select(rhs_ge_zero, min, max);
495 fx.bcx.ins().select(has_overflow, sat_val, val)
500 let res = CValue::by_val(val, lhs.layout());
502 ret.write_cvalue(fx, res);
504 rotate_left, (c x, v y) {
505 let layout = x.layout();
506 let x = x.load_scalar(fx);
507 let res = fx.bcx.ins().rotl(x, y);
508 ret.write_cvalue(fx, CValue::by_val(res, layout));
510 rotate_right, (c x, v y) {
511 let layout = x.layout();
512 let x = x.load_scalar(fx);
513 let res = fx.bcx.ins().rotr(x, y);
514 ret.write_cvalue(fx, CValue::by_val(res, layout));
517 // The only difference between offset and arith_offset is regarding UB. Because Cranelift
518 // doesn't have UB both are codegen'ed the same way
519 offset | arith_offset, (c base, v offset) {
520 let pointee_ty = base.layout().ty.builtin_deref(true).unwrap().ty;
521 let pointee_size = fx.layout_of(pointee_ty).size.bytes();
522 let ptr_diff = if pointee_size != 1 {
523 fx.bcx.ins().imul_imm(offset, pointee_size as i64)
527 let base_val = base.load_scalar(fx);
528 let res = fx.bcx.ins().iadd(base_val, ptr_diff);
529 ret.write_cvalue(fx, CValue::by_val(res, base.layout()));
532 transmute, (c from) {
533 ret.write_cvalue_transmute(fx, from);
535 write_bytes | volatile_set_memory, (c dst, v val, v count) {
536 let pointee_ty = dst.layout().ty.builtin_deref(true).unwrap().ty;
537 let pointee_size = fx.layout_of(pointee_ty).size.bytes();
538 let count = if pointee_size != 1 {
539 fx.bcx.ins().imul_imm(count, pointee_size as i64)
543 let dst_ptr = dst.load_scalar(fx);
544 // FIXME make the memset actually volatile when switching to emit_small_memset
545 // FIXME use emit_small_memset
546 fx.bcx.call_memset(fx.target_config, dst_ptr, val, count);
548 ctlz | ctlz_nonzero, (c arg) {
549 let val = arg.load_scalar(fx);
550 // FIXME trap on `ctlz_nonzero` with zero arg.
551 let res = fx.bcx.ins().clz(val);
552 let res = CValue::by_val(res, arg.layout());
553 ret.write_cvalue(fx, res);
555 cttz | cttz_nonzero, (c arg) {
556 let val = arg.load_scalar(fx);
557 // FIXME trap on `cttz_nonzero` with zero arg.
558 let res = fx.bcx.ins().ctz(val);
559 let res = CValue::by_val(res, arg.layout());
560 ret.write_cvalue(fx, res);
563 let val = arg.load_scalar(fx);
564 let res = fx.bcx.ins().popcnt(val);
565 let res = CValue::by_val(res, arg.layout());
566 ret.write_cvalue(fx, res);
568 bitreverse, (c arg) {
569 let val = arg.load_scalar(fx);
570 let res = fx.bcx.ins().bitrev(val);
571 let res = CValue::by_val(res, arg.layout());
572 ret.write_cvalue(fx, res);
575 // FIXME(CraneStation/cranelift#794) add bswap instruction to cranelift
576 fn swap(bcx: &mut FunctionBuilder<'_>, v: Value) -> Value {
577 match bcx.func.dfg.value_type(v) {
580 // https://code.woboq.org/gcc/include/bits/byteswap.h.html
582 let tmp1 = bcx.ins().ishl_imm(v, 8);
583 let n1 = bcx.ins().band_imm(tmp1, 0xFF00);
585 let tmp2 = bcx.ins().ushr_imm(v, 8);
586 let n2 = bcx.ins().band_imm(tmp2, 0x00FF);
588 bcx.ins().bor(n1, n2)
591 let tmp1 = bcx.ins().ishl_imm(v, 24);
592 let n1 = bcx.ins().band_imm(tmp1, 0xFF00_0000);
594 let tmp2 = bcx.ins().ishl_imm(v, 8);
595 let n2 = bcx.ins().band_imm(tmp2, 0x00FF_0000);
597 let tmp3 = bcx.ins().ushr_imm(v, 8);
598 let n3 = bcx.ins().band_imm(tmp3, 0x0000_FF00);
600 let tmp4 = bcx.ins().ushr_imm(v, 24);
601 let n4 = bcx.ins().band_imm(tmp4, 0x0000_00FF);
603 let or_tmp1 = bcx.ins().bor(n1, n2);
604 let or_tmp2 = bcx.ins().bor(n3, n4);
605 bcx.ins().bor(or_tmp1, or_tmp2)
608 let tmp1 = bcx.ins().ishl_imm(v, 56);
609 let n1 = bcx.ins().band_imm(tmp1, 0xFF00_0000_0000_0000u64 as i64);
611 let tmp2 = bcx.ins().ishl_imm(v, 40);
612 let n2 = bcx.ins().band_imm(tmp2, 0x00FF_0000_0000_0000u64 as i64);
614 let tmp3 = bcx.ins().ishl_imm(v, 24);
615 let n3 = bcx.ins().band_imm(tmp3, 0x0000_FF00_0000_0000u64 as i64);
617 let tmp4 = bcx.ins().ishl_imm(v, 8);
618 let n4 = bcx.ins().band_imm(tmp4, 0x0000_00FF_0000_0000u64 as i64);
620 let tmp5 = bcx.ins().ushr_imm(v, 8);
621 let n5 = bcx.ins().band_imm(tmp5, 0x0000_0000_FF00_0000u64 as i64);
623 let tmp6 = bcx.ins().ushr_imm(v, 24);
624 let n6 = bcx.ins().band_imm(tmp6, 0x0000_0000_00FF_0000u64 as i64);
626 let tmp7 = bcx.ins().ushr_imm(v, 40);
627 let n7 = bcx.ins().band_imm(tmp7, 0x0000_0000_0000_FF00u64 as i64);
629 let tmp8 = bcx.ins().ushr_imm(v, 56);
630 let n8 = bcx.ins().band_imm(tmp8, 0x0000_0000_0000_00FFu64 as i64);
632 let or_tmp1 = bcx.ins().bor(n1, n2);
633 let or_tmp2 = bcx.ins().bor(n3, n4);
634 let or_tmp3 = bcx.ins().bor(n5, n6);
635 let or_tmp4 = bcx.ins().bor(n7, n8);
637 let or_tmp5 = bcx.ins().bor(or_tmp1, or_tmp2);
638 let or_tmp6 = bcx.ins().bor(or_tmp3, or_tmp4);
639 bcx.ins().bor(or_tmp5, or_tmp6)
642 let (lo, hi) = bcx.ins().isplit(v);
643 let lo = swap(bcx, lo);
644 let hi = swap(bcx, hi);
645 bcx.ins().iconcat(hi, lo)
647 ty => unreachable!("bswap {}", ty),
650 let val = arg.load_scalar(fx);
651 let res = CValue::by_val(swap(&mut fx.bcx, val), arg.layout());
652 ret.write_cvalue(fx, res);
654 assert_inhabited | assert_zero_valid | assert_uninit_valid, () {
655 let layout = fx.layout_of(substs.type_at(0));
656 if layout.abi.is_uninhabited() {
657 with_no_trimmed_paths!({
658 crate::base::codegen_panic(
660 &format!("attempted to instantiate uninhabited type `{}`", layout.ty),
667 if intrinsic == sym::assert_zero_valid && !layout.might_permit_raw_init(fx, /*zero:*/ true) {
668 with_no_trimmed_paths!({
669 crate::base::codegen_panic(
671 &format!("attempted to zero-initialize type `{}`, which is invalid", layout.ty),
678 if intrinsic == sym::assert_uninit_valid && !layout.might_permit_raw_init(fx, /*zero:*/ false) {
679 with_no_trimmed_paths!({
680 crate::base::codegen_panic(
682 &format!("attempted to leave type `{}` uninitialized, which is invalid", layout.ty),
690 volatile_load | unaligned_volatile_load, (c ptr) {
691 // Cranelift treats loads as volatile by default
692 // FIXME correctly handle unaligned_volatile_load
694 fx.layout_of(ptr.layout().ty.builtin_deref(true).unwrap().ty);
695 let val = CValue::by_ref(Pointer::new(ptr.load_scalar(fx)), inner_layout);
696 ret.write_cvalue(fx, val);
698 volatile_store | unaligned_volatile_store, (v ptr, c val) {
699 // Cranelift treats stores as volatile by default
700 // FIXME correctly handle unaligned_volatile_store
701 let dest = CPlace::for_ptr(Pointer::new(ptr), val.layout());
702 dest.write_cvalue(fx, val);
705 pref_align_of | needs_drop | type_id | type_name | variant_count, () {
707 fx.tcx.const_eval_instance(ParamEnv::reveal_all(), instance, None).unwrap();
708 let val = crate::constant::codegen_const_value(
713 ret.write_cvalue(fx, val);
716 ptr_offset_from, (v ptr, v base) {
717 let ty = substs.type_at(0);
718 let isize_layout = fx.layout_of(fx.tcx.types.isize);
720 let pointee_size: u64 = fx.layout_of(ty).size.bytes();
721 let diff = fx.bcx.ins().isub(ptr, base);
722 // FIXME this can be an exact division.
723 let val = CValue::by_val(fx.bcx.ins().sdiv_imm(diff, pointee_size as i64), isize_layout);
724 ret.write_cvalue(fx, val);
727 ptr_guaranteed_eq, (c a, c b) {
728 let val = crate::num::codegen_ptr_binop(fx, BinOp::Eq, a, b);
729 ret.write_cvalue(fx, val);
732 ptr_guaranteed_ne, (c a, c b) {
733 let val = crate::num::codegen_ptr_binop(fx, BinOp::Ne, a, b);
734 ret.write_cvalue(fx, val);
737 caller_location, () {
738 let caller_location = fx.get_caller_location(span);
739 ret.write_cvalue(fx, caller_location);
742 _ if intrinsic.as_str().starts_with("atomic_fence"), () {
743 fx.bcx.ins().fence();
745 _ if intrinsic.as_str().starts_with("atomic_singlethreadfence"), () {
746 // FIXME use a compiler fence once Cranelift supports it
747 fx.bcx.ins().fence();
749 _ if intrinsic.as_str().starts_with("atomic_load"), (v ptr) {
750 let ty = substs.type_at(0);
752 ty::Uint(UintTy::U128) | ty::Int(IntTy::I128) => {
753 // FIXME implement 128bit atomics
754 if fx.tcx.is_compiler_builtins(LOCAL_CRATE) {
755 // special case for compiler-builtins to avoid having to patch it
756 crate::trap::trap_unimplemented(fx, "128bit atomics not yet supported");
757 let ret_block = fx.get_block(destination.unwrap().1);
758 fx.bcx.ins().jump(ret_block, &[]);
761 fx.tcx.sess.span_fatal(span, "128bit atomics not yet supported");
764 ty::Uint(_) | ty::Int(_) | ty::RawPtr(..) => {}
766 report_atomic_type_validation_error(fx, intrinsic, span, ty);
770 let clif_ty = fx.clif_type(ty).unwrap();
772 let val = fx.bcx.ins().atomic_load(clif_ty, MemFlags::trusted(), ptr);
774 let val = CValue::by_val(val, fx.layout_of(ty));
775 ret.write_cvalue(fx, val);
777 _ if intrinsic.as_str().starts_with("atomic_store"), (v ptr, c val) {
778 let ty = substs.type_at(0);
780 ty::Uint(UintTy::U128) | ty::Int(IntTy::I128) => {
781 // FIXME implement 128bit atomics
782 if fx.tcx.is_compiler_builtins(LOCAL_CRATE) {
783 // special case for compiler-builtins to avoid having to patch it
784 crate::trap::trap_unimplemented(fx, "128bit atomics not yet supported");
785 let ret_block = fx.get_block(destination.unwrap().1);
786 fx.bcx.ins().jump(ret_block, &[]);
789 fx.tcx.sess.span_fatal(span, "128bit atomics not yet supported");
792 ty::Uint(_) | ty::Int(_) | ty::RawPtr(..) => {}
794 report_atomic_type_validation_error(fx, intrinsic, span, ty);
799 let val = val.load_scalar(fx);
801 fx.bcx.ins().atomic_store(MemFlags::trusted(), val, ptr);
803 _ if intrinsic.as_str().starts_with("atomic_xchg"), (v ptr, c new) {
804 let layout = new.layout();
805 match layout.ty.kind() {
806 ty::Uint(_) | ty::Int(_) | ty::RawPtr(..) => {}
808 report_atomic_type_validation_error(fx, intrinsic, span, layout.ty);
812 let ty = fx.clif_type(layout.ty).unwrap();
814 let new = new.load_scalar(fx);
816 let old = fx.bcx.ins().atomic_rmw(ty, MemFlags::trusted(), AtomicRmwOp::Xchg, ptr, new);
818 let old = CValue::by_val(old, layout);
819 ret.write_cvalue(fx, old);
821 _ if intrinsic.as_str().starts_with("atomic_cxchg"), (v ptr, c test_old, c new) { // both atomic_cxchg_* and atomic_cxchgweak_*
822 let layout = new.layout();
823 match layout.ty.kind() {
824 ty::Uint(_) | ty::Int(_) | ty::RawPtr(..) => {}
826 report_atomic_type_validation_error(fx, intrinsic, span, layout.ty);
831 let test_old = test_old.load_scalar(fx);
832 let new = new.load_scalar(fx);
834 let old = fx.bcx.ins().atomic_cas(MemFlags::trusted(), ptr, test_old, new);
835 let is_eq = fx.bcx.ins().icmp(IntCC::Equal, old, test_old);
837 let ret_val = CValue::by_val_pair(old, fx.bcx.ins().bint(types::I8, is_eq), ret.layout());
838 ret.write_cvalue(fx, ret_val)
841 _ if intrinsic.as_str().starts_with("atomic_xadd"), (v ptr, c amount) {
842 let layout = amount.layout();
843 match layout.ty.kind() {
844 ty::Uint(_) | ty::Int(_) | ty::RawPtr(..) => {}
846 report_atomic_type_validation_error(fx, intrinsic, span, layout.ty);
850 let ty = fx.clif_type(layout.ty).unwrap();
852 let amount = amount.load_scalar(fx);
854 let old = fx.bcx.ins().atomic_rmw(ty, MemFlags::trusted(), AtomicRmwOp::Add, ptr, amount);
856 let old = CValue::by_val(old, layout);
857 ret.write_cvalue(fx, old);
859 _ if intrinsic.as_str().starts_with("atomic_xsub"), (v ptr, c amount) {
860 let layout = amount.layout();
861 match layout.ty.kind() {
862 ty::Uint(_) | ty::Int(_) | ty::RawPtr(..) => {}
864 report_atomic_type_validation_error(fx, intrinsic, span, layout.ty);
868 let ty = fx.clif_type(layout.ty).unwrap();
870 let amount = amount.load_scalar(fx);
872 let old = fx.bcx.ins().atomic_rmw(ty, MemFlags::trusted(), AtomicRmwOp::Sub, ptr, amount);
874 let old = CValue::by_val(old, layout);
875 ret.write_cvalue(fx, old);
877 _ if intrinsic.as_str().starts_with("atomic_and"), (v ptr, c src) {
878 let layout = src.layout();
879 match layout.ty.kind() {
880 ty::Uint(_) | ty::Int(_) | ty::RawPtr(..) => {}
882 report_atomic_type_validation_error(fx, intrinsic, span, layout.ty);
886 let ty = fx.clif_type(layout.ty).unwrap();
888 let src = src.load_scalar(fx);
890 let old = fx.bcx.ins().atomic_rmw(ty, MemFlags::trusted(), AtomicRmwOp::And, ptr, src);
892 let old = CValue::by_val(old, layout);
893 ret.write_cvalue(fx, old);
895 _ if intrinsic.as_str().starts_with("atomic_or"), (v ptr, c src) {
896 let layout = src.layout();
897 match layout.ty.kind() {
898 ty::Uint(_) | ty::Int(_) | ty::RawPtr(..) => {}
900 report_atomic_type_validation_error(fx, intrinsic, span, layout.ty);
904 let ty = fx.clif_type(layout.ty).unwrap();
906 let src = src.load_scalar(fx);
908 let old = fx.bcx.ins().atomic_rmw(ty, MemFlags::trusted(), AtomicRmwOp::Or, ptr, src);
910 let old = CValue::by_val(old, layout);
911 ret.write_cvalue(fx, old);
913 _ if intrinsic.as_str().starts_with("atomic_xor"), (v ptr, c src) {
914 let layout = src.layout();
915 match layout.ty.kind() {
916 ty::Uint(_) | ty::Int(_) | ty::RawPtr(..) => {}
918 report_atomic_type_validation_error(fx, intrinsic, span, layout.ty);
922 let ty = fx.clif_type(layout.ty).unwrap();
924 let src = src.load_scalar(fx);
926 let old = fx.bcx.ins().atomic_rmw(ty, MemFlags::trusted(), AtomicRmwOp::Xor, ptr, src);
928 let old = CValue::by_val(old, layout);
929 ret.write_cvalue(fx, old);
931 _ if intrinsic.as_str().starts_with("atomic_nand"), (v ptr, c src) {
932 let layout = src.layout();
933 match layout.ty.kind() {
934 ty::Uint(_) | ty::Int(_) | ty::RawPtr(..) => {}
936 report_atomic_type_validation_error(fx, intrinsic, span, layout.ty);
940 let ty = fx.clif_type(layout.ty).unwrap();
942 let src = src.load_scalar(fx);
944 let old = fx.bcx.ins().atomic_rmw(ty, MemFlags::trusted(), AtomicRmwOp::Nand, ptr, src);
946 let old = CValue::by_val(old, layout);
947 ret.write_cvalue(fx, old);
949 _ if intrinsic.as_str().starts_with("atomic_max"), (v ptr, c src) {
950 let layout = src.layout();
951 match layout.ty.kind() {
952 ty::Uint(_) | ty::Int(_) | ty::RawPtr(..) => {}
954 report_atomic_type_validation_error(fx, intrinsic, span, layout.ty);
958 let ty = fx.clif_type(layout.ty).unwrap();
960 let src = src.load_scalar(fx);
962 let old = fx.bcx.ins().atomic_rmw(ty, MemFlags::trusted(), AtomicRmwOp::Smax, ptr, src);
964 let old = CValue::by_val(old, layout);
965 ret.write_cvalue(fx, old);
967 _ if intrinsic.as_str().starts_with("atomic_umax"), (v ptr, c src) {
968 let layout = src.layout();
969 match layout.ty.kind() {
970 ty::Uint(_) | ty::Int(_) | ty::RawPtr(..) => {}
972 report_atomic_type_validation_error(fx, intrinsic, span, layout.ty);
976 let ty = fx.clif_type(layout.ty).unwrap();
978 let src = src.load_scalar(fx);
980 let old = fx.bcx.ins().atomic_rmw(ty, MemFlags::trusted(), AtomicRmwOp::Umax, ptr, src);
982 let old = CValue::by_val(old, layout);
983 ret.write_cvalue(fx, old);
985 _ if intrinsic.as_str().starts_with("atomic_min"), (v ptr, c src) {
986 let layout = src.layout();
987 match layout.ty.kind() {
988 ty::Uint(_) | ty::Int(_) | ty::RawPtr(..) => {}
990 report_atomic_type_validation_error(fx, intrinsic, span, layout.ty);
994 let ty = fx.clif_type(layout.ty).unwrap();
996 let src = src.load_scalar(fx);
998 let old = fx.bcx.ins().atomic_rmw(ty, MemFlags::trusted(), AtomicRmwOp::Smin, ptr, src);
1000 let old = CValue::by_val(old, layout);
1001 ret.write_cvalue(fx, old);
1003 _ if intrinsic.as_str().starts_with("atomic_umin"), (v ptr, c src) {
1004 let layout = src.layout();
1005 match layout.ty.kind() {
1006 ty::Uint(_) | ty::Int(_) | ty::RawPtr(..) => {}
1008 report_atomic_type_validation_error(fx, intrinsic, span, layout.ty);
1012 let ty = fx.clif_type(layout.ty).unwrap();
1014 let src = src.load_scalar(fx);
1016 let old = fx.bcx.ins().atomic_rmw(ty, MemFlags::trusted(), AtomicRmwOp::Umin, ptr, src);
1018 let old = CValue::by_val(old, layout);
1019 ret.write_cvalue(fx, old);
1022 // In Rust floating point min and max don't propagate NaN. In Cranelift they do however.
1023 // For this reason it is necessary to use `a.is_nan() ? b : (a >= b ? b : a)` for `minnumf*`
1024 // and `a.is_nan() ? b : (a <= b ? b : a)` for `maxnumf*`. NaN checks are done by comparing
1025 // a float against itself. Only in case of NaN is it not equal to itself.
1026 minnumf32, (v a, v b) {
1027 let a_is_nan = fx.bcx.ins().fcmp(FloatCC::NotEqual, a, a);
1028 let a_ge_b = fx.bcx.ins().fcmp(FloatCC::GreaterThanOrEqual, a, b);
1029 let temp = fx.bcx.ins().select(a_ge_b, b, a);
1030 let val = fx.bcx.ins().select(a_is_nan, b, temp);
1031 let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f32));
1032 ret.write_cvalue(fx, val);
1034 minnumf64, (v a, v b) {
1035 let a_is_nan = fx.bcx.ins().fcmp(FloatCC::NotEqual, a, a);
1036 let a_ge_b = fx.bcx.ins().fcmp(FloatCC::GreaterThanOrEqual, a, b);
1037 let temp = fx.bcx.ins().select(a_ge_b, b, a);
1038 let val = fx.bcx.ins().select(a_is_nan, b, temp);
1039 let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f64));
1040 ret.write_cvalue(fx, val);
1042 maxnumf32, (v a, v b) {
1043 let a_is_nan = fx.bcx.ins().fcmp(FloatCC::NotEqual, a, a);
1044 let a_le_b = fx.bcx.ins().fcmp(FloatCC::LessThanOrEqual, a, b);
1045 let temp = fx.bcx.ins().select(a_le_b, b, a);
1046 let val = fx.bcx.ins().select(a_is_nan, b, temp);
1047 let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f32));
1048 ret.write_cvalue(fx, val);
1050 maxnumf64, (v a, v b) {
1051 let a_is_nan = fx.bcx.ins().fcmp(FloatCC::NotEqual, a, a);
1052 let a_le_b = fx.bcx.ins().fcmp(FloatCC::LessThanOrEqual, a, b);
1053 let temp = fx.bcx.ins().select(a_le_b, b, a);
1054 let val = fx.bcx.ins().select(a_is_nan, b, temp);
1055 let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f64));
1056 ret.write_cvalue(fx, val);
1059 kw.Try, (v f, v data, v _catch_fn) {
1060 // FIXME once unwinding is supported, change this to actually catch panics
1061 let f_sig = fx.bcx.func.import_signature(Signature {
1062 call_conv: fx.target_config.default_call_conv,
1063 params: vec![AbiParam::new(fx.bcx.func.dfg.value_type(data))],
1067 fx.bcx.ins().call_indirect(f_sig, f, &[data]);
1069 let layout = ret.layout();
1070 let ret_val = CValue::const_val(fx, layout, ty::ScalarInt::null(layout.size));
1071 ret.write_cvalue(fx, ret_val);
1074 fadd_fast | fsub_fast | fmul_fast | fdiv_fast | frem_fast, (c x, c y) {
1075 let res = crate::num::codegen_float_binop(fx, match intrinsic {
1076 sym::fadd_fast => BinOp::Add,
1077 sym::fsub_fast => BinOp::Sub,
1078 sym::fmul_fast => BinOp::Mul,
1079 sym::fdiv_fast => BinOp::Div,
1080 sym::frem_fast => BinOp::Rem,
1081 _ => unreachable!(),
1083 ret.write_cvalue(fx, res);
1085 float_to_int_unchecked, (v f) {
1086 let res = crate::cast::clif_int_or_float_cast(
1090 fx.clif_type(ret.layout().ty).unwrap(),
1091 type_sign(ret.layout().ty),
1093 ret.write_cvalue(fx, CValue::by_val(res, ret.layout()));
1096 raw_eq, (v lhs_ref, v rhs_ref) {
1097 let size = fx.layout_of(substs.type_at(0)).layout.size();
1098 // FIXME add and use emit_small_memcmp
1100 if size == Size::ZERO {
1101 // No bytes means they're trivially equal
1102 fx.bcx.ins().iconst(types::I8, 1)
1103 } else if let Some(clty) = size.bits().try_into().ok().and_then(Type::int) {
1104 // Can't use `trusted` for these loads; they could be unaligned.
1105 let mut flags = MemFlags::new();
1107 let lhs_val = fx.bcx.ins().load(clty, flags, lhs_ref, 0);
1108 let rhs_val = fx.bcx.ins().load(clty, flags, rhs_ref, 0);
1109 let eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_val, rhs_val);
1110 fx.bcx.ins().bint(types::I8, eq)
1112 // Just call `memcmp` (like slices do in core) when the
1113 // size is too large or it's not a power-of-two.
1114 let signed_bytes = i64::try_from(size.bytes()).unwrap();
1115 let bytes_val = fx.bcx.ins().iconst(fx.pointer_type, signed_bytes);
1116 let params = vec![AbiParam::new(fx.pointer_type); 3];
1117 let returns = vec![AbiParam::new(types::I32)];
1118 let args = &[lhs_ref, rhs_ref, bytes_val];
1119 let cmp = fx.lib_call("memcmp", params, returns, args)[0];
1120 let eq = fx.bcx.ins().icmp_imm(IntCC::Equal, cmp, 0);
1121 fx.bcx.ins().bint(types::I8, eq)
1123 ret.write_cvalue(fx, CValue::by_val(is_eq_value, ret.layout()));
1126 const_allocate, (c _size, c _align) {
1127 // returns a null pointer at runtime.
1128 let null = fx.bcx.ins().iconst(fx.pointer_type, 0);
1129 ret.write_cvalue(fx, CValue::by_val(null, ret.layout()));
1132 const_deallocate, (c _ptr, c _size, c _align) {
1137 // FIXME implement black_box semantics
1138 ret.write_cvalue(fx, a);
1142 let ret_block = fx.get_block(destination.unwrap().1);
1143 fx.bcx.ins().jump(ret_block, &[]);