]> git.lizzy.rs Git - rust.git/blob - src/intrinsics.rs
Fix simd comparison
[rust.git] / src / intrinsics.rs
1 use crate::prelude::*;
2
3 use rustc::ty::subst::SubstsRef;
4
5 macro_rules! intrinsic_pat {
6     (_) => {
7         _
8     };
9     ($name:ident) => {
10         stringify!($name)
11     }
12 }
13
14 macro_rules! intrinsic_arg {
15     (c $fx:expr, $arg:ident) => {
16         $arg
17     };
18     (v $fx:expr, $arg:ident) => {
19         $arg.load_scalar($fx)
20     };
21 }
22
23 macro_rules! intrinsic_substs {
24     ($substs:expr, $index:expr,) => {};
25     ($substs:expr, $index:expr, $first:ident $(,$rest:ident)*) => {
26         let $first = $substs.type_at($index);
27         intrinsic_substs!($substs, $index+1, $($rest),*);
28     };
29 }
30
31 macro_rules! intrinsic_match {
32     ($fx:expr, $intrinsic:expr, $substs:expr, $args:expr, $(
33         $($name:tt)|+ $(if $cond:expr)?, $(<$($subst:ident),*>)? ($($a:ident $arg:ident),*) $content:block;
34     )*) => {
35         match $intrinsic {
36             $(
37                 $(intrinsic_pat!($name))|* $(if $cond)? => {
38                     #[allow(unused_parens, non_snake_case)]
39                     {
40                         $(
41                             intrinsic_substs!($substs, 0, $($subst),*);
42                         )?
43                         if let [$($arg),*] = *$args {
44                             let ($($arg),*) = (
45                                 $(intrinsic_arg!($a $fx, $arg)),*
46                             );
47                             #[warn(unused_parens, non_snake_case)]
48                             {
49                                 $content
50                             }
51                         } else {
52                             bug!("wrong number of args for intrinsic {:?}", $intrinsic);
53                         }
54                     }
55                 }
56             )*
57             _ => unimpl!("unsupported intrinsic {}", $intrinsic),
58         }
59     };
60 }
61
62 macro_rules! call_intrinsic_match {
63     ($fx:expr, $intrinsic:expr, $substs:expr, $ret:expr, $destination:expr, $args:expr, $(
64         $name:ident($($arg:ident),*) -> $ty:ident => $func:ident,
65     )*) => {
66         match $intrinsic {
67             $(
68                 stringify!($name) => {
69                     assert!($substs.is_noop());
70                     if let [$($arg),*] = *$args {
71                         let res = $fx.easy_call(stringify!($func), &[$($arg),*], $fx.tcx.types.$ty);
72                         $ret.write_cvalue($fx, res);
73
74                         if let Some((_, dest)) = $destination {
75                             let ret_ebb = $fx.get_ebb(dest);
76                             $fx.bcx.ins().jump(ret_ebb, &[]);
77                             return;
78                         } else {
79                             unreachable!();
80                         }
81                     } else {
82                         bug!("wrong number of args for intrinsic {:?}", $intrinsic);
83                     }
84                 }
85             )*
86             _ => {}
87         }
88     }
89 }
90
91 macro_rules! atomic_binop_return_old {
92     ($fx:expr, $op:ident<$T:ident>($ptr:ident, $src:ident) -> $ret:ident) => {
93         let clif_ty = $fx.clif_type($T).unwrap();
94         let old = $fx.bcx.ins().load(clif_ty, MemFlags::new(), $ptr, 0);
95         let new = $fx.bcx.ins().$op(old, $src);
96         $fx.bcx.ins().store(MemFlags::new(), new, $ptr, 0);
97         $ret.write_cvalue($fx, CValue::by_val(old, $fx.layout_of($T)));
98     };
99 }
100
101 macro_rules! atomic_minmax {
102     ($fx:expr, $cc:expr, <$T:ident> ($ptr:ident, $src:ident) -> $ret:ident) => {
103         // Read old
104         let clif_ty = $fx.clif_type($T).unwrap();
105         let old = $fx.bcx.ins().load(clif_ty, MemFlags::new(), $ptr, 0);
106
107         // Compare
108         let is_eq = $fx.bcx.ins().icmp(IntCC::SignedGreaterThan, old, $src);
109         let new = crate::common::codegen_select(&mut $fx.bcx, is_eq, old, $src);
110
111         // Write new
112         $fx.bcx.ins().store(MemFlags::new(), new, $ptr, 0);
113
114         let ret_val = CValue::by_val(old, $ret.layout());
115         $ret.write_cvalue($fx, ret_val);
116     };
117 }
118
119 fn lane_type_and_count<'tcx>(
120     fx: &FunctionCx<'_, 'tcx, impl Backend>,
121     layout: TyLayout<'tcx>,
122     intrinsic: &str,
123 ) -> (TyLayout<'tcx>, usize) {
124     let lane_count = match layout.fields {
125         layout::FieldPlacement::Array { stride: _, count } => usize::try_from(count).unwrap(),
126         _ => panic!("Non vector type {:?} passed to or returned from simd_* intrinsic {}", layout.ty, intrinsic),
127     };
128     let lane_layout = layout.field(fx, 0);
129     (lane_layout, lane_count)
130 }
131
132 fn simd_for_each_lane<'tcx, B: Backend>(
133     fx: &mut FunctionCx<'_, 'tcx, B>,
134     intrinsic: &str,
135     x: CValue<'tcx>,
136     y: CValue<'tcx>,
137     ret: CPlace<'tcx>,
138     f: impl Fn(&mut FunctionCx<'_, 'tcx, B>, TyLayout<'tcx>, TyLayout<'tcx>, Value, Value) -> CValue<'tcx>,
139 ) {
140     assert_eq!(x.layout(), y.layout());
141     let layout = x.layout();
142
143     let (lane_layout, lane_count) = lane_type_and_count(fx, layout, intrinsic);
144     let (ret_lane_layout, ret_lane_count) = lane_type_and_count(fx, ret.layout(), intrinsic);
145     assert_eq!(lane_count, ret_lane_count);
146
147     for lane in 0..lane_count {
148         let lane = mir::Field::new(lane);
149         let x_lane = x.value_field(fx, lane).load_scalar(fx);
150         let y_lane = y.value_field(fx, lane).load_scalar(fx);
151
152         let res_lane = f(fx, lane_layout, ret_lane_layout, x_lane, y_lane);
153
154         ret.place_field(fx, lane).write_cvalue(fx, res_lane);
155     }
156 }
157
158 fn bool_to_zero_or_max_uint<'tcx>(
159     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
160     layout: TyLayout<'tcx>,
161     val: Value,
162 ) -> CValue<'tcx> {
163     let ty = fx.clif_type(layout.ty).unwrap();
164
165     let zero = fx.bcx.ins().iconst(ty, 0);
166     let max = fx.bcx.ins().iconst(ty, (u64::max_value() >> (64 - ty.bits())) as i64);
167     let res = crate::common::codegen_select(&mut fx.bcx, val, max, zero);
168     CValue::by_val(res, layout)
169 }
170
171 macro_rules! simd_cmp {
172     ($fx:expr, $intrinsic:expr, $cc:ident($x:ident, $y:ident) -> $ret:ident) => {
173         simd_for_each_lane($fx, $intrinsic, $x, $y, $ret, |fx, _lane_layout, res_lane_layout, x_lane, y_lane| {
174             let res_lane = fx.bcx.ins().icmp(IntCC::$cc, x_lane, y_lane);
175             bool_to_zero_or_max_uint(fx, res_lane_layout, res_lane)
176         });
177     };
178     ($fx:expr, $intrinsic:expr, $cc_u:ident|$cc_s:ident($x:ident, $y:ident) -> $ret:ident) => {
179         simd_for_each_lane($fx, $intrinsic, $x, $y, $ret, |fx, lane_layout, res_lane_layout, x_lane, y_lane| {
180             let res_lane = match lane_layout.ty.sty {
181                 ty::Uint(_) => fx.bcx.ins().icmp(IntCC::$cc_u, x_lane, y_lane),
182                 ty::Int(_) => fx.bcx.ins().icmp(IntCC::$cc_s, x_lane, y_lane),
183                 _ => unreachable!("{:?}", lane_layout.ty),
184             };
185             bool_to_zero_or_max_uint(fx, res_lane_layout, res_lane)
186         });
187     };
188
189 }
190
191 macro_rules! simd_binop {
192     ($fx:expr, $intrinsic:expr, $op:ident($x:ident, $y:ident) -> $ret:ident) => {
193         simd_for_each_lane($fx, $intrinsic, $x, $y, $ret, |fx, _lane_layout, ret_lane_layout, x_lane, y_lane| {
194             let res_lane = fx.bcx.ins().$op(x_lane, y_lane);
195             CValue::by_val(res_lane, ret_lane_layout)
196         });
197     };
198     ($fx:expr, $intrinsic:expr, $op_u:ident|$op_s:ident($x:ident, $y:ident) -> $ret:ident) => {
199         simd_for_each_lane($fx, $intrinsic, $x, $y, $ret, |fx, lane_layout, ret_lane_layout, x_lane, y_lane| {
200             let res_lane = match lane_layout.ty.sty {
201                 ty::Uint(_) => fx.bcx.ins().$op_u(x_lane, y_lane),
202                 ty::Int(_) => fx.bcx.ins().$op_s(x_lane, y_lane),
203                 _ => unreachable!("{:?}", lane_layout.ty),
204             };
205             CValue::by_val(res_lane, ret_lane_layout)
206         });
207     };
208 }
209
210 pub fn codegen_intrinsic_call<'a, 'tcx: 'a>(
211     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
212     def_id: DefId,
213     substs: SubstsRef<'tcx>,
214     args: Vec<CValue<'tcx>>,
215     destination: Option<(CPlace<'tcx>, BasicBlock)>,
216 ) {
217     let intrinsic = fx.tcx.item_name(def_id).as_str();
218     let intrinsic = &intrinsic[..];
219
220     let ret = match destination {
221         Some((place, _)) => place,
222         None => {
223             // Insert non returning intrinsics here
224             match intrinsic {
225                 "abort" => {
226                     trap_panic(fx, "Called intrinsic::abort.");
227                 }
228                 "unreachable" => {
229                     trap_unreachable(fx, "[corruption] Called intrinsic::unreachable.");
230                 }
231                 _ => unimplemented!("unsupported instrinsic {}", intrinsic),
232             }
233             return;
234         }
235     };
236
237     let u64_layout = fx.layout_of(fx.tcx.types.u64);
238     let usize_layout = fx.layout_of(fx.tcx.types.usize);
239
240     call_intrinsic_match! {
241         fx, intrinsic, substs, ret, destination, args,
242         expf32(flt) -> f32 => expf,
243         expf64(flt) -> f64 => exp,
244         exp2f32(flt) -> f32 => exp2f,
245         exp2f64(flt) -> f64 => exp2,
246         sqrtf32(flt) -> f32 => sqrtf,
247         sqrtf64(flt) -> f64 => sqrt,
248         powif32(a, x) -> f32 => __powisf2, // compiler-builtins
249         powif64(a, x) -> f64 => __powidf2, // compiler-builtins
250         logf32(flt) -> f32 => logf,
251         logf64(flt) -> f64 => log,
252         fabsf32(flt) -> f32 => fabsf,
253         fabsf64(flt) -> f64 => fabs,
254         fmaf32(x, y, z) -> f32 => fmaf,
255         fmaf64(x, y, z) -> f64 => fma,
256
257         // rounding variants
258         floorf32(flt) -> f32 => floorf,
259         floorf64(flt) -> f64 => floor,
260         ceilf32(flt) -> f32 => ceilf,
261         ceilf64(flt) -> f64 => ceil,
262         truncf32(flt) -> f32 => truncf,
263         truncf64(flt) -> f64 => trunc,
264         roundf32(flt) -> f32 => roundf,
265         roundf64(flt) -> f64 => round,
266
267         // trigonometry
268         sinf32(flt) -> f32 => sinf,
269         sinf64(flt) -> f64 => sin,
270         cosf32(flt) -> f32 => cosf,
271         cosf64(flt) -> f64 => cos,
272         tanf32(flt) -> f32 => tanf,
273         tanf64(flt) -> f64 => tan,
274     }
275
276     intrinsic_match! {
277         fx, intrinsic, substs, args,
278
279         assume, (c _a) {};
280         likely | unlikely, (c a) {
281             ret.write_cvalue(fx, a);
282         };
283         breakpoint, () {
284             fx.bcx.ins().debugtrap();
285         };
286         copy | copy_nonoverlapping, <elem_ty> (v src, v dst, v count) {
287             let elem_size: u64 = fx.layout_of(elem_ty).size.bytes();
288             let elem_size = fx
289                 .bcx
290                 .ins()
291                 .iconst(fx.pointer_type, elem_size as i64);
292             assert_eq!(args.len(), 3);
293             let byte_amount = fx.bcx.ins().imul(count, elem_size);
294
295             if intrinsic.ends_with("_nonoverlapping") {
296                 fx.bcx.call_memcpy(fx.module.target_config(), dst, src, byte_amount);
297             } else {
298                 fx.bcx.call_memmove(fx.module.target_config(), dst, src, byte_amount);
299             }
300         };
301         discriminant_value, (c val) {
302             let pointee_layout = fx.layout_of(val.layout().ty.builtin_deref(true).unwrap().ty);
303             let place = CPlace::for_addr(val.load_scalar(fx), pointee_layout);
304             let discr = crate::base::trans_get_discriminant(fx, place, ret.layout());
305             ret.write_cvalue(fx, discr);
306         };
307         size_of, <T> () {
308             let size_of = fx.layout_of(T).size.bytes();
309             let size_of = CValue::const_val(fx, usize_layout.ty, size_of.into());
310             ret.write_cvalue(fx, size_of);
311         };
312         size_of_val, <T> (c ptr) {
313             let layout = fx.layout_of(T);
314             let size = if layout.is_unsized() {
315                 let (_ptr, info) = ptr.load_scalar_pair(fx);
316                 let (size, _align) = crate::unsize::size_and_align_of_dst(fx, layout.ty, info);
317                 size
318             } else {
319                 fx
320                     .bcx
321                     .ins()
322                     .iconst(fx.pointer_type, layout.size.bytes() as i64)
323             };
324             ret.write_cvalue(fx, CValue::by_val(size, usize_layout));
325         };
326         min_align_of, <T> () {
327             let min_align = fx.layout_of(T).align.abi.bytes();
328             let min_align = CValue::const_val(fx, usize_layout.ty, min_align.into());
329             ret.write_cvalue(fx, min_align);
330         };
331         min_align_of_val, <T> (c ptr) {
332             let layout = fx.layout_of(T);
333             let align = if layout.is_unsized() {
334                 let (_ptr, info) = ptr.load_scalar_pair(fx);
335                 let (_size, align) = crate::unsize::size_and_align_of_dst(fx, layout.ty, info);
336                 align
337             } else {
338                 fx
339                     .bcx
340                     .ins()
341                     .iconst(fx.pointer_type, layout.align.abi.bytes() as i64)
342             };
343             ret.write_cvalue(fx, CValue::by_val(align, usize_layout));
344         };
345         pref_align_of, <T> () {
346             let pref_align = fx.layout_of(T).align.pref.bytes();
347             let pref_align = CValue::const_val(fx, usize_layout.ty, pref_align.into());
348             ret.write_cvalue(fx, pref_align);
349         };
350
351
352         type_id, <T> () {
353             let type_id = fx.tcx.type_id_hash(T);
354             let type_id = CValue::const_val(fx, u64_layout.ty, type_id.into());
355             ret.write_cvalue(fx, type_id);
356         };
357         type_name, <T> () {
358             let type_name = fx.tcx.type_name(T);
359             let type_name = crate::constant::trans_const_value(fx, type_name);
360             ret.write_cvalue(fx, type_name);
361         };
362
363         _ if intrinsic.starts_with("unchecked_") || intrinsic == "exact_div", (c x, c y) {
364             // FIXME trap on overflow
365             let bin_op = match intrinsic {
366                 "unchecked_sub" => BinOp::Sub,
367                 "unchecked_div" | "exact_div" => BinOp::Div,
368                 "unchecked_rem" => BinOp::Rem,
369                 "unchecked_shl" => BinOp::Shl,
370                 "unchecked_shr" => BinOp::Shr,
371                 _ => unimplemented!("intrinsic {}", intrinsic),
372             };
373             let res = match ret.layout().ty.sty {
374                 ty::Uint(_) => crate::base::trans_int_binop(
375                     fx,
376                     bin_op,
377                     x,
378                     y,
379                     ret.layout().ty,
380                     false,
381                 ),
382                 ty::Int(_) => crate::base::trans_int_binop(
383                     fx,
384                     bin_op,
385                     x,
386                     y,
387                     ret.layout().ty,
388                     true,
389                 ),
390                 _ => panic!(),
391             };
392             ret.write_cvalue(fx, res);
393         };
394         _ if intrinsic.ends_with("_with_overflow"), <T> (c x, c y) {
395             assert_eq!(x.layout().ty, y.layout().ty);
396             let bin_op = match intrinsic {
397                 "add_with_overflow" => BinOp::Add,
398                 "sub_with_overflow" => BinOp::Sub,
399                 "mul_with_overflow" => BinOp::Mul,
400                 _ => unimplemented!("intrinsic {}", intrinsic),
401             };
402             let res = match T.sty {
403                 ty::Uint(_) => crate::base::trans_checked_int_binop(
404                     fx,
405                     bin_op,
406                     x,
407                     y,
408                     ret.layout().ty,
409                     false,
410                 ),
411                 ty::Int(_) => crate::base::trans_checked_int_binop(
412                     fx,
413                     bin_op,
414                     x,
415                     y,
416                     ret.layout().ty,
417                     true,
418                 ),
419                 _ => panic!(),
420             };
421             ret.write_cvalue(fx, res);
422         };
423         _ if intrinsic.starts_with("overflowing_"), <T> (c x, c y) {
424             assert_eq!(x.layout().ty, y.layout().ty);
425             let bin_op = match intrinsic {
426                 "overflowing_add" => BinOp::Add,
427                 "overflowing_sub" => BinOp::Sub,
428                 "overflowing_mul" => BinOp::Mul,
429                 _ => unimplemented!("intrinsic {}", intrinsic),
430             };
431             let res = match T.sty {
432                 ty::Uint(_) => crate::base::trans_int_binop(
433                     fx,
434                     bin_op,
435                     x,
436                     y,
437                     ret.layout().ty,
438                     false,
439                 ),
440                 ty::Int(_) => crate::base::trans_int_binop(
441                     fx,
442                     bin_op,
443                     x,
444                     y,
445                     ret.layout().ty,
446                     true,
447                 ),
448                 _ => panic!(),
449             };
450             ret.write_cvalue(fx, res);
451         };
452         _ if intrinsic.starts_with("saturating_"), <T> (c x, c y) {
453             // FIXME implement saturating behavior
454             assert_eq!(x.layout().ty, y.layout().ty);
455             let bin_op = match intrinsic {
456                 "saturating_add" => BinOp::Add,
457                 "saturating_sub" => BinOp::Sub,
458                 "saturating_mul" => BinOp::Mul,
459                 _ => unimplemented!("intrinsic {}", intrinsic),
460             };
461             let res = match T.sty {
462                 ty::Uint(_) => crate::base::trans_int_binop(
463                     fx,
464                     bin_op,
465                     x,
466                     y,
467                     ret.layout().ty,
468                     false,
469                 ),
470                 ty::Int(_) => crate::base::trans_int_binop(
471                     fx,
472                     bin_op,
473                     x,
474                     y,
475                     ret.layout().ty,
476                     true,
477                 ),
478                 _ => panic!(),
479             };
480             ret.write_cvalue(fx, res);
481         };
482         rotate_left, <T>(v x, v y) {
483             let layout = fx.layout_of(T);
484             let res = fx.bcx.ins().rotl(x, y);
485             ret.write_cvalue(fx, CValue::by_val(res, layout));
486         };
487         rotate_right, <T>(v x, v y) {
488             let layout = fx.layout_of(T);
489             let res = fx.bcx.ins().rotr(x, y);
490             ret.write_cvalue(fx, CValue::by_val(res, layout));
491         };
492
493         // The only difference between offset and arith_offset is regarding UB. Because Cranelift
494         // doesn't have UB both are codegen'ed the same way
495         offset | arith_offset, (c base, v offset) {
496             let pointee_ty = base.layout().ty.builtin_deref(true).unwrap().ty;
497             let pointee_size = fx.layout_of(pointee_ty).size.bytes();
498             let ptr_diff = fx.bcx.ins().imul_imm(offset, pointee_size as i64);
499             let base_val = base.load_scalar(fx);
500             let res = fx.bcx.ins().iadd(base_val, ptr_diff);
501             ret.write_cvalue(fx, CValue::by_val(res, args[0].layout()));
502         };
503
504         transmute, <src_ty, dst_ty> (c from) {
505             assert_eq!(from.layout().ty, src_ty);
506             let addr = from.force_stack(fx);
507             let dst_layout = fx.layout_of(dst_ty);
508             ret.write_cvalue(fx, CValue::by_ref(addr, dst_layout))
509         };
510         init, () {
511             if ret.layout().abi == Abi::Uninhabited {
512                 crate::trap::trap_panic(fx, "[panic] Called intrinsic::init for uninhabited type.");
513                 return;
514             }
515
516             match ret {
517                 CPlace::NoPlace(_layout) => {}
518                 CPlace::Var(var, layout) => {
519                     let clif_ty = fx.clif_type(layout.ty).unwrap();
520                     let val = match clif_ty {
521                         types::I8 | types::I16 | types::I32 | types::I64 => fx.bcx.ins().iconst(clif_ty, 0),
522                         types::F32 => {
523                             let zero = fx.bcx.ins().iconst(types::I32, 0);
524                             fx.bcx.ins().bitcast(types::F32, zero)
525                         }
526                         types::F64 => {
527                             let zero = fx.bcx.ins().iconst(types::I64, 0);
528                             fx.bcx.ins().bitcast(types::F64, zero)
529                         }
530                         _ => panic!("clif_type returned {}", clif_ty),
531                     };
532                     fx.bcx.def_var(mir_var(var), val);
533                 }
534                 _ => {
535                     let addr = ret.to_addr(fx);
536                     let layout = ret.layout();
537                     fx.bcx.emit_small_memset(fx.module.target_config(), addr, 0, layout.size.bytes(), 1);
538                 }
539             }
540         };
541         write_bytes, (c dst, v val, v count) {
542             let pointee_ty = dst.layout().ty.builtin_deref(true).unwrap().ty;
543             let pointee_size = fx.layout_of(pointee_ty).size.bytes();
544             let count = fx.bcx.ins().imul_imm(count, pointee_size as i64);
545             let dst_ptr = dst.load_scalar(fx);
546             fx.bcx.call_memset(fx.module.target_config(), dst_ptr, val, count);
547         };
548         ctlz | ctlz_nonzero, <T> (v arg) {
549             let res = if T == fx.tcx.types.u128 || T == fx.tcx.types.i128 {
550                 // FIXME verify this algorithm is correct
551                 let (lsb, msb) = fx.bcx.ins().isplit(arg);
552                 let lsb_lz = fx.bcx.ins().clz(lsb);
553                 let msb_lz = fx.bcx.ins().clz(msb);
554                 let msb_is_zero = fx.bcx.ins().icmp_imm(IntCC::Equal, msb, 0);
555                 let lsb_lz_plus_64 = fx.bcx.ins().iadd_imm(lsb_lz, 64);
556                 fx.bcx.ins().select(msb_is_zero, lsb_lz_plus_64, msb_lz)
557             } else {
558                 fx.bcx.ins().clz(arg)
559             };
560             let res = CValue::by_val(res, fx.layout_of(T));
561             ret.write_cvalue(fx, res);
562         };
563         cttz | cttz_nonzero, <T> (v arg) {
564             let res = if T == fx.tcx.types.u128 || T == fx.tcx.types.i128 {
565                 // FIXME verify this algorithm is correct
566                 let (lsb, msb) = fx.bcx.ins().isplit(arg);
567                 let lsb_tz = fx.bcx.ins().ctz(lsb);
568                 let msb_tz = fx.bcx.ins().ctz(msb);
569                 let lsb_is_zero = fx.bcx.ins().icmp_imm(IntCC::Equal, lsb, 0);
570                 let msb_tz_plus_64 = fx.bcx.ins().iadd_imm(msb_tz, 64);
571                 fx.bcx.ins().select(lsb_is_zero, msb_tz_plus_64, lsb_tz)
572             } else {
573                 fx.bcx.ins().ctz(arg)
574             };
575             let res = CValue::by_val(res, fx.layout_of(T));
576             ret.write_cvalue(fx, res);
577         };
578         ctpop, <T> (v arg) {
579             let res = CValue::by_val(fx.bcx.ins().popcnt(arg), fx.layout_of(T));
580             ret.write_cvalue(fx, res);
581         };
582         bitreverse, <T> (v arg) {
583             let res = CValue::by_val(fx.bcx.ins().bitrev(arg), fx.layout_of(T));
584             ret.write_cvalue(fx, res);
585         };
586         bswap, <T> (v arg) {
587             // FIXME(CraneStation/cranelift#794) add bswap instruction to cranelift
588             fn swap(bcx: &mut FunctionBuilder, v: Value) -> Value {
589                 match bcx.func.dfg.value_type(v) {
590                     types::I8 => v,
591
592                     // https://code.woboq.org/gcc/include/bits/byteswap.h.html
593                     types::I16 => {
594                         let tmp1 = bcx.ins().ishl_imm(v, 8);
595                         let n1 = bcx.ins().band_imm(tmp1, 0xFF00);
596
597                         let tmp2 = bcx.ins().ushr_imm(v, 8);
598                         let n2 = bcx.ins().band_imm(tmp2, 0x00FF);
599
600                         bcx.ins().bor(n1, n2)
601                     }
602                     types::I32 => {
603                         let tmp1 = bcx.ins().ishl_imm(v, 24);
604                         let n1 = bcx.ins().band_imm(tmp1, 0xFF00_0000);
605
606                         let tmp2 = bcx.ins().ishl_imm(v, 8);
607                         let n2 = bcx.ins().band_imm(tmp2, 0x00FF_0000);
608
609                         let tmp3 = bcx.ins().ushr_imm(v, 8);
610                         let n3 = bcx.ins().band_imm(tmp3, 0x0000_FF00);
611
612                         let tmp4 = bcx.ins().ushr_imm(v, 24);
613                         let n4 = bcx.ins().band_imm(tmp4, 0x0000_00FF);
614
615                         let or_tmp1 = bcx.ins().bor(n1, n2);
616                         let or_tmp2 = bcx.ins().bor(n3, n4);
617                         bcx.ins().bor(or_tmp1, or_tmp2)
618                     }
619                     types::I64 => {
620                         let tmp1 = bcx.ins().ishl_imm(v, 56);
621                         let n1 = bcx.ins().band_imm(tmp1, 0xFF00_0000_0000_0000u64 as i64);
622
623                         let tmp2 = bcx.ins().ishl_imm(v, 40);
624                         let n2 = bcx.ins().band_imm(tmp2, 0x00FF_0000_0000_0000u64 as i64);
625
626                         let tmp3 = bcx.ins().ishl_imm(v, 24);
627                         let n3 = bcx.ins().band_imm(tmp3, 0x0000_FF00_0000_0000u64 as i64);
628
629                         let tmp4 = bcx.ins().ishl_imm(v, 8);
630                         let n4 = bcx.ins().band_imm(tmp4, 0x0000_00FF_0000_0000u64 as i64);
631
632                         let tmp5 = bcx.ins().ushr_imm(v, 8);
633                         let n5 = bcx.ins().band_imm(tmp5, 0x0000_0000_FF00_0000u64 as i64);
634
635                         let tmp6 = bcx.ins().ushr_imm(v, 24);
636                         let n6 = bcx.ins().band_imm(tmp6, 0x0000_0000_00FF_0000u64 as i64);
637
638                         let tmp7 = bcx.ins().ushr_imm(v, 40);
639                         let n7 = bcx.ins().band_imm(tmp7, 0x0000_0000_0000_FF00u64 as i64);
640
641                         let tmp8 = bcx.ins().ushr_imm(v, 56);
642                         let n8 = bcx.ins().band_imm(tmp8, 0x0000_0000_0000_00FFu64 as i64);
643
644                         let or_tmp1 = bcx.ins().bor(n1, n2);
645                         let or_tmp2 = bcx.ins().bor(n3, n4);
646                         let or_tmp3 = bcx.ins().bor(n5, n6);
647                         let or_tmp4 = bcx.ins().bor(n7, n8);
648
649                         let or_tmp5 = bcx.ins().bor(or_tmp1, or_tmp2);
650                         let or_tmp6 = bcx.ins().bor(or_tmp3, or_tmp4);
651                         bcx.ins().bor(or_tmp5, or_tmp6)
652                     }
653                     types::I128 => {
654                         let (lo, hi) = bcx.ins().isplit(v);
655                         let lo = swap(bcx, lo);
656                         let hi = swap(bcx, hi);
657                         bcx.ins().iconcat(hi, lo)
658                     }
659                     ty => unimplemented!("bswap {}", ty),
660                 }
661             };
662             let res = CValue::by_val(swap(&mut fx.bcx, arg), fx.layout_of(T));
663             ret.write_cvalue(fx, res);
664         };
665         needs_drop, <T> () {
666             let needs_drop = if T.needs_drop(fx.tcx, ParamEnv::reveal_all()) {
667                 1
668             } else {
669                 0
670             };
671             let needs_drop = CValue::const_val(fx, fx.tcx.types.bool, needs_drop);
672             ret.write_cvalue(fx, needs_drop);
673         };
674         panic_if_uninhabited, <T> () {
675             if fx.layout_of(T).abi.is_uninhabited() {
676                 crate::trap::trap_panic(fx, "[panic] Called intrinsic::panic_if_uninhabited for uninhabited type.");
677                 return;
678             }
679         };
680
681         volatile_load, (c ptr) {
682             // Cranelift treats loads as volatile by default
683             let inner_layout =
684                 fx.layout_of(ptr.layout().ty.builtin_deref(true).unwrap().ty);
685             let val = CValue::by_ref(ptr.load_scalar(fx), inner_layout);
686             ret.write_cvalue(fx, val);
687         };
688         volatile_store, (v ptr, c val) {
689             // Cranelift treats stores as volatile by default
690             let dest = CPlace::for_addr(ptr, val.layout());
691             dest.write_cvalue(fx, val);
692         };
693
694         _ if intrinsic.starts_with("atomic_fence"), () {};
695         _ if intrinsic.starts_with("atomic_singlethreadfence"), () {};
696         _ if intrinsic.starts_with("atomic_load"), (c ptr) {
697             let inner_layout =
698                 fx.layout_of(ptr.layout().ty.builtin_deref(true).unwrap().ty);
699             let val = CValue::by_ref(ptr.load_scalar(fx), inner_layout);
700             ret.write_cvalue(fx, val);
701         };
702         _ if intrinsic.starts_with("atomic_store"), (v ptr, c val) {
703             let dest = CPlace::for_addr(ptr, val.layout());
704             dest.write_cvalue(fx, val);
705         };
706         _ if intrinsic.starts_with("atomic_xchg"), <T> (v ptr, c src) {
707             // Read old
708             let clif_ty = fx.clif_type(T).unwrap();
709             let old = fx.bcx.ins().load(clif_ty, MemFlags::new(), ptr, 0);
710             ret.write_cvalue(fx, CValue::by_val(old, fx.layout_of(T)));
711
712             // Write new
713             let dest = CPlace::for_addr(ptr, src.layout());
714             dest.write_cvalue(fx, src);
715         };
716         _ if intrinsic.starts_with("atomic_cxchg"), <T> (v ptr, v test_old, v new) { // both atomic_cxchg_* and atomic_cxchgweak_*
717             // Read old
718             let clif_ty = fx.clif_type(T).unwrap();
719             let old = fx.bcx.ins().load(clif_ty, MemFlags::new(), ptr, 0);
720
721             // Compare
722             let is_eq = fx.bcx.ins().icmp(IntCC::Equal, old, test_old);
723             let new = crate::common::codegen_select(&mut fx.bcx, is_eq, new, old); // Keep old if not equal to test_old
724
725             // Write new
726             fx.bcx.ins().store(MemFlags::new(), new, ptr, 0);
727
728             let ret_val = CValue::by_val_pair(old, fx.bcx.ins().bint(types::I8, is_eq), ret.layout());
729             ret.write_cvalue(fx, ret_val);
730         };
731
732         _ if intrinsic.starts_with("atomic_xadd"), <T> (v ptr, v amount) {
733             atomic_binop_return_old! (fx, iadd<T>(ptr, amount) -> ret);
734         };
735         _ if intrinsic.starts_with("atomic_xsub"), <T> (v ptr, v amount) {
736             atomic_binop_return_old! (fx, isub<T>(ptr, amount) -> ret);
737         };
738         _ if intrinsic.starts_with("atomic_and"), <T> (v ptr, v src) {
739             atomic_binop_return_old! (fx, band<T>(ptr, src) -> ret);
740         };
741         _ if intrinsic.starts_with("atomic_nand"), <T> (v ptr, v src) {
742             atomic_binop_return_old! (fx, band_not<T>(ptr, src) -> ret);
743         };
744         _ if intrinsic.starts_with("atomic_or"), <T> (v ptr, v src) {
745             atomic_binop_return_old! (fx, bor<T>(ptr, src) -> ret);
746         };
747         _ if intrinsic.starts_with("atomic_xor"), <T> (v ptr, v src) {
748             atomic_binop_return_old! (fx, bxor<T>(ptr, src) -> ret);
749         };
750
751         _ if intrinsic.starts_with("atomic_max"), <T> (v ptr, v src) {
752             atomic_minmax!(fx, IntCC::SignedGreaterThan, <T> (ptr, src) -> ret);
753         };
754         _ if intrinsic.starts_with("atomic_umax"), <T> (v ptr, v src) {
755             atomic_minmax!(fx, IntCC::UnsignedGreaterThan, <T> (ptr, src) -> ret);
756         };
757         _ if intrinsic.starts_with("atomic_min"), <T> (v ptr, v src) {
758             atomic_minmax!(fx, IntCC::SignedLessThan, <T> (ptr, src) -> ret);
759         };
760         _ if intrinsic.starts_with("atomic_umin"), <T> (v ptr, v src) {
761             atomic_minmax!(fx, IntCC::UnsignedLessThan, <T> (ptr, src) -> ret);
762         };
763
764         minnumf32, (v a, v b) {
765             let val = fx.bcx.ins().fmin(a, b);
766             let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f32));
767             ret.write_cvalue(fx, val);
768         };
769         minnumf64, (v a, v b) {
770             let val = fx.bcx.ins().fmin(a, b);
771             let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f64));
772             ret.write_cvalue(fx, val);
773         };
774         maxnumf32, (v a, v b) {
775             let val = fx.bcx.ins().fmax(a, b);
776             let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f32));
777             ret.write_cvalue(fx, val);
778         };
779         maxnumf64, (v a, v b) {
780             let val = fx.bcx.ins().fmax(a, b);
781             let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f64));
782             ret.write_cvalue(fx, val);
783         };
784
785         simd_cast, (c x) {
786             ret.write_cvalue(fx, x.unchecked_cast_to(ret.layout()));
787         };
788
789         simd_eq, (c x, c y) {
790             simd_cmp!(fx, intrinsic, Equal(x, y) -> ret);
791         };
792         simd_ne, (c x, c y) {
793             simd_cmp!(fx, intrinsic, NotEqual(x, y) -> ret);
794         };
795         simd_lt, (c x, c y) {
796             simd_cmp!(fx, intrinsic, UnsignedLessThan|SignedLessThan(x, y) -> ret);
797         };
798         simd_le, (c x, c y) {
799             simd_cmp!(fx, intrinsic, UnsignedLessThanOrEqual|SignedLessThanOrEqual(x, y) -> ret);
800         };
801         simd_gt, (c x, c y) {
802             simd_cmp!(fx, intrinsic, UnsignedGreaterThan|SignedGreaterThan(x, y) -> ret);
803         };
804         simd_ge, (c x, c y) {
805             simd_cmp!(fx, intrinsic, UnsignedGreaterThanOrEqual|SignedGreaterThanOrEqual(x, y) -> ret);
806         };
807
808         simd_add, (c x, c y) {
809             simd_binop!(fx, intrinsic, iadd(x, y) -> ret);
810         };
811         simd_sub, (c x, c y) {
812             simd_binop!(fx, intrinsic, isub(x, y) -> ret);
813         };
814         simd_mul, (c x, c y) {
815             simd_binop!(fx, intrinsic, imul(x, y) -> ret);
816         };
817         simd_div, (c x, c y) {
818             simd_binop!(fx, intrinsic, udiv|sdiv(x, y) -> ret);
819         };
820         simd_rem, (c x, c y) {
821             simd_binop!(fx, intrinsic, urem|srem(x, y) -> ret);
822         };
823         simd_shl, (c x, c y) {
824             simd_binop!(fx, intrinsic, ishl(x, y) -> ret);
825         };
826         simd_shr, (c x, c y) {
827             simd_binop!(fx, intrinsic, ushr|sshr(x, y) -> ret);
828         };
829         simd_and, (c x, c y) {
830             simd_binop!(fx, intrinsic, band(x, y) -> ret);
831         };
832         simd_or, (c x, c y) {
833             simd_binop!(fx, intrinsic, bor(x, y) -> ret);
834         };
835         simd_bxor, (c x, c y) {
836             simd_binop!(fx, intrinsic, bxor(x, y) -> ret);
837         };
838
839         simd_fmin, (c x, c y) {
840             simd_binop!(fx, intrinsic, fmin(x, y) -> ret);
841         };
842         simd_fmax, (c x, c y) {
843             simd_binop!(fx, intrinsic, fmax(x, y) -> ret);
844         };
845     }
846
847     if let Some((_, dest)) = destination {
848         let ret_ebb = fx.get_ebb(dest);
849         fx.bcx.ins().jump(ret_ebb, &[]);
850     } else {
851         trap_unreachable(fx, "[corruption] Diverging intrinsic returned.");
852     }
853 }