]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/intrinsic.rs
Auto merge of #67808 - Marwes:projection_normalization_recurse, r=nikomatsakis
[rust.git] / src / librustc_typeck / check / intrinsic.rs
1 //! Type-checking for the rust-intrinsic and platform-intrinsic
2 //! intrinsics that the compiler exposes.
3
4 use crate::require_same_types;
5 use rustc::traits::{ObligationCause, ObligationCauseCode};
6 use rustc::ty::subst::Subst;
7 use rustc::ty::{self, Ty, TyCtxt};
8
9 use rustc_span::symbol::Symbol;
10 use rustc_target::spec::abi::Abi;
11
12 use rustc::hir;
13
14 use rustc_error_codes::*;
15
16 use std::iter;
17
18 fn equate_intrinsic_type<'tcx>(
19     tcx: TyCtxt<'tcx>,
20     it: &hir::ForeignItem<'_>,
21     n_tps: usize,
22     abi: Abi,
23     safety: hir::Unsafety,
24     inputs: Vec<Ty<'tcx>>,
25     output: Ty<'tcx>,
26 ) {
27     let def_id = tcx.hir().local_def_id(it.hir_id);
28
29     match it.kind {
30         hir::ForeignItemKind::Fn(..) => {}
31         _ => {
32             struct_span_err!(tcx.sess, it.span, E0622, "intrinsic must be a function")
33                 .span_label(it.span, "expected a function")
34                 .emit();
35             return;
36         }
37     }
38
39     let i_n_tps = tcx.generics_of(def_id).own_counts().types;
40     if i_n_tps != n_tps {
41         let span = match it.kind {
42             hir::ForeignItemKind::Fn(_, _, ref generics) => generics.span,
43             _ => bug!(),
44         };
45
46         struct_span_err!(
47             tcx.sess,
48             span,
49             E0094,
50             "intrinsic has wrong number of type \
51                          parameters: found {}, expected {}",
52             i_n_tps,
53             n_tps
54         )
55         .span_label(span, format!("expected {} type parameter", n_tps))
56         .emit();
57         return;
58     }
59
60     let fty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
61         inputs.into_iter(),
62         output,
63         false,
64         safety,
65         abi,
66     )));
67     let cause = ObligationCause::new(it.span, it.hir_id, ObligationCauseCode::IntrinsicType);
68     require_same_types(tcx, &cause, tcx.mk_fn_ptr(tcx.fn_sig(def_id)), fty);
69 }
70
71 /// Returns `true` if the given intrinsic is unsafe to call or not.
72 pub fn intrinsic_operation_unsafety(intrinsic: &str) -> hir::Unsafety {
73     match intrinsic {
74         "size_of" | "min_align_of" | "needs_drop" | "caller_location" | "size_of_val"
75         | "min_align_of_val" | "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow"
76         | "wrapping_add" | "wrapping_sub" | "wrapping_mul" | "saturating_add"
77         | "saturating_sub" | "rotate_left" | "rotate_right" | "ctpop" | "ctlz" | "cttz"
78         | "bswap" | "bitreverse" | "discriminant_value" | "type_id" | "likely" | "unlikely"
79         | "minnumf32" | "minnumf64" | "maxnumf32" | "maxnumf64" | "type_name" => {
80             hir::Unsafety::Normal
81         }
82         _ => hir::Unsafety::Unsafe,
83     }
84 }
85
86 /// Remember to add all intrinsics here, in librustc_codegen_llvm/intrinsic.rs,
87 /// and in libcore/intrinsics.rs
88 pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) {
89     let param = |n| tcx.mk_ty_param(n, Symbol::intern(&format!("P{}", n)));
90     let name = it.ident.as_str();
91
92     let mk_va_list_ty = |mutbl| {
93         tcx.lang_items().va_list().map(|did| {
94             let region = tcx.mk_region(ty::ReLateBound(ty::INNERMOST, ty::BrAnon(0)));
95             let env_region = ty::ReLateBound(ty::INNERMOST, ty::BrEnv);
96             let va_list_ty = tcx.type_of(did).subst(tcx, &[region.into()]);
97             (
98                 tcx.mk_ref(tcx.mk_region(env_region), ty::TypeAndMut { ty: va_list_ty, mutbl }),
99                 va_list_ty,
100             )
101         })
102     };
103
104     let (n_tps, inputs, output, unsafety) = if name.starts_with("atomic_") {
105         let split: Vec<&str> = name.split('_').collect();
106         assert!(split.len() >= 2, "Atomic intrinsic in an incorrect format");
107
108         //We only care about the operation here
109         let (n_tps, inputs, output) = match split[1] {
110             "cxchg" | "cxchgweak" => (
111                 1,
112                 vec![tcx.mk_mut_ptr(param(0)), param(0), param(0)],
113                 tcx.intern_tup(&[param(0), tcx.types.bool]),
114             ),
115             "load" => (1, vec![tcx.mk_imm_ptr(param(0))], param(0)),
116             "store" => (1, vec![tcx.mk_mut_ptr(param(0)), param(0)], tcx.mk_unit()),
117
118             "xchg" | "xadd" | "xsub" | "and" | "nand" | "or" | "xor" | "max" | "min" | "umax"
119             | "umin" => (1, vec![tcx.mk_mut_ptr(param(0)), param(0)], param(0)),
120             "fence" | "singlethreadfence" => (0, Vec::new(), tcx.mk_unit()),
121             op => {
122                 struct_span_err!(
123                     tcx.sess,
124                     it.span,
125                     E0092,
126                     "unrecognized atomic operation function: `{}`",
127                     op
128                 )
129                 .span_label(it.span, "unrecognized atomic operation")
130                 .emit();
131                 return;
132             }
133         };
134         (n_tps, inputs, output, hir::Unsafety::Unsafe)
135     } else if &name[..] == "abort" || &name[..] == "unreachable" {
136         (0, Vec::new(), tcx.types.never, hir::Unsafety::Unsafe)
137     } else {
138         let unsafety = intrinsic_operation_unsafety(&name[..]);
139         let (n_tps, inputs, output) = match &name[..] {
140             "breakpoint" => (0, Vec::new(), tcx.mk_unit()),
141             "size_of" | "pref_align_of" | "min_align_of" => (1, Vec::new(), tcx.types.usize),
142             "size_of_val" | "min_align_of_val" => (
143                 1,
144                 vec![tcx.mk_imm_ref(
145                     tcx.mk_region(ty::ReLateBound(ty::INNERMOST, ty::BrAnon(0))),
146                     param(0),
147                 )],
148                 tcx.types.usize,
149             ),
150             "rustc_peek" => (1, vec![param(0)], param(0)),
151             "caller_location" => (0, vec![], tcx.caller_location_ty()),
152             "panic_if_uninhabited" => (1, Vec::new(), tcx.mk_unit()),
153             "init" => (1, Vec::new(), param(0)),
154             "uninit" => (1, Vec::new(), param(0)),
155             "forget" => (1, vec![param(0)], tcx.mk_unit()),
156             "transmute" => (2, vec![param(0)], param(1)),
157             "move_val_init" => (1, vec![tcx.mk_mut_ptr(param(0)), param(0)], tcx.mk_unit()),
158             "prefetch_read_data"
159             | "prefetch_write_data"
160             | "prefetch_read_instruction"
161             | "prefetch_write_instruction" => (
162                 1,
163                 vec![
164                     tcx.mk_ptr(ty::TypeAndMut { ty: param(0), mutbl: hir::Mutability::Not }),
165                     tcx.types.i32,
166                 ],
167                 tcx.mk_unit(),
168             ),
169             "drop_in_place" => (1, vec![tcx.mk_mut_ptr(param(0))], tcx.mk_unit()),
170             "needs_drop" => (1, Vec::new(), tcx.types.bool),
171
172             "type_name" => (1, Vec::new(), tcx.mk_static_str()),
173             "type_id" => (1, Vec::new(), tcx.types.u64),
174             "offset" | "arith_offset" => (
175                 1,
176                 vec![
177                     tcx.mk_ptr(ty::TypeAndMut { ty: param(0), mutbl: hir::Mutability::Not }),
178                     tcx.types.isize,
179                 ],
180                 tcx.mk_ptr(ty::TypeAndMut { ty: param(0), mutbl: hir::Mutability::Not }),
181             ),
182             "copy" | "copy_nonoverlapping" => (
183                 1,
184                 vec![
185                     tcx.mk_ptr(ty::TypeAndMut { ty: param(0), mutbl: hir::Mutability::Not }),
186                     tcx.mk_ptr(ty::TypeAndMut { ty: param(0), mutbl: hir::Mutability::Mut }),
187                     tcx.types.usize,
188                 ],
189                 tcx.mk_unit(),
190             ),
191             "volatile_copy_memory" | "volatile_copy_nonoverlapping_memory" => (
192                 1,
193                 vec![
194                     tcx.mk_ptr(ty::TypeAndMut { ty: param(0), mutbl: hir::Mutability::Mut }),
195                     tcx.mk_ptr(ty::TypeAndMut { ty: param(0), mutbl: hir::Mutability::Not }),
196                     tcx.types.usize,
197                 ],
198                 tcx.mk_unit(),
199             ),
200             "write_bytes" | "volatile_set_memory" => (
201                 1,
202                 vec![
203                     tcx.mk_ptr(ty::TypeAndMut { ty: param(0), mutbl: hir::Mutability::Mut }),
204                     tcx.types.u8,
205                     tcx.types.usize,
206                 ],
207                 tcx.mk_unit(),
208             ),
209             "sqrtf32" => (0, vec![tcx.types.f32], tcx.types.f32),
210             "sqrtf64" => (0, vec![tcx.types.f64], tcx.types.f64),
211             "powif32" => (0, vec![tcx.types.f32, tcx.types.i32], tcx.types.f32),
212             "powif64" => (0, vec![tcx.types.f64, tcx.types.i32], tcx.types.f64),
213             "sinf32" => (0, vec![tcx.types.f32], tcx.types.f32),
214             "sinf64" => (0, vec![tcx.types.f64], tcx.types.f64),
215             "cosf32" => (0, vec![tcx.types.f32], tcx.types.f32),
216             "cosf64" => (0, vec![tcx.types.f64], tcx.types.f64),
217             "powf32" => (0, vec![tcx.types.f32, tcx.types.f32], tcx.types.f32),
218             "powf64" => (0, vec![tcx.types.f64, tcx.types.f64], tcx.types.f64),
219             "expf32" => (0, vec![tcx.types.f32], tcx.types.f32),
220             "expf64" => (0, vec![tcx.types.f64], tcx.types.f64),
221             "exp2f32" => (0, vec![tcx.types.f32], tcx.types.f32),
222             "exp2f64" => (0, vec![tcx.types.f64], tcx.types.f64),
223             "logf32" => (0, vec![tcx.types.f32], tcx.types.f32),
224             "logf64" => (0, vec![tcx.types.f64], tcx.types.f64),
225             "log10f32" => (0, vec![tcx.types.f32], tcx.types.f32),
226             "log10f64" => (0, vec![tcx.types.f64], tcx.types.f64),
227             "log2f32" => (0, vec![tcx.types.f32], tcx.types.f32),
228             "log2f64" => (0, vec![tcx.types.f64], tcx.types.f64),
229             "fmaf32" => (0, vec![tcx.types.f32, tcx.types.f32, tcx.types.f32], tcx.types.f32),
230             "fmaf64" => (0, vec![tcx.types.f64, tcx.types.f64, tcx.types.f64], tcx.types.f64),
231             "fabsf32" => (0, vec![tcx.types.f32], tcx.types.f32),
232             "fabsf64" => (0, vec![tcx.types.f64], tcx.types.f64),
233             "minnumf32" => (0, vec![tcx.types.f32, tcx.types.f32], tcx.types.f32),
234             "minnumf64" => (0, vec![tcx.types.f64, tcx.types.f64], tcx.types.f64),
235             "maxnumf32" => (0, vec![tcx.types.f32, tcx.types.f32], tcx.types.f32),
236             "maxnumf64" => (0, vec![tcx.types.f64, tcx.types.f64], tcx.types.f64),
237             "copysignf32" => (0, vec![tcx.types.f32, tcx.types.f32], tcx.types.f32),
238             "copysignf64" => (0, vec![tcx.types.f64, tcx.types.f64], tcx.types.f64),
239             "floorf32" => (0, vec![tcx.types.f32], tcx.types.f32),
240             "floorf64" => (0, vec![tcx.types.f64], tcx.types.f64),
241             "ceilf32" => (0, vec![tcx.types.f32], tcx.types.f32),
242             "ceilf64" => (0, vec![tcx.types.f64], tcx.types.f64),
243             "truncf32" => (0, vec![tcx.types.f32], tcx.types.f32),
244             "truncf64" => (0, vec![tcx.types.f64], tcx.types.f64),
245             "rintf32" => (0, vec![tcx.types.f32], tcx.types.f32),
246             "rintf64" => (0, vec![tcx.types.f64], tcx.types.f64),
247             "nearbyintf32" => (0, vec![tcx.types.f32], tcx.types.f32),
248             "nearbyintf64" => (0, vec![tcx.types.f64], tcx.types.f64),
249             "roundf32" => (0, vec![tcx.types.f32], tcx.types.f32),
250             "roundf64" => (0, vec![tcx.types.f64], tcx.types.f64),
251
252             "volatile_load" | "unaligned_volatile_load" => {
253                 (1, vec![tcx.mk_imm_ptr(param(0))], param(0))
254             }
255             "volatile_store" | "unaligned_volatile_store" => {
256                 (1, vec![tcx.mk_mut_ptr(param(0)), param(0)], tcx.mk_unit())
257             }
258
259             "ctpop" | "ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" | "bswap"
260             | "bitreverse" => (1, vec![param(0)], param(0)),
261
262             "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" => {
263                 (1, vec![param(0), param(0)], tcx.intern_tup(&[param(0), tcx.types.bool]))
264             }
265
266             "ptr_offset_from" => {
267                 (1, vec![tcx.mk_imm_ptr(param(0)), tcx.mk_imm_ptr(param(0))], tcx.types.isize)
268             }
269             "unchecked_div" | "unchecked_rem" | "exact_div" => {
270                 (1, vec![param(0), param(0)], param(0))
271             }
272             "unchecked_shl" | "unchecked_shr" | "rotate_left" | "rotate_right" => {
273                 (1, vec![param(0), param(0)], param(0))
274             }
275             "unchecked_add" | "unchecked_sub" | "unchecked_mul" => {
276                 (1, vec![param(0), param(0)], param(0))
277             }
278             "wrapping_add" | "wrapping_sub" | "wrapping_mul" => {
279                 (1, vec![param(0), param(0)], param(0))
280             }
281             "saturating_add" | "saturating_sub" => (1, vec![param(0), param(0)], param(0)),
282             "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => {
283                 (1, vec![param(0), param(0)], param(0))
284             }
285             "float_to_int_approx_unchecked" => (2, vec![param(0)], param(1)),
286
287             "assume" => (0, vec![tcx.types.bool], tcx.mk_unit()),
288             "likely" => (0, vec![tcx.types.bool], tcx.types.bool),
289             "unlikely" => (0, vec![tcx.types.bool], tcx.types.bool),
290
291             "discriminant_value" => (
292                 1,
293                 vec![tcx.mk_imm_ref(
294                     tcx.mk_region(ty::ReLateBound(ty::INNERMOST, ty::BrAnon(0))),
295                     param(0),
296                 )],
297                 tcx.types.u64,
298             ),
299
300             "try" => {
301                 let mut_u8 = tcx.mk_mut_ptr(tcx.types.u8);
302                 let fn_ty = ty::Binder::bind(tcx.mk_fn_sig(
303                     iter::once(mut_u8),
304                     tcx.mk_unit(),
305                     false,
306                     hir::Unsafety::Normal,
307                     Abi::Rust,
308                 ));
309                 (0, vec![tcx.mk_fn_ptr(fn_ty), mut_u8, mut_u8], tcx.types.i32)
310             }
311
312             "va_start" | "va_end" => match mk_va_list_ty(hir::Mutability::Mut) {
313                 Some((va_list_ref_ty, _)) => (0, vec![va_list_ref_ty], tcx.mk_unit()),
314                 None => bug!("`va_list` language item needed for C-variadic intrinsics"),
315             },
316
317             "va_copy" => match mk_va_list_ty(hir::Mutability::Not) {
318                 Some((va_list_ref_ty, va_list_ty)) => {
319                     let va_list_ptr_ty = tcx.mk_mut_ptr(va_list_ty);
320                     (0, vec![va_list_ptr_ty, va_list_ref_ty], tcx.mk_unit())
321                 }
322                 None => bug!("`va_list` language item needed for C-variadic intrinsics"),
323             },
324
325             "va_arg" => match mk_va_list_ty(hir::Mutability::Mut) {
326                 Some((va_list_ref_ty, _)) => (1, vec![va_list_ref_ty], param(0)),
327                 None => bug!("`va_list` language item needed for C-variadic intrinsics"),
328             },
329
330             "nontemporal_store" => (1, vec![tcx.mk_mut_ptr(param(0)), param(0)], tcx.mk_unit()),
331
332             "miri_start_panic" => {
333                 // FIXME - the relevant types aren't lang items,
334                 // so it's not trivial to check this
335                 return;
336             }
337
338             ref other => {
339                 struct_span_err!(
340                     tcx.sess,
341                     it.span,
342                     E0093,
343                     "unrecognized intrinsic function: `{}`",
344                     *other
345                 )
346                 .span_label(it.span, "unrecognized intrinsic")
347                 .emit();
348                 return;
349             }
350         };
351         (n_tps, inputs, output, unsafety)
352     };
353     equate_intrinsic_type(tcx, it, n_tps, Abi::RustIntrinsic, unsafety, inputs, output)
354 }
355
356 /// Type-check `extern "platform-intrinsic" { ... }` functions.
357 pub fn check_platform_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) {
358     let param = |n| {
359         let name = Symbol::intern(&format!("P{}", n));
360         tcx.mk_ty_param(n, name)
361     };
362
363     let name = it.ident.as_str();
364
365     let (n_tps, inputs, output) = match &*name {
366         "simd_eq" | "simd_ne" | "simd_lt" | "simd_le" | "simd_gt" | "simd_ge" => {
367             (2, vec![param(0), param(0)], param(1))
368         }
369         "simd_add"
370         | "simd_sub"
371         | "simd_mul"
372         | "simd_rem"
373         | "simd_div"
374         | "simd_shl"
375         | "simd_shr"
376         | "simd_and"
377         | "simd_or"
378         | "simd_xor"
379         | "simd_fmin"
380         | "simd_fmax"
381         | "simd_fpow"
382         | "simd_saturating_add"
383         | "simd_saturating_sub" => (1, vec![param(0), param(0)], param(0)),
384         "simd_fsqrt" | "simd_fsin" | "simd_fcos" | "simd_fexp" | "simd_fexp2" | "simd_flog2"
385         | "simd_flog10" | "simd_flog" | "simd_fabs" | "simd_floor" | "simd_ceil" => {
386             (1, vec![param(0)], param(0))
387         }
388         "simd_fpowi" => (1, vec![param(0), tcx.types.i32], param(0)),
389         "simd_fma" => (1, vec![param(0), param(0), param(0)], param(0)),
390         "simd_gather" => (3, vec![param(0), param(1), param(2)], param(0)),
391         "simd_scatter" => (3, vec![param(0), param(1), param(2)], tcx.mk_unit()),
392         "simd_insert" => (2, vec![param(0), tcx.types.u32, param(1)], param(0)),
393         "simd_extract" => (2, vec![param(0), tcx.types.u32], param(1)),
394         "simd_cast" => (2, vec![param(0)], param(1)),
395         "simd_bitmask" => (2, vec![param(0)], param(1)),
396         "simd_select" | "simd_select_bitmask" => (2, vec![param(0), param(1), param(1)], param(1)),
397         "simd_reduce_all" | "simd_reduce_any" => (1, vec![param(0)], tcx.types.bool),
398         "simd_reduce_add_ordered" | "simd_reduce_mul_ordered" => {
399             (2, vec![param(0), param(1)], param(1))
400         }
401         "simd_reduce_add_unordered"
402         | "simd_reduce_mul_unordered"
403         | "simd_reduce_and"
404         | "simd_reduce_or"
405         | "simd_reduce_xor"
406         | "simd_reduce_min"
407         | "simd_reduce_max"
408         | "simd_reduce_min_nanless"
409         | "simd_reduce_max_nanless" => (2, vec![param(0)], param(1)),
410         name if name.starts_with("simd_shuffle") => match name["simd_shuffle".len()..].parse() {
411             Ok(n) => {
412                 let params = vec![param(0), param(0), tcx.mk_array(tcx.types.u32, n)];
413                 (2, params, param(1))
414             }
415             Err(_) => {
416                 span_err!(
417                     tcx.sess,
418                     it.span,
419                     E0439,
420                     "invalid `simd_shuffle`, needs length: `{}`",
421                     name
422                 );
423                 return;
424             }
425         },
426         _ => {
427             let msg = format!("unrecognized platform-specific intrinsic function: `{}`", name);
428             tcx.sess.span_err(it.span, &msg);
429             return;
430         }
431     };
432
433     equate_intrinsic_type(
434         tcx,
435         it,
436         n_tps,
437         Abi::PlatformIntrinsic,
438         hir::Unsafety::Unsafe,
439         inputs,
440         output,
441     )
442 }