]> git.lizzy.rs Git - rust.git/blob - src/intrinsics.rs
Fix and optimize init intrinsic
[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! atomic_binop_return_old {
63     ($fx:expr, $op:ident<$T:ident>($ptr:ident, $src:ident) -> $ret:ident) => {
64         let clif_ty = $fx.clif_type($T).unwrap();
65         let old = $fx.bcx.ins().load(clif_ty, MemFlags::new(), $ptr, 0);
66         let new = $fx.bcx.ins().$op(old, $src);
67         $fx.bcx.ins().store(MemFlags::new(), new, $ptr, 0);
68         $ret.write_cvalue($fx, CValue::ByVal(old, $fx.layout_of($T)));
69     };
70 }
71
72 macro_rules! atomic_minmax {
73     ($fx:expr, $cc:expr, <$T:ident> ($ptr:ident, $src:ident) -> $ret:ident) => {
74         // Read old
75         let clif_ty = $fx.clif_type($T).unwrap();
76         let old = $fx.bcx.ins().load(clif_ty, MemFlags::new(), $ptr, 0);
77
78         // Compare
79         let is_eq = $fx.bcx.ins().icmp(IntCC::SignedGreaterThan, old, $src);
80         let new = crate::common::codegen_select(&mut $fx.bcx, is_eq, old, $src);
81
82         // Write new
83         $fx.bcx.ins().store(MemFlags::new(), new, $ptr, 0);
84
85         let ret_val = CValue::ByVal(old, $ret.layout());
86         $ret.write_cvalue($fx, ret_val);
87     };
88 }
89
90 pub fn codegen_intrinsic_call<'a, 'tcx: 'a>(
91     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
92     def_id: DefId,
93     substs: SubstsRef<'tcx>,
94     args: Vec<CValue<'tcx>>,
95     destination: Option<(CPlace<'tcx>, BasicBlock)>,
96 ) {
97     let intrinsic = fx.tcx.item_name(def_id).as_str();
98     let intrinsic = &intrinsic[..];
99
100     let ret = match destination {
101         Some((place, _)) => place,
102         None => {
103             // Insert non returning intrinsics here
104             match intrinsic {
105                 "abort" => {
106                     trap_panic(&mut fx.bcx);
107                 }
108                 "unreachable" => {
109                     trap_unreachable(&mut fx.bcx);
110                 }
111                 _ => unimplemented!("unsupported instrinsic {}", intrinsic),
112             }
113             return;
114         }
115     };
116
117     let u64_layout = fx.layout_of(fx.tcx.types.u64);
118     let usize_layout = fx.layout_of(fx.tcx.types.usize);
119
120     intrinsic_match! {
121         fx, intrinsic, substs, args,
122
123         assume, (c _a) {};
124         likely | unlikely, (c a) {
125             ret.write_cvalue(fx, a);
126         };
127         breakpoint, () {
128             fx.bcx.ins().debugtrap();
129         };
130         copy | copy_nonoverlapping, <elem_ty> (v src, v dst, v count) {
131             let elem_size: u64 = fx.layout_of(elem_ty).size.bytes();
132             let elem_size = fx
133                 .bcx
134                 .ins()
135                 .iconst(fx.pointer_type, elem_size as i64);
136             assert_eq!(args.len(), 3);
137             let byte_amount = fx.bcx.ins().imul(count, elem_size);
138
139             if intrinsic.ends_with("_nonoverlapping") {
140                 fx.bcx.call_memcpy(fx.module.target_config(), dst, src, byte_amount);
141             } else {
142                 fx.bcx.call_memmove(fx.module.target_config(), dst, src, byte_amount);
143             }
144         };
145         discriminant_value, (c val) {
146             let pointee_layout = fx.layout_of(val.layout().ty.builtin_deref(true).unwrap().ty);
147             let place = CPlace::Addr(val.load_scalar(fx), None, pointee_layout);
148             let discr = crate::base::trans_get_discriminant(fx, place, ret.layout());
149             ret.write_cvalue(fx, discr);
150         };
151         size_of, <T> () {
152             let size_of = fx.layout_of(T).size.bytes();
153             let size_of = CValue::const_val(fx, usize_layout.ty, size_of as i64);
154             ret.write_cvalue(fx, size_of);
155         };
156         size_of_val, <T> (c ptr) {
157             let layout = fx.layout_of(T);
158             let size = if layout.is_unsized() {
159                 let (_ptr, info) = ptr.load_scalar_pair(fx);
160                 let (size, _align) = crate::unsize::size_and_align_of_dst(fx, layout.ty, info);
161                 size
162             } else {
163                 fx
164                     .bcx
165                     .ins()
166                     .iconst(fx.pointer_type, layout.size.bytes() as i64)
167             };
168             ret.write_cvalue(fx, CValue::ByVal(size, usize_layout));
169         };
170         min_align_of, <T> () {
171             let min_align = fx.layout_of(T).align.abi.bytes();
172             let min_align = CValue::const_val(fx, usize_layout.ty, min_align as i64);
173             ret.write_cvalue(fx, min_align);
174         };
175         min_align_of_val, <T> (c ptr) {
176             let layout = fx.layout_of(T);
177             let align = if layout.is_unsized() {
178                 let (_ptr, info) = ptr.load_scalar_pair(fx);
179                 let (_size, align) = crate::unsize::size_and_align_of_dst(fx, layout.ty, info);
180                 align
181             } else {
182                 fx
183                     .bcx
184                     .ins()
185                     .iconst(fx.pointer_type, layout.align.abi.bytes() as i64)
186             };
187             ret.write_cvalue(fx, CValue::ByVal(align, usize_layout));
188         };
189         type_id, <T> () {
190             let type_id = fx.tcx.type_id_hash(T);
191             let type_id = CValue::const_val(fx, u64_layout.ty, type_id as i64);
192             ret.write_cvalue(fx, type_id);
193         };
194         _ if intrinsic.starts_with("unchecked_") || intrinsic == "exact_div", (c x, c y) {
195             // FIXME trap on overflow
196             let bin_op = match intrinsic {
197                 "unchecked_div" | "exact_div" => BinOp::Div,
198                 "unchecked_rem" => BinOp::Rem,
199                 "unchecked_shl" => BinOp::Shl,
200                 "unchecked_shr" => BinOp::Shr,
201                 _ => unimplemented!("intrinsic {}", intrinsic),
202             };
203             let res = match ret.layout().ty.sty {
204                 ty::Uint(_) => crate::base::trans_int_binop(
205                     fx,
206                     bin_op,
207                     x,
208                     y,
209                     ret.layout().ty,
210                     false,
211                 ),
212                 ty::Int(_) => crate::base::trans_int_binop(
213                     fx,
214                     bin_op,
215                     x,
216                     y,
217                     ret.layout().ty,
218                     true,
219                 ),
220                 _ => panic!(),
221             };
222             ret.write_cvalue(fx, res);
223         };
224         _ if intrinsic.ends_with("_with_overflow"), <T> (c x, c y) {
225             assert_eq!(x.layout().ty, y.layout().ty);
226             let bin_op = match intrinsic {
227                 "add_with_overflow" => BinOp::Add,
228                 "sub_with_overflow" => BinOp::Sub,
229                 "mul_with_overflow" => BinOp::Mul,
230                 _ => unimplemented!("intrinsic {}", intrinsic),
231             };
232             let res = match T.sty {
233                 ty::Uint(_) => crate::base::trans_checked_int_binop(
234                     fx,
235                     bin_op,
236                     x,
237                     y,
238                     ret.layout().ty,
239                     false,
240                 ),
241                 ty::Int(_) => crate::base::trans_checked_int_binop(
242                     fx,
243                     bin_op,
244                     x,
245                     y,
246                     ret.layout().ty,
247                     true,
248                 ),
249                 _ => panic!(),
250             };
251             ret.write_cvalue(fx, res);
252         };
253         _ if intrinsic.starts_with("overflowing_"), <T> (c x, c y) {
254             assert_eq!(x.layout().ty, y.layout().ty);
255             let bin_op = match intrinsic {
256                 "overflowing_add" => BinOp::Add,
257                 "overflowing_sub" => BinOp::Sub,
258                 "overflowing_mul" => BinOp::Mul,
259                 _ => unimplemented!("intrinsic {}", intrinsic),
260             };
261             let res = match T.sty {
262                 ty::Uint(_) => crate::base::trans_int_binop(
263                     fx,
264                     bin_op,
265                     x,
266                     y,
267                     ret.layout().ty,
268                     false,
269                 ),
270                 ty::Int(_) => crate::base::trans_int_binop(
271                     fx,
272                     bin_op,
273                     x,
274                     y,
275                     ret.layout().ty,
276                     true,
277                 ),
278                 _ => panic!(),
279             };
280             ret.write_cvalue(fx, res);
281         };
282         _ if intrinsic.starts_with("saturating_"), <T> (c x, c y) {
283             // FIXME implement saturating behavior
284             assert_eq!(x.layout().ty, y.layout().ty);
285             let bin_op = match intrinsic {
286                 "saturating_add" => BinOp::Add,
287                 "saturating_sub" => BinOp::Sub,
288                 "saturating_mul" => BinOp::Mul,
289                 _ => unimplemented!("intrinsic {}", intrinsic),
290             };
291             let res = match T.sty {
292                 ty::Uint(_) => crate::base::trans_int_binop(
293                     fx,
294                     bin_op,
295                     x,
296                     y,
297                     ret.layout().ty,
298                     false,
299                 ),
300                 ty::Int(_) => crate::base::trans_int_binop(
301                     fx,
302                     bin_op,
303                     x,
304                     y,
305                     ret.layout().ty,
306                     true,
307                 ),
308                 _ => panic!(),
309             };
310             ret.write_cvalue(fx, res);
311         };
312         rotate_left, <T>(v x, v y) {
313             let layout = fx.layout_of(T);
314             let res = fx.bcx.ins().rotl(x, y);
315             ret.write_cvalue(fx, CValue::ByVal(res, layout));
316         };
317         rotate_right, <T>(v x, v y) {
318             let layout = fx.layout_of(T);
319             let res = fx.bcx.ins().rotr(x, y);
320             ret.write_cvalue(fx, CValue::ByVal(res, layout));
321         };
322
323         // The only difference between offset and arith_offset is regarding UB. Because Cranelift
324         // doesn't have UB both are codegen'ed the same way
325         offset | arith_offset, (c base, v offset) {
326             let pointee_ty = base.layout().ty.builtin_deref(true).unwrap().ty;
327             let pointee_size = fx.layout_of(pointee_ty).size.bytes();
328             let ptr_diff = fx.bcx.ins().imul_imm(offset, pointee_size as i64);
329             let base_val = base.load_scalar(fx);
330             let res = fx.bcx.ins().iadd(base_val, ptr_diff);
331             ret.write_cvalue(fx, CValue::ByVal(res, args[0].layout()));
332         };
333
334         transmute, <src_ty, dst_ty> (c from) {
335             assert_eq!(from.layout().ty, src_ty);
336             let addr = from.force_stack(fx);
337             let dst_layout = fx.layout_of(dst_ty);
338             ret.write_cvalue(fx, CValue::ByRef(addr, dst_layout))
339         };
340         init, () {
341             if ret.layout().abi == Abi::Uninhabited {
342                 crate::trap::trap_panic(&mut fx.bcx);
343                 return;
344             }
345
346             match ret {
347                 CPlace::NoPlace(_layout) => {}
348                 CPlace::Var(var, layout) => {
349                     let clif_ty = fx.clif_type(layout.ty).unwrap();
350                     let val = match clif_ty {
351                         types::I8 | types::I16 | types::I32 | types::I64 => fx.bcx.ins().iconst(clif_ty, 0),
352                         types::F32 => {
353                             let zero = fx.bcx.ins().iconst(types::I32, 0);
354                             fx.bcx.ins().bitcast(types::F32, zero)
355                         }
356                         types::F64 => {
357                             let zero = fx.bcx.ins().iconst(types::I64, 0);
358                             fx.bcx.ins().bitcast(types::F64, zero)
359                         }
360                         _ => panic!("clif_type returned {}", clif_ty),
361                     };
362                     fx.bcx.def_var(mir_var(var), val);
363                 }
364                 _ => {
365                     let addr = ret.to_addr(fx);
366                     let layout = ret.layout();
367                     fx.bcx.emit_small_memset(fx.module.target_config(), addr, 0, layout.size.bytes(), 1);
368                 }
369             }
370         };
371         write_bytes, (c dst, v val, v count) {
372             let pointee_ty = dst.layout().ty.builtin_deref(true).unwrap().ty;
373             let pointee_size = fx.layout_of(pointee_ty).size.bytes();
374             let count = fx.bcx.ins().imul_imm(count, pointee_size as i64);
375             let dst_ptr = dst.load_scalar(fx);
376             fx.bcx.call_memset(fx.module.target_config(), dst_ptr, val, count);
377         };
378         uninit, <T> () {
379             if ret.layout().abi == Abi::Uninhabited {
380                 crate::trap::trap_panic(&mut fx.bcx);
381                 return;
382             }
383
384             let uninit_place = CPlace::new_stack_slot(fx, T);
385             let uninit_val = uninit_place.to_cvalue(fx);
386             ret.write_cvalue(fx, uninit_val);
387         };
388         ctlz | ctlz_nonzero, <T> (v arg) {
389             let res = CValue::ByVal(fx.bcx.ins().clz(arg), fx.layout_of(T));
390             ret.write_cvalue(fx, res);
391         };
392         cttz | cttz_nonzero, <T> (v arg) {
393             let res = CValue::ByVal(fx.bcx.ins().ctz(arg), fx.layout_of(T));
394             ret.write_cvalue(fx, res);
395         };
396         ctpop, <T> (v arg) {
397             let res = CValue::ByVal(fx.bcx.ins().popcnt(arg), fx.layout_of(T));
398             ret.write_cvalue(fx, res);
399         };
400         bitreverse, <T> (v arg) {
401             let res = CValue::ByVal(fx.bcx.ins().bitrev(arg), fx.layout_of(T));
402             ret.write_cvalue(fx, res);
403         };
404         needs_drop, <T> () {
405             let needs_drop = if T.needs_drop(fx.tcx, ParamEnv::reveal_all()) {
406                 1
407             } else {
408                 0
409             };
410             let needs_drop = CValue::const_val(fx, fx.tcx.types.bool, needs_drop);
411             ret.write_cvalue(fx, needs_drop);
412         };
413         panic_if_uninhabited, <T> () {
414             if fx.layout_of(T).abi.is_uninhabited() {
415                 crate::trap::trap_panic(&mut fx.bcx);
416                 return;
417             }
418         };
419
420         _ if intrinsic.starts_with("atomic_fence"), () {};
421         _ if intrinsic.starts_with("atomic_singlethreadfence"), () {};
422         _ if intrinsic.starts_with("atomic_load"), (c ptr) {
423             let inner_layout =
424                 fx.layout_of(ptr.layout().ty.builtin_deref(true).unwrap().ty);
425             let val = CValue::ByRef(ptr.load_scalar(fx), inner_layout);
426             ret.write_cvalue(fx, val);
427         };
428         _ if intrinsic.starts_with("atomic_store"), (v ptr, c val) {
429             let dest = CPlace::Addr(ptr, None, val.layout());
430             dest.write_cvalue(fx, val);
431         };
432         _ if intrinsic.starts_with("atomic_xchg"), <T> (v ptr, c src) {
433             // Read old
434             let clif_ty = fx.clif_type(T).unwrap();
435             let old = fx.bcx.ins().load(clif_ty, MemFlags::new(), ptr, 0);
436             ret.write_cvalue(fx, CValue::ByVal(old, fx.layout_of(T)));
437
438             // Write new
439             let dest = CPlace::Addr(ptr, None, src.layout());
440             dest.write_cvalue(fx, src);
441         };
442         _ if intrinsic.starts_with("atomic_cxchg"), <T> (v ptr, v test_old, v new) { // both atomic_cxchg_* and atomic_cxchgweak_*
443             // Read old
444             let clif_ty = fx.clif_type(T).unwrap();
445             let old = fx.bcx.ins().load(clif_ty, MemFlags::new(), ptr, 0);
446
447             // Compare
448             let is_eq = fx.bcx.ins().icmp(IntCC::Equal, old, test_old);
449             let new = crate::common::codegen_select(&mut fx.bcx, is_eq, new, old); // Keep old if not equal to test_old
450
451             // Write new
452             fx.bcx.ins().store(MemFlags::new(), new, ptr, 0);
453
454             let ret_val = CValue::ByValPair(old, fx.bcx.ins().bint(types::I8, is_eq), ret.layout());
455             ret.write_cvalue(fx, ret_val);
456         };
457
458         _ if intrinsic.starts_with("atomic_xadd"), <T> (v ptr, v amount) {
459             atomic_binop_return_old! (fx, iadd<T>(ptr, amount) -> ret);
460         };
461         _ if intrinsic.starts_with("atomic_xsub"), <T> (v ptr, v amount) {
462             atomic_binop_return_old! (fx, isub<T>(ptr, amount) -> ret);
463         };
464         _ if intrinsic.starts_with("atomic_and"), <T> (v ptr, v src) {
465             atomic_binop_return_old! (fx, band<T>(ptr, src) -> ret);
466         };
467         _ if intrinsic.starts_with("atomic_nand"), <T> (v ptr, v src) {
468             atomic_binop_return_old! (fx, band_not<T>(ptr, src) -> ret);
469         };
470         _ if intrinsic.starts_with("atomic_or"), <T> (v ptr, v src) {
471             atomic_binop_return_old! (fx, bor<T>(ptr, src) -> ret);
472         };
473         _ if intrinsic.starts_with("atomic_xor"), <T> (v ptr, v src) {
474             atomic_binop_return_old! (fx, bxor<T>(ptr, src) -> ret);
475         };
476
477         _ if intrinsic.starts_with("atomic_max"), <T> (v ptr, v src) {
478             atomic_minmax!(fx, IntCC::SignedGreaterThan, <T> (ptr, src) -> ret);
479         };
480         _ if intrinsic.starts_with("atomic_umax"), <T> (v ptr, v src) {
481             atomic_minmax!(fx, IntCC::UnsignedGreaterThan, <T> (ptr, src) -> ret);
482         };
483         _ if intrinsic.starts_with("atomic_min"), <T> (v ptr, v src) {
484             atomic_minmax!(fx, IntCC::SignedLessThan, <T> (ptr, src) -> ret);
485         };
486         _ if intrinsic.starts_with("atomic_umin"), <T> (v ptr, v src) {
487             atomic_minmax!(fx, IntCC::UnsignedLessThan, <T> (ptr, src) -> ret);
488         };
489     }
490
491     if let Some((_, dest)) = destination {
492         let ret_ebb = fx.get_ebb(dest);
493         fx.bcx.ins().jump(ret_ebb, &[]);
494     } else {
495         trap_unreachable(&mut fx.bcx);
496     }
497 }