]> git.lizzy.rs Git - rust.git/blob - src/intrinsics/mod.rs
Implement float_to_int_unchecked intrinsic
[rust.git] / src / intrinsics / mod.rs
1 mod llvm;
2 mod simd;
3
4 pub(crate) use llvm::codegen_llvm_intrinsic_call;
5
6 use crate::prelude::*;
7
8 macro intrinsic_pat {
9     (_) => {
10         _
11     },
12     ($name:ident) => {
13         stringify!($name)
14     },
15     ($name:literal) => {
16         stringify!($name)
17     },
18     ($x:ident . $($xs:tt).*) => {
19         concat!(stringify!($x), ".", intrinsic_pat!($($xs).*))
20     }
21 }
22
23 macro intrinsic_arg {
24     (o $fx:expr, $arg:ident) => {
25         $arg
26     },
27     (c $fx:expr, $arg:ident) => {
28         trans_operand($fx, $arg)
29     },
30     (v $fx:expr, $arg:ident) => {
31         trans_operand($fx, $arg).load_scalar($fx)
32     }
33 }
34
35 macro intrinsic_substs {
36     ($substs:expr, $index:expr,) => {},
37     ($substs:expr, $index:expr, $first:ident $(,$rest:ident)*) => {
38         let $first = $substs.type_at($index);
39         intrinsic_substs!($substs, $index+1, $($rest),*);
40     }
41 }
42
43 macro intrinsic_match {
44     ($fx:expr, $intrinsic:expr, $substs:expr, $args:expr,
45     _ => $unknown:block;
46     $(
47         $($($name:tt).*)|+ $(if $cond:expr)?, $(<$($subst:ident),*>)? ($($a:ident $arg:ident),*) $content:block;
48     )*) => {
49         let _ = $substs; // Silence warning when substs is unused.
50         match $intrinsic {
51             $(
52                 $(intrinsic_pat!($($name).*))|* $(if $cond)? => {
53                     #[allow(unused_parens, non_snake_case)]
54                     {
55                         $(
56                             intrinsic_substs!($substs, 0, $($subst),*);
57                         )?
58                         if let [$($arg),*] = $args {
59                             let ($($arg,)*) = (
60                                 $(intrinsic_arg!($a $fx, $arg),)*
61                             );
62                             #[warn(unused_parens, non_snake_case)]
63                             {
64                                 $content
65                             }
66                         } else {
67                             bug!("wrong number of args for intrinsic {:?}", $intrinsic);
68                         }
69                     }
70                 }
71             )*
72             _ => $unknown,
73         }
74     }
75 }
76
77 macro call_intrinsic_match {
78     ($fx:expr, $intrinsic:expr, $substs:expr, $ret:expr, $destination:expr, $args:expr, $(
79         $name:ident($($arg:ident),*) -> $ty:ident => $func:ident,
80     )*) => {
81         match $intrinsic {
82             $(
83                 stringify!($name) => {
84                     assert!($substs.is_noop());
85                     if let [$(ref $arg),*] = *$args {
86                         let ($($arg,)*) = (
87                             $(trans_operand($fx, $arg),)*
88                         );
89                         let res = $fx.easy_call(stringify!($func), &[$($arg),*], $fx.tcx.types.$ty);
90                         $ret.write_cvalue($fx, res);
91
92                         if let Some((_, dest)) = $destination {
93                             let ret_block = $fx.get_block(dest);
94                             $fx.bcx.ins().jump(ret_block, &[]);
95                             return;
96                         } else {
97                             unreachable!();
98                         }
99                     } else {
100                         bug!("wrong number of args for intrinsic {:?}", $intrinsic);
101                     }
102                 }
103             )*
104             _ => {}
105         }
106     }
107 }
108
109 macro atomic_binop_return_old($fx:expr, $op:ident<$T:ident>($ptr:ident, $src:ident) -> $ret:ident)  {
110     crate::atomic_shim::lock_global_lock($fx);
111
112     let clif_ty = $fx.clif_type($T).unwrap();
113     let old = $fx.bcx.ins().load(clif_ty, MemFlags::new(), $ptr, 0);
114     let new = $fx.bcx.ins().$op(old, $src);
115     $fx.bcx.ins().store(MemFlags::new(), new, $ptr, 0);
116     $ret.write_cvalue($fx, CValue::by_val(old, $fx.layout_of($T)));
117
118     crate::atomic_shim::unlock_global_lock($fx);
119 }
120
121 macro atomic_minmax($fx:expr, $cc:expr, <$T:ident> ($ptr:ident, $src:ident) -> $ret:ident) {
122     crate::atomic_shim::lock_global_lock($fx);
123
124     // Read old
125     let clif_ty = $fx.clif_type($T).unwrap();
126     let old = $fx.bcx.ins().load(clif_ty, MemFlags::new(), $ptr, 0);
127
128     // Compare
129     let is_eq = $fx.bcx.ins().icmp(IntCC::SignedGreaterThan, old, $src);
130     let new = $fx.bcx.ins().select(is_eq, old, $src);
131
132     // Write new
133     $fx.bcx.ins().store(MemFlags::new(), new, $ptr, 0);
134
135     let ret_val = CValue::by_val(old, $ret.layout());
136     $ret.write_cvalue($fx, ret_val);
137
138     crate::atomic_shim::unlock_global_lock($fx);
139 }
140
141 fn lane_type_and_count<'tcx>(
142     tcx: TyCtxt<'tcx>,
143     layout: TyAndLayout<'tcx>,
144 ) -> (TyAndLayout<'tcx>, u16) {
145     assert!(layout.ty.is_simd());
146     let lane_count = match layout.fields {
147         rustc_target::abi::FieldsShape::Array { stride: _, count } => u16::try_from(count).unwrap(),
148         _ => unreachable!("lane_type_and_count({:?})", layout),
149     };
150     let lane_layout = layout.field(&ty::layout::LayoutCx {
151         tcx,
152         param_env: ParamEnv::reveal_all(),
153     }, 0).unwrap();
154     (lane_layout, lane_count)
155 }
156
157 fn clif_vector_type<'tcx>(tcx: TyCtxt<'tcx>, layout: TyAndLayout<'tcx>) -> Option<Type> {
158     let (element, count) = match &layout.abi {
159         Abi::Vector { element, count } => (element.clone(), *count),
160         _ => unreachable!(),
161     };
162
163     match scalar_to_clif_type(tcx, element).by(u16::try_from(count).unwrap()) {
164         // Cranelift currently only implements icmp for 128bit vectors. While 64bit lanes are
165         // supported, this needs either the `use_sse41_simd` or `use_sse42_simd` target flag
166         // to be enabled.
167         Some(vector_ty) if vector_ty.bits() == 128 && vector_ty.lane_type() != types::I64 => Some(vector_ty),
168         _ => None,
169     }
170 }
171
172 fn simd_for_each_lane<'tcx, B: Backend>(
173     fx: &mut FunctionCx<'_, 'tcx, B>,
174     val: CValue<'tcx>,
175     ret: CPlace<'tcx>,
176     f: impl Fn(
177         &mut FunctionCx<'_, 'tcx, B>,
178         TyAndLayout<'tcx>,
179         TyAndLayout<'tcx>,
180         Value,
181     ) -> CValue<'tcx>,
182 ) {
183     let layout = val.layout();
184
185     let (lane_layout, lane_count) = lane_type_and_count(fx.tcx, layout);
186     let (ret_lane_layout, ret_lane_count) = lane_type_and_count(fx.tcx, ret.layout());
187     assert_eq!(lane_count, ret_lane_count);
188
189     for lane_idx in 0..lane_count {
190         let lane_idx = mir::Field::new(lane_idx.try_into().unwrap());
191         let lane = val.value_field(fx, lane_idx).load_scalar(fx);
192
193         let res_lane = f(fx, lane_layout, ret_lane_layout, lane);
194
195         ret.place_field(fx, lane_idx).write_cvalue(fx, res_lane);
196     }
197 }
198
199 fn simd_pair_for_each_lane<'tcx, B: Backend>(
200     fx: &mut FunctionCx<'_, 'tcx, B>,
201     x: CValue<'tcx>,
202     y: CValue<'tcx>,
203     ret: CPlace<'tcx>,
204     f: impl Fn(
205         &mut FunctionCx<'_, 'tcx, B>,
206         TyAndLayout<'tcx>,
207         TyAndLayout<'tcx>,
208         Value,
209         Value,
210     ) -> CValue<'tcx>,
211 ) {
212     assert_eq!(x.layout(), y.layout());
213     let layout = x.layout();
214
215     let (lane_layout, lane_count) = lane_type_and_count(fx.tcx, layout);
216     let (ret_lane_layout, ret_lane_count) = lane_type_and_count(fx.tcx, ret.layout());
217     assert_eq!(lane_count, ret_lane_count);
218
219     for lane in 0..lane_count {
220         let lane = mir::Field::new(lane.try_into().unwrap());
221         let x_lane = x.value_field(fx, lane).load_scalar(fx);
222         let y_lane = y.value_field(fx, lane).load_scalar(fx);
223
224         let res_lane = f(fx, lane_layout, ret_lane_layout, x_lane, y_lane);
225
226         ret.place_field(fx, lane).write_cvalue(fx, res_lane);
227     }
228 }
229
230 fn bool_to_zero_or_max_uint<'tcx>(
231     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
232     layout: TyAndLayout<'tcx>,
233     val: Value,
234 ) -> CValue<'tcx> {
235     let ty = fx.clif_type(layout.ty).unwrap();
236
237     let int_ty = match ty {
238         types::F32 => types::I32,
239         types::F64 => types::I64,
240         ty => ty,
241     };
242
243     let val = fx.bcx.ins().bint(int_ty, val);
244     let mut res = fx.bcx.ins().ineg(val);
245
246     if ty.is_float() {
247         res = fx.bcx.ins().bitcast(ty, res);
248     }
249
250     CValue::by_val(res, layout)
251 }
252
253 macro simd_cmp {
254     ($fx:expr, $cc:ident($x:ident, $y:ident) -> $ret:ident) => {
255         let vector_ty = clif_vector_type($fx.tcx, $x.layout());
256
257         if let Some(vector_ty) = vector_ty {
258             let x = $x.load_scalar($fx);
259             let y = $y.load_scalar($fx);
260             let val = $fx.bcx.ins().icmp(IntCC::$cc, x, y);
261
262             // HACK This depends on the fact that icmp for vectors represents bools as 0 and !0, not 0 and 1.
263             let val = $fx.bcx.ins().raw_bitcast(vector_ty, val);
264
265             $ret.write_cvalue($fx, CValue::by_val(val, $ret.layout()));
266         } else {
267             simd_pair_for_each_lane(
268                 $fx,
269                 $x,
270                 $y,
271                 $ret,
272                 |fx, lane_layout, res_lane_layout, x_lane, y_lane| {
273                     let res_lane = match lane_layout.ty.kind {
274                         ty::Uint(_) | ty::Int(_) => fx.bcx.ins().icmp(IntCC::$cc, x_lane, y_lane),
275                         _ => unreachable!("{:?}", lane_layout.ty),
276                     };
277                     bool_to_zero_or_max_uint(fx, res_lane_layout, res_lane)
278                 },
279             );
280         }
281     },
282     ($fx:expr, $cc_u:ident|$cc_s:ident($x:ident, $y:ident) -> $ret:ident) => {
283         // FIXME use vector icmp when possible
284         simd_pair_for_each_lane(
285             $fx,
286             $x,
287             $y,
288             $ret,
289             |fx, lane_layout, res_lane_layout, x_lane, y_lane| {
290                 let res_lane = match lane_layout.ty.kind {
291                     ty::Uint(_) => fx.bcx.ins().icmp(IntCC::$cc_u, x_lane, y_lane),
292                     ty::Int(_) => fx.bcx.ins().icmp(IntCC::$cc_s, x_lane, y_lane),
293                     _ => unreachable!("{:?}", lane_layout.ty),
294                 };
295                 bool_to_zero_or_max_uint(fx, res_lane_layout, res_lane)
296             },
297         );
298     },
299 }
300
301 macro simd_int_binop {
302     ($fx:expr, $op:ident($x:ident, $y:ident) -> $ret:ident) => {
303         simd_int_binop!($fx, $op|$op($x, $y) -> $ret);
304     },
305     ($fx:expr, $op_u:ident|$op_s:ident($x:ident, $y:ident) -> $ret:ident) => {
306         simd_pair_for_each_lane(
307             $fx,
308             $x,
309             $y,
310             $ret,
311             |fx, lane_layout, ret_lane_layout, x_lane, y_lane| {
312                 let res_lane = match lane_layout.ty.kind {
313                     ty::Uint(_) => fx.bcx.ins().$op_u(x_lane, y_lane),
314                     ty::Int(_) => fx.bcx.ins().$op_s(x_lane, y_lane),
315                     _ => unreachable!("{:?}", lane_layout.ty),
316                 };
317                 CValue::by_val(res_lane, ret_lane_layout)
318             },
319         );
320     },
321 }
322
323 macro simd_int_flt_binop {
324     ($fx:expr, $op:ident|$op_f:ident($x:ident, $y:ident) -> $ret:ident) => {
325         simd_int_flt_binop!($fx, $op|$op|$op_f($x, $y) -> $ret);
326     },
327     ($fx:expr, $op_u:ident|$op_s:ident|$op_f:ident($x:ident, $y:ident) -> $ret:ident) => {
328         simd_pair_for_each_lane(
329             $fx,
330             $x,
331             $y,
332             $ret,
333             |fx, lane_layout, ret_lane_layout, x_lane, y_lane| {
334                 let res_lane = match lane_layout.ty.kind {
335                     ty::Uint(_) => fx.bcx.ins().$op_u(x_lane, y_lane),
336                     ty::Int(_) => fx.bcx.ins().$op_s(x_lane, y_lane),
337                     ty::Float(_) => fx.bcx.ins().$op_f(x_lane, y_lane),
338                     _ => unreachable!("{:?}", lane_layout.ty),
339                 };
340                 CValue::by_val(res_lane, ret_lane_layout)
341             },
342         );
343     },
344 }
345
346 macro simd_flt_binop($fx:expr, $op:ident($x:ident, $y:ident) -> $ret:ident) {
347     simd_pair_for_each_lane(
348         $fx,
349         $x,
350         $y,
351         $ret,
352         |fx, lane_layout, ret_lane_layout, x_lane, y_lane| {
353             let res_lane = match lane_layout.ty.kind {
354                 ty::Float(_) => fx.bcx.ins().$op(x_lane, y_lane),
355                 _ => unreachable!("{:?}", lane_layout.ty),
356             };
357             CValue::by_val(res_lane, ret_lane_layout)
358         },
359     );
360 }
361
362 pub(crate) fn codegen_intrinsic_call<'tcx>(
363     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
364     instance: Instance<'tcx>,
365     args: &[mir::Operand<'tcx>],
366     destination: Option<(CPlace<'tcx>, BasicBlock)>,
367     span: Span,
368 ) {
369     let def_id = instance.def_id();
370     let substs = instance.substs;
371
372     let intrinsic = fx.tcx.item_name(def_id).as_str();
373     let intrinsic = &intrinsic[..];
374
375     let ret = match destination {
376         Some((place, _)) => place,
377         None => {
378             // Insert non returning intrinsics here
379             match intrinsic {
380                 "abort" => {
381                     trap_panic(fx, "Called intrinsic::abort.");
382                 }
383                 "unreachable" => {
384                     trap_unreachable(fx, "[corruption] Called intrinsic::unreachable.");
385                 }
386                 "transmute" => {
387                     trap_unreachable(
388                         fx,
389                         "[corruption] Transmuting to uninhabited type.",
390                     );
391                 }
392                 _ => unimplemented!("unsupported instrinsic {}", intrinsic),
393             }
394             return;
395         }
396     };
397
398     if intrinsic.starts_with("simd_") {
399         self::simd::codegen_simd_intrinsic_call(fx, instance, args, ret, span);
400         let ret_block = fx.get_block(destination.expect("SIMD intrinsics don't diverge").1);
401         fx.bcx.ins().jump(ret_block, &[]);
402         return;
403     }
404
405     let usize_layout = fx.layout_of(fx.tcx.types.usize);
406
407     call_intrinsic_match! {
408         fx, intrinsic, substs, ret, destination, args,
409         expf32(flt) -> f32 => expf,
410         expf64(flt) -> f64 => exp,
411         exp2f32(flt) -> f32 => exp2f,
412         exp2f64(flt) -> f64 => exp2,
413         sqrtf32(flt) -> f32 => sqrtf,
414         sqrtf64(flt) -> f64 => sqrt,
415         powif32(a, x) -> f32 => __powisf2, // compiler-builtins
416         powif64(a, x) -> f64 => __powidf2, // compiler-builtins
417         powf32(a, x) -> f32 => powf,
418         powf64(a, x) -> f64 => pow,
419         logf32(flt) -> f32 => logf,
420         logf64(flt) -> f64 => log,
421         log2f32(flt) -> f32 => log2f,
422         log2f64(flt) -> f64 => log2,
423         log10f32(flt) -> f32 => log10f,
424         log10f64(flt) -> f64 => log10,
425         fabsf32(flt) -> f32 => fabsf,
426         fabsf64(flt) -> f64 => fabs,
427         fmaf32(x, y, z) -> f32 => fmaf,
428         fmaf64(x, y, z) -> f64 => fma,
429         copysignf32(x, y) -> f32 => copysignf,
430         copysignf64(x, y) -> f64 => copysign,
431
432         // rounding variants
433         // FIXME use clif insts
434         floorf32(flt) -> f32 => floorf,
435         floorf64(flt) -> f64 => floor,
436         ceilf32(flt) -> f32 => ceilf,
437         ceilf64(flt) -> f64 => ceil,
438         truncf32(flt) -> f32 => truncf,
439         truncf64(flt) -> f64 => trunc,
440         roundf32(flt) -> f32 => roundf,
441         roundf64(flt) -> f64 => round,
442
443         // trigonometry
444         sinf32(flt) -> f32 => sinf,
445         sinf64(flt) -> f64 => sin,
446         cosf32(flt) -> f32 => cosf,
447         cosf64(flt) -> f64 => cos,
448         tanf32(flt) -> f32 => tanf,
449         tanf64(flt) -> f64 => tan,
450     }
451
452     intrinsic_match! {
453         fx, intrinsic, substs, args,
454         _ => {
455             fx.tcx.sess.span_fatal(span, &format!("unsupported intrinsic {}", intrinsic));
456         };
457
458         assume, (c _a) {};
459         likely | unlikely, (c a) {
460             ret.write_cvalue(fx, a);
461         };
462         breakpoint, () {
463             fx.bcx.ins().debugtrap();
464         };
465         copy | copy_nonoverlapping, <elem_ty> (v src, v dst, v count) {
466             let elem_size: u64 = fx.layout_of(elem_ty).size.bytes();
467             let elem_size = fx
468                 .bcx
469                 .ins()
470                 .iconst(fx.pointer_type, elem_size as i64);
471             assert_eq!(args.len(), 3);
472             let byte_amount = fx.bcx.ins().imul(count, elem_size);
473
474             if intrinsic.contains("nonoverlapping") {
475                 // FIXME emit_small_memcpy
476                 fx.bcx.call_memcpy(fx.module.target_config(), dst, src, byte_amount);
477             } else {
478                 // FIXME emit_small_memmove
479                 fx.bcx.call_memmove(fx.module.target_config(), dst, src, byte_amount);
480             }
481         };
482         // NOTE: the volatile variants have src and dst swapped
483         volatile_copy_memory | volatile_copy_nonoverlapping_memory, <elem_ty> (v dst, v src, v count) {
484             let elem_size: u64 = fx.layout_of(elem_ty).size.bytes();
485             let elem_size = fx
486                 .bcx
487                 .ins()
488                 .iconst(fx.pointer_type, elem_size as i64);
489             assert_eq!(args.len(), 3);
490             let byte_amount = fx.bcx.ins().imul(count, elem_size);
491
492             // FIXME make the copy actually volatile when using emit_small_mem{cpy,move}
493             if intrinsic.contains("nonoverlapping") {
494                 // FIXME emit_small_memcpy
495                 fx.bcx.call_memcpy(fx.module.target_config(), dst, src, byte_amount);
496             } else {
497                 // FIXME emit_small_memmove
498                 fx.bcx.call_memmove(fx.module.target_config(), dst, src, byte_amount);
499             }
500         };
501         discriminant_value, (c ptr) {
502             let pointee_layout = fx.layout_of(ptr.layout().ty.builtin_deref(true).unwrap().ty);
503             let val = CValue::by_ref(Pointer::new(ptr.load_scalar(fx)), pointee_layout);
504             let discr = crate::discriminant::codegen_get_discriminant(fx, val, ret.layout());
505             ret.write_cvalue(fx, discr);
506         };
507         size_of_val, <T> (c ptr) {
508             let layout = fx.layout_of(T);
509             let size = if layout.is_unsized() {
510                 let (_ptr, info) = ptr.load_scalar_pair(fx);
511                 let (size, _align) = crate::unsize::size_and_align_of_dst(fx, layout, info);
512                 size
513             } else {
514                 fx
515                     .bcx
516                     .ins()
517                     .iconst(fx.pointer_type, layout.size.bytes() as i64)
518             };
519             ret.write_cvalue(fx, CValue::by_val(size, usize_layout));
520         };
521         min_align_of_val, <T> (c ptr) {
522             let layout = fx.layout_of(T);
523             let align = if layout.is_unsized() {
524                 let (_ptr, info) = ptr.load_scalar_pair(fx);
525                 let (_size, align) = crate::unsize::size_and_align_of_dst(fx, layout, info);
526                 align
527             } else {
528                 fx
529                     .bcx
530                     .ins()
531                     .iconst(fx.pointer_type, layout.align.abi.bytes() as i64)
532             };
533             ret.write_cvalue(fx, CValue::by_val(align, usize_layout));
534         };
535
536         _ if intrinsic.starts_with("unchecked_") || intrinsic == "exact_div", (c x, c y) {
537             // FIXME trap on overflow
538             let bin_op = match intrinsic {
539                 "unchecked_add" => BinOp::Add,
540                 "unchecked_sub" => BinOp::Sub,
541                 "unchecked_div" | "exact_div" => BinOp::Div,
542                 "unchecked_rem" => BinOp::Rem,
543                 "unchecked_shl" => BinOp::Shl,
544                 "unchecked_shr" => BinOp::Shr,
545                 _ => unreachable!("intrinsic {}", intrinsic),
546             };
547             let res = crate::num::trans_int_binop(fx, bin_op, x, y);
548             ret.write_cvalue(fx, res);
549         };
550         _ if intrinsic.ends_with("_with_overflow"), (c x, c y) {
551             assert_eq!(x.layout().ty, y.layout().ty);
552             let bin_op = match intrinsic {
553                 "add_with_overflow" => BinOp::Add,
554                 "sub_with_overflow" => BinOp::Sub,
555                 "mul_with_overflow" => BinOp::Mul,
556                 _ => unreachable!("intrinsic {}", intrinsic),
557             };
558
559             let res = crate::num::trans_checked_int_binop(
560                 fx,
561                 bin_op,
562                 x,
563                 y,
564             );
565             ret.write_cvalue(fx, res);
566         };
567         _ if intrinsic.starts_with("wrapping_"), (c x, c y) {
568             assert_eq!(x.layout().ty, y.layout().ty);
569             let bin_op = match intrinsic {
570                 "wrapping_add" => BinOp::Add,
571                 "wrapping_sub" => BinOp::Sub,
572                 "wrapping_mul" => BinOp::Mul,
573                 _ => unreachable!("intrinsic {}", intrinsic),
574             };
575             let res = crate::num::trans_int_binop(
576                 fx,
577                 bin_op,
578                 x,
579                 y,
580             );
581             ret.write_cvalue(fx, res);
582         };
583         _ if intrinsic.starts_with("saturating_"), <T> (c lhs, c rhs) {
584             assert_eq!(lhs.layout().ty, rhs.layout().ty);
585             let bin_op = match intrinsic {
586                 "saturating_add" => BinOp::Add,
587                 "saturating_sub" => BinOp::Sub,
588                 _ => unreachable!("intrinsic {}", intrinsic),
589             };
590
591             let signed = type_sign(T);
592
593             let checked_res = crate::num::trans_checked_int_binop(
594                 fx,
595                 bin_op,
596                 lhs,
597                 rhs,
598             );
599
600             let (val, has_overflow) = checked_res.load_scalar_pair(fx);
601             let clif_ty = fx.clif_type(T).unwrap();
602
603             // `select.i8` is not implemented by Cranelift.
604             let has_overflow = fx.bcx.ins().uextend(types::I32, has_overflow);
605
606             let (min, max) = type_min_max_value(&mut fx.bcx, clif_ty, signed);
607
608             let val = match (intrinsic, signed) {
609                 ("saturating_add", false) => fx.bcx.ins().select(has_overflow, max, val),
610                 ("saturating_sub", false) => fx.bcx.ins().select(has_overflow, min, val),
611                 ("saturating_add", true) => {
612                     let rhs = rhs.load_scalar(fx);
613                     let rhs_ge_zero = fx.bcx.ins().icmp_imm(IntCC::SignedGreaterThanOrEqual, rhs, 0);
614                     let sat_val = fx.bcx.ins().select(rhs_ge_zero, max, min);
615                     fx.bcx.ins().select(has_overflow, sat_val, val)
616                 }
617                 ("saturating_sub", true) => {
618                     let rhs = rhs.load_scalar(fx);
619                     let rhs_ge_zero = fx.bcx.ins().icmp_imm(IntCC::SignedGreaterThanOrEqual, rhs, 0);
620                     let sat_val = fx.bcx.ins().select(rhs_ge_zero, min, max);
621                     fx.bcx.ins().select(has_overflow, sat_val, val)
622                 }
623                 _ => unreachable!(),
624             };
625
626             let res = CValue::by_val(val, fx.layout_of(T));
627
628             ret.write_cvalue(fx, res);
629         };
630         rotate_left, <T>(v x, v y) {
631             let layout = fx.layout_of(T);
632             let res = fx.bcx.ins().rotl(x, y);
633             ret.write_cvalue(fx, CValue::by_val(res, layout));
634         };
635         rotate_right, <T>(v x, v y) {
636             let layout = fx.layout_of(T);
637             let res = fx.bcx.ins().rotr(x, y);
638             ret.write_cvalue(fx, CValue::by_val(res, layout));
639         };
640
641         // The only difference between offset and arith_offset is regarding UB. Because Cranelift
642         // doesn't have UB both are codegen'ed the same way
643         offset | arith_offset, (c base, v offset) {
644             let pointee_ty = base.layout().ty.builtin_deref(true).unwrap().ty;
645             let pointee_size = fx.layout_of(pointee_ty).size.bytes();
646             let ptr_diff = fx.bcx.ins().imul_imm(offset, pointee_size as i64);
647             let base_val = base.load_scalar(fx);
648             let res = fx.bcx.ins().iadd(base_val, ptr_diff);
649             ret.write_cvalue(fx, CValue::by_val(res, base.layout()));
650         };
651
652         transmute, (c from) {
653             ret.write_cvalue_transmute(fx, from);
654         };
655         write_bytes | volatile_set_memory, (c dst, v val, v count) {
656             let pointee_ty = dst.layout().ty.builtin_deref(true).unwrap().ty;
657             let pointee_size = fx.layout_of(pointee_ty).size.bytes();
658             let count = fx.bcx.ins().imul_imm(count, pointee_size as i64);
659             let dst_ptr = dst.load_scalar(fx);
660             // FIXME make the memset actually volatile when switching to emit_small_memset
661             // FIXME use emit_small_memset
662             fx.bcx.call_memset(fx.module.target_config(), dst_ptr, val, count);
663         };
664         ctlz | ctlz_nonzero, <T> (v arg) {
665             // FIXME trap on `ctlz_nonzero` with zero arg.
666             let res = if T == fx.tcx.types.u128 || T == fx.tcx.types.i128 {
667                 // FIXME verify this algorithm is correct
668                 let (lsb, msb) = fx.bcx.ins().isplit(arg);
669                 let lsb_lz = fx.bcx.ins().clz(lsb);
670                 let msb_lz = fx.bcx.ins().clz(msb);
671                 let msb_is_zero = fx.bcx.ins().icmp_imm(IntCC::Equal, msb, 0);
672                 let lsb_lz_plus_64 = fx.bcx.ins().iadd_imm(lsb_lz, 64);
673                 let res = fx.bcx.ins().select(msb_is_zero, lsb_lz_plus_64, msb_lz);
674                 fx.bcx.ins().uextend(types::I128, res)
675             } else {
676                 fx.bcx.ins().clz(arg)
677             };
678             let res = CValue::by_val(res, fx.layout_of(T));
679             ret.write_cvalue(fx, res);
680         };
681         cttz | cttz_nonzero, <T> (v arg) {
682             // FIXME trap on `cttz_nonzero` with zero arg.
683             let res = if T == fx.tcx.types.u128 || T == fx.tcx.types.i128 {
684                 // FIXME verify this algorithm is correct
685                 let (lsb, msb) = fx.bcx.ins().isplit(arg);
686                 let lsb_tz = fx.bcx.ins().ctz(lsb);
687                 let msb_tz = fx.bcx.ins().ctz(msb);
688                 let lsb_is_zero = fx.bcx.ins().icmp_imm(IntCC::Equal, lsb, 0);
689                 let msb_tz_plus_64 = fx.bcx.ins().iadd_imm(msb_tz, 64);
690                 let res = fx.bcx.ins().select(lsb_is_zero, msb_tz_plus_64, lsb_tz);
691                 fx.bcx.ins().uextend(types::I128, res)
692             } else {
693                 fx.bcx.ins().ctz(arg)
694             };
695             let res = CValue::by_val(res, fx.layout_of(T));
696             ret.write_cvalue(fx, res);
697         };
698         ctpop, <T> (v arg) {
699             let res = fx.bcx.ins().popcnt(arg);
700             let res = CValue::by_val(res, fx.layout_of(T));
701             ret.write_cvalue(fx, res);
702         };
703         bitreverse, <T> (v arg) {
704             let res = fx.bcx.ins().bitrev(arg);
705             let res = CValue::by_val(res, fx.layout_of(T));
706             ret.write_cvalue(fx, res);
707         };
708         bswap, <T> (v arg) {
709             // FIXME(CraneStation/cranelift#794) add bswap instruction to cranelift
710             fn swap(bcx: &mut FunctionBuilder<'_>, v: Value) -> Value {
711                 match bcx.func.dfg.value_type(v) {
712                     types::I8 => v,
713
714                     // https://code.woboq.org/gcc/include/bits/byteswap.h.html
715                     types::I16 => {
716                         let tmp1 = bcx.ins().ishl_imm(v, 8);
717                         let n1 = bcx.ins().band_imm(tmp1, 0xFF00);
718
719                         let tmp2 = bcx.ins().ushr_imm(v, 8);
720                         let n2 = bcx.ins().band_imm(tmp2, 0x00FF);
721
722                         bcx.ins().bor(n1, n2)
723                     }
724                     types::I32 => {
725                         let tmp1 = bcx.ins().ishl_imm(v, 24);
726                         let n1 = bcx.ins().band_imm(tmp1, 0xFF00_0000);
727
728                         let tmp2 = bcx.ins().ishl_imm(v, 8);
729                         let n2 = bcx.ins().band_imm(tmp2, 0x00FF_0000);
730
731                         let tmp3 = bcx.ins().ushr_imm(v, 8);
732                         let n3 = bcx.ins().band_imm(tmp3, 0x0000_FF00);
733
734                         let tmp4 = bcx.ins().ushr_imm(v, 24);
735                         let n4 = bcx.ins().band_imm(tmp4, 0x0000_00FF);
736
737                         let or_tmp1 = bcx.ins().bor(n1, n2);
738                         let or_tmp2 = bcx.ins().bor(n3, n4);
739                         bcx.ins().bor(or_tmp1, or_tmp2)
740                     }
741                     types::I64 => {
742                         let tmp1 = bcx.ins().ishl_imm(v, 56);
743                         let n1 = bcx.ins().band_imm(tmp1, 0xFF00_0000_0000_0000u64 as i64);
744
745                         let tmp2 = bcx.ins().ishl_imm(v, 40);
746                         let n2 = bcx.ins().band_imm(tmp2, 0x00FF_0000_0000_0000u64 as i64);
747
748                         let tmp3 = bcx.ins().ishl_imm(v, 24);
749                         let n3 = bcx.ins().band_imm(tmp3, 0x0000_FF00_0000_0000u64 as i64);
750
751                         let tmp4 = bcx.ins().ishl_imm(v, 8);
752                         let n4 = bcx.ins().band_imm(tmp4, 0x0000_00FF_0000_0000u64 as i64);
753
754                         let tmp5 = bcx.ins().ushr_imm(v, 8);
755                         let n5 = bcx.ins().band_imm(tmp5, 0x0000_0000_FF00_0000u64 as i64);
756
757                         let tmp6 = bcx.ins().ushr_imm(v, 24);
758                         let n6 = bcx.ins().band_imm(tmp6, 0x0000_0000_00FF_0000u64 as i64);
759
760                         let tmp7 = bcx.ins().ushr_imm(v, 40);
761                         let n7 = bcx.ins().band_imm(tmp7, 0x0000_0000_0000_FF00u64 as i64);
762
763                         let tmp8 = bcx.ins().ushr_imm(v, 56);
764                         let n8 = bcx.ins().band_imm(tmp8, 0x0000_0000_0000_00FFu64 as i64);
765
766                         let or_tmp1 = bcx.ins().bor(n1, n2);
767                         let or_tmp2 = bcx.ins().bor(n3, n4);
768                         let or_tmp3 = bcx.ins().bor(n5, n6);
769                         let or_tmp4 = bcx.ins().bor(n7, n8);
770
771                         let or_tmp5 = bcx.ins().bor(or_tmp1, or_tmp2);
772                         let or_tmp6 = bcx.ins().bor(or_tmp3, or_tmp4);
773                         bcx.ins().bor(or_tmp5, or_tmp6)
774                     }
775                     types::I128 => {
776                         let (lo, hi) = bcx.ins().isplit(v);
777                         let lo = swap(bcx, lo);
778                         let hi = swap(bcx, hi);
779                         bcx.ins().iconcat(hi, lo)
780                     }
781                     ty => unreachable!("bswap {}", ty),
782                 }
783             };
784             let res = CValue::by_val(swap(&mut fx.bcx, arg), fx.layout_of(T));
785             ret.write_cvalue(fx, res);
786         };
787         assert_inhabited | assert_zero_valid | assert_uninit_valid, <T> () {
788             let layout = fx.layout_of(T);
789             if layout.abi.is_uninhabited() {
790                 crate::trap::trap_panic(fx, &format!("attempted to instantiate uninhabited type `{}`", T));
791                 return;
792             }
793
794             if intrinsic == "assert_zero_valid" && !layout.might_permit_raw_init(fx, /*zero:*/ true).unwrap() {
795                 crate::trap::trap_panic(fx, &format!("attempted to zero-initialize type `{}`, which is invalid", T));
796                 return;
797             }
798
799             if intrinsic == "assert_uninit_valid" && !layout.might_permit_raw_init(fx, /*zero:*/ false).unwrap() {
800                 crate::trap::trap_panic(fx, &format!("attempted to leave type `{}` uninitialized, which is invalid", T));
801                 return;
802             }
803         };
804
805         volatile_load, (c ptr) {
806             // Cranelift treats loads as volatile by default
807             // FIXME ignore during stack2reg optimization
808             let inner_layout =
809                 fx.layout_of(ptr.layout().ty.builtin_deref(true).unwrap().ty);
810             let val = CValue::by_ref(Pointer::new(ptr.load_scalar(fx)), inner_layout);
811             ret.write_cvalue(fx, val);
812         };
813         volatile_store, (v ptr, c val) {
814             // Cranelift treats stores as volatile by default
815             // FIXME ignore during stack2reg optimization
816             let dest = CPlace::for_ptr(Pointer::new(ptr), val.layout());
817             dest.write_cvalue(fx, val);
818         };
819
820         size_of | pref_align_of | min_align_of | needs_drop | type_id | type_name, () {
821             let const_val =
822                 fx.tcx.const_eval_instance(ParamEnv::reveal_all(), instance, None).unwrap();
823             let val = crate::constant::trans_const_value(
824                 fx,
825                 ty::Const::from_value(fx.tcx, const_val, ret.layout().ty),
826             );
827             ret.write_cvalue(fx, val);
828         };
829
830         ptr_offset_from, <T> (v ptr, v base) {
831             let isize_layout = fx.layout_of(fx.tcx.types.isize);
832
833             let pointee_size: u64 = fx.layout_of(T).size.bytes();
834             let diff = fx.bcx.ins().isub(ptr, base);
835             // FIXME this can be an exact division.
836             let val = CValue::by_val(fx.bcx.ins().sdiv_imm(diff, pointee_size as i64), isize_layout);
837             ret.write_cvalue(fx, val);
838         };
839
840         ptr_guaranteed_eq, (c a, c b) {
841             let val = crate::num::trans_ptr_binop(fx, BinOp::Eq, a, b);
842             ret.write_cvalue(fx, val);
843         };
844
845         ptr_guaranteed_ne, (c a, c b) {
846             let val = crate::num::trans_ptr_binop(fx, BinOp::Ne, a, b);
847             ret.write_cvalue(fx, val);
848         };
849
850         caller_location, () {
851             let caller_location = fx.get_caller_location(span);
852             ret.write_cvalue(fx, caller_location);
853         };
854
855         _ if intrinsic.starts_with("atomic_fence"), () {
856             crate::atomic_shim::lock_global_lock(fx);
857             crate::atomic_shim::unlock_global_lock(fx);
858         };
859         _ if intrinsic.starts_with("atomic_singlethreadfence"), () {
860             crate::atomic_shim::lock_global_lock(fx);
861             crate::atomic_shim::unlock_global_lock(fx);
862         };
863         _ if intrinsic.starts_with("atomic_load"), (c ptr) {
864             crate::atomic_shim::lock_global_lock(fx);
865
866             let inner_layout =
867                 fx.layout_of(ptr.layout().ty.builtin_deref(true).unwrap().ty);
868             let val = CValue::by_ref(Pointer::new(ptr.load_scalar(fx)), inner_layout);
869             ret.write_cvalue(fx, val);
870
871             crate::atomic_shim::unlock_global_lock(fx);
872         };
873         _ if intrinsic.starts_with("atomic_store"), (v ptr, c val) {
874             crate::atomic_shim::lock_global_lock(fx);
875
876             let dest = CPlace::for_ptr(Pointer::new(ptr), val.layout());
877             dest.write_cvalue(fx, val);
878
879             crate::atomic_shim::unlock_global_lock(fx);
880         };
881         _ if intrinsic.starts_with("atomic_xchg"), <T> (v ptr, c src) {
882             crate::atomic_shim::lock_global_lock(fx);
883
884             // Read old
885             let clif_ty = fx.clif_type(T).unwrap();
886             let old = fx.bcx.ins().load(clif_ty, MemFlags::new(), ptr, 0);
887             ret.write_cvalue(fx, CValue::by_val(old, fx.layout_of(T)));
888
889             // Write new
890             let dest = CPlace::for_ptr(Pointer::new(ptr), src.layout());
891             dest.write_cvalue(fx, src);
892
893             crate::atomic_shim::unlock_global_lock(fx);
894         };
895         _ if intrinsic.starts_with("atomic_cxchg"), <T> (v ptr, v test_old, v new) { // both atomic_cxchg_* and atomic_cxchgweak_*
896             crate::atomic_shim::lock_global_lock(fx);
897
898             // Read old
899             let clif_ty = fx.clif_type(T).unwrap();
900             let old = fx.bcx.ins().load(clif_ty, MemFlags::new(), ptr, 0);
901
902             // Compare
903             let is_eq = fx.bcx.ins().icmp(IntCC::Equal, old, test_old);
904             let new = fx.bcx.ins().select(is_eq, new, old); // Keep old if not equal to test_old
905
906             // Write new
907             fx.bcx.ins().store(MemFlags::new(), new, ptr, 0);
908
909             let ret_val = CValue::by_val_pair(old, fx.bcx.ins().bint(types::I8, is_eq), ret.layout());
910             ret.write_cvalue(fx, ret_val);
911
912             crate::atomic_shim::unlock_global_lock(fx);
913         };
914
915         _ if intrinsic.starts_with("atomic_xadd"), <T> (v ptr, v amount) {
916             atomic_binop_return_old! (fx, iadd<T>(ptr, amount) -> ret);
917         };
918         _ if intrinsic.starts_with("atomic_xsub"), <T> (v ptr, v amount) {
919             atomic_binop_return_old! (fx, isub<T>(ptr, amount) -> ret);
920         };
921         _ if intrinsic.starts_with("atomic_and"), <T> (v ptr, v src) {
922             atomic_binop_return_old! (fx, band<T>(ptr, src) -> ret);
923         };
924         _ if intrinsic.starts_with("atomic_nand"), <T> (v ptr, v src) {
925             crate::atomic_shim::lock_global_lock(fx);
926
927             let clif_ty = fx.clif_type(T).unwrap();
928             let old = fx.bcx.ins().load(clif_ty, MemFlags::new(), ptr, 0);
929             let and = fx.bcx.ins().band(old, src);
930             let new = fx.bcx.ins().bnot(and);
931             fx.bcx.ins().store(MemFlags::new(), new, ptr, 0);
932             ret.write_cvalue(fx, CValue::by_val(old, fx.layout_of(T)));
933
934             crate::atomic_shim::unlock_global_lock(fx);
935         };
936         _ if intrinsic.starts_with("atomic_or"), <T> (v ptr, v src) {
937             atomic_binop_return_old! (fx, bor<T>(ptr, src) -> ret);
938         };
939         _ if intrinsic.starts_with("atomic_xor"), <T> (v ptr, v src) {
940             atomic_binop_return_old! (fx, bxor<T>(ptr, src) -> ret);
941         };
942
943         _ if intrinsic.starts_with("atomic_max"), <T> (v ptr, v src) {
944             atomic_minmax!(fx, IntCC::SignedGreaterThan, <T> (ptr, src) -> ret);
945         };
946         _ if intrinsic.starts_with("atomic_umax"), <T> (v ptr, v src) {
947             atomic_minmax!(fx, IntCC::UnsignedGreaterThan, <T> (ptr, src) -> ret);
948         };
949         _ if intrinsic.starts_with("atomic_min"), <T> (v ptr, v src) {
950             atomic_minmax!(fx, IntCC::SignedLessThan, <T> (ptr, src) -> ret);
951         };
952         _ if intrinsic.starts_with("atomic_umin"), <T> (v ptr, v src) {
953             atomic_minmax!(fx, IntCC::UnsignedLessThan, <T> (ptr, src) -> ret);
954         };
955
956         minnumf32, (v a, v b) {
957             let val = fx.bcx.ins().fmin(a, b);
958             let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f32));
959             ret.write_cvalue(fx, val);
960         };
961         minnumf64, (v a, v b) {
962             let val = fx.bcx.ins().fmin(a, b);
963             let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f64));
964             ret.write_cvalue(fx, val);
965         };
966         maxnumf32, (v a, v b) {
967             let val = fx.bcx.ins().fmax(a, b);
968             let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f32));
969             ret.write_cvalue(fx, val);
970         };
971         maxnumf64, (v a, v b) {
972             let val = fx.bcx.ins().fmax(a, b);
973             let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f64));
974             ret.write_cvalue(fx, val);
975         };
976
977         try, (v f, v data, v _catch_fn) {
978             // FIXME once unwinding is supported, change this to actually catch panics
979             let f_sig = fx.bcx.func.import_signature(Signature {
980                 call_conv: CallConv::triple_default(fx.triple()),
981                 params: vec![AbiParam::new(fx.bcx.func.dfg.value_type(data))],
982                 returns: vec![],
983             });
984
985             fx.bcx.ins().call_indirect(f_sig, f, &[data]);
986
987             let ret_val = CValue::const_val(fx, ret.layout(), 0);
988             ret.write_cvalue(fx, ret_val);
989         };
990
991         fadd_fast | fsub_fast | fmul_fast | fdiv_fast | frem_fast, (c x, c y) {
992             let res = crate::num::trans_float_binop(fx, match intrinsic {
993                 "fadd_fast" => BinOp::Add,
994                 "fsub_fast" => BinOp::Sub,
995                 "fmul_fast" => BinOp::Mul,
996                 "fdiv_fast" => BinOp::Div,
997                 "frem_fast" => BinOp::Rem,
998                 _ => unreachable!(),
999             }, x, y);
1000             ret.write_cvalue(fx, res);
1001         };
1002         float_to_int_unchecked, (v f) {
1003             let res = crate::cast::clif_int_or_float_cast(
1004                 fx,
1005                 f,
1006                 false,
1007                 fx.clif_type(ret.layout().ty).unwrap(),
1008                 type_sign(ret.layout().ty),
1009             );
1010             ret.write_cvalue(fx, CValue::by_val(res, ret.layout()));
1011         };
1012     }
1013
1014     if let Some((_, dest)) = destination {
1015         let ret_block = fx.get_block(dest);
1016         fx.bcx.ins().jump(ret_block, &[]);
1017     } else {
1018         trap_unreachable(fx, "[corruption] Diverging intrinsic returned.");
1019     }
1020 }