]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/intrinsic.rs
Rollup merge of #35980 - kyrias:E0094-underline, r=jonathandturner
[rust.git] / src / librustc_typeck / check / intrinsic.rs
1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Type-checking for the rust-intrinsic and platform-intrinsic
12 //! intrinsics that the compiler exposes.
13
14 use intrinsics;
15 use rustc::infer::TypeOrigin;
16 use rustc::ty::subst::Substs;
17 use rustc::ty::FnSig;
18 use rustc::ty::{self, Ty};
19 use {CrateCtxt, require_same_types};
20
21 use std::collections::{HashMap};
22 use syntax::abi::Abi;
23 use syntax::ast;
24 use syntax::parse::token;
25 use syntax_pos::Span;
26
27 use rustc::hir;
28
29 fn equate_intrinsic_type<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
30                                    it: &hir::ForeignItem,
31                                    n_tps: usize,
32                                    abi: Abi,
33                                    inputs: Vec<Ty<'tcx>>,
34                                    output: Ty<'tcx>) {
35     let tcx = ccx.tcx;
36     let def_id = tcx.map.local_def_id(it.id);
37     let i_ty = tcx.lookup_item_type(def_id);
38
39     let substs = Substs::for_item(tcx, def_id,
40                                   |_, _| tcx.mk_region(ty::ReErased),
41                                   |def, _| tcx.mk_param_from_def(def));
42
43     let fty = tcx.mk_fn_def(def_id, substs, tcx.mk_bare_fn(ty::BareFnTy {
44         unsafety: hir::Unsafety::Unsafe,
45         abi: abi,
46         sig: ty::Binder(FnSig {
47             inputs: inputs,
48             output: output,
49             variadic: false,
50         }),
51     }));
52     let i_n_tps = i_ty.generics.types.len();
53     if i_n_tps != n_tps {
54         let span = match it.node {
55             hir::ForeignItemFn(_, ref generics) => generics.span().unwrap_or(it.span),
56             hir::ForeignItemStatic(_, _) => it.span
57         };
58
59         struct_span_err!(tcx.sess, span, E0094,
60                         "intrinsic has wrong number of type \
61                         parameters: found {}, expected {}",
62                         i_n_tps, n_tps)
63             .span_label(span, &format!("expected {} type parameter", n_tps))
64             .emit();
65     } else {
66         require_same_types(ccx,
67                            TypeOrigin::IntrinsicType(it.span),
68                            i_ty.ty,
69                            fty);
70     }
71 }
72
73 /// Remember to add all intrinsics here, in librustc_trans/trans/intrinsic.rs,
74 /// and in libcore/intrinsics.rs
75 pub fn check_intrinsic_type(ccx: &CrateCtxt, it: &hir::ForeignItem) {
76     fn param<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, n: u32) -> Ty<'tcx> {
77         let name = token::intern(&format!("P{}", n));
78         ccx.tcx.mk_param(n, name)
79     }
80
81     let tcx = ccx.tcx;
82     let name = it.name.as_str();
83     let (n_tps, inputs, output) = if name.starts_with("atomic_") {
84         let split : Vec<&str> = name.split('_').collect();
85         assert!(split.len() >= 2, "Atomic intrinsic not correct format");
86
87         //We only care about the operation here
88         let (n_tps, inputs, output) = match split[1] {
89             "cxchg" | "cxchgweak" => (1, vec!(tcx.mk_mut_ptr(param(ccx, 0)),
90                                               param(ccx, 0),
91                                               param(ccx, 0)),
92                                       tcx.mk_tup(vec!(param(ccx, 0), tcx.types.bool))),
93             "load" => (1, vec!(tcx.mk_imm_ptr(param(ccx, 0))),
94                        param(ccx, 0)),
95             "store" => (1, vec!(tcx.mk_mut_ptr(param(ccx, 0)), param(ccx, 0)),
96                         tcx.mk_nil()),
97
98             "xchg" | "xadd" | "xsub" | "and"  | "nand" | "or" | "xor" | "max" |
99             "min"  | "umax" | "umin" => {
100                 (1, vec!(tcx.mk_mut_ptr(param(ccx, 0)), param(ccx, 0)),
101                  param(ccx, 0))
102             }
103             "fence" | "singlethreadfence" => {
104                 (0, Vec::new(), tcx.mk_nil())
105             }
106             op => {
107                 struct_span_err!(tcx.sess, it.span, E0092,
108                       "unrecognized atomic operation function: `{}`", op)
109                   .span_label(it.span, &format!("unrecognized atomic operation"))
110                   .emit();
111                 return;
112             }
113         };
114         (n_tps, inputs, output)
115     } else if &name[..] == "abort" || &name[..] == "unreachable" {
116         (0, Vec::new(), tcx.types.never)
117     } else {
118         let (n_tps, inputs, output) = match &name[..] {
119             "breakpoint" => (0, Vec::new(), tcx.mk_nil()),
120             "size_of" |
121             "pref_align_of" | "min_align_of" => (1, Vec::new(), ccx.tcx.types.usize),
122             "size_of_val" |  "min_align_of_val" => {
123                 (1, vec![
124                     tcx.mk_imm_ref(tcx.mk_region(ty::ReLateBound(ty::DebruijnIndex::new(1),
125                                                                   ty::BrAnon(0))),
126                                     param(ccx, 0))
127                  ], ccx.tcx.types.usize)
128             }
129             "rustc_peek" => (1, vec![param(ccx, 0)], param(ccx, 0)),
130             "init" => (1, Vec::new(), param(ccx, 0)),
131             "uninit" => (1, Vec::new(), param(ccx, 0)),
132             "forget" => (1, vec!( param(ccx, 0) ), tcx.mk_nil()),
133             "transmute" => (2, vec!( param(ccx, 0) ), param(ccx, 1)),
134             "move_val_init" => {
135                 (1,
136                  vec!(
137                     tcx.mk_mut_ptr(param(ccx, 0)),
138                     param(ccx, 0)
139                   ),
140                tcx.mk_nil())
141             }
142             "drop_in_place" => {
143                 (1, vec![tcx.mk_mut_ptr(param(ccx, 0))], tcx.mk_nil())
144             }
145             "needs_drop" => (1, Vec::new(), ccx.tcx.types.bool),
146
147             "type_name" => (1, Vec::new(), tcx.mk_static_str()),
148             "type_id" => (1, Vec::new(), ccx.tcx.types.u64),
149             "offset" | "arith_offset" => {
150               (1,
151                vec!(
152                   tcx.mk_ptr(ty::TypeAndMut {
153                       ty: param(ccx, 0),
154                       mutbl: hir::MutImmutable
155                   }),
156                   ccx.tcx.types.isize
157                ),
158                tcx.mk_ptr(ty::TypeAndMut {
159                    ty: param(ccx, 0),
160                    mutbl: hir::MutImmutable
161                }))
162             }
163             "copy" | "copy_nonoverlapping" => {
164               (1,
165                vec!(
166                   tcx.mk_ptr(ty::TypeAndMut {
167                       ty: param(ccx, 0),
168                       mutbl: hir::MutImmutable
169                   }),
170                   tcx.mk_ptr(ty::TypeAndMut {
171                       ty: param(ccx, 0),
172                       mutbl: hir::MutMutable
173                   }),
174                   tcx.types.usize,
175                ),
176                tcx.mk_nil())
177             }
178             "volatile_copy_memory" | "volatile_copy_nonoverlapping_memory" => {
179               (1,
180                vec!(
181                   tcx.mk_ptr(ty::TypeAndMut {
182                       ty: param(ccx, 0),
183                       mutbl: hir::MutMutable
184                   }),
185                   tcx.mk_ptr(ty::TypeAndMut {
186                       ty: param(ccx, 0),
187                       mutbl: hir::MutImmutable
188                   }),
189                   tcx.types.usize,
190                ),
191                tcx.mk_nil())
192             }
193             "write_bytes" | "volatile_set_memory" => {
194               (1,
195                vec!(
196                   tcx.mk_ptr(ty::TypeAndMut {
197                       ty: param(ccx, 0),
198                       mutbl: hir::MutMutable
199                   }),
200                   tcx.types.u8,
201                   tcx.types.usize,
202                ),
203                tcx.mk_nil())
204             }
205             "sqrtf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32),
206             "sqrtf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64),
207             "powif32" => {
208                (0,
209                 vec!( tcx.types.f32, tcx.types.i32 ),
210                 tcx.types.f32)
211             }
212             "powif64" => {
213                (0,
214                 vec!( tcx.types.f64, tcx.types.i32 ),
215                 tcx.types.f64)
216             }
217             "sinf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32),
218             "sinf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64),
219             "cosf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32),
220             "cosf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64),
221             "powf32" => {
222                (0,
223                 vec!( tcx.types.f32, tcx.types.f32 ),
224                 tcx.types.f32)
225             }
226             "powf64" => {
227                (0,
228                 vec!( tcx.types.f64, tcx.types.f64 ),
229                 tcx.types.f64)
230             }
231             "expf32"   => (0, vec!( tcx.types.f32 ), tcx.types.f32),
232             "expf64"   => (0, vec!( tcx.types.f64 ), tcx.types.f64),
233             "exp2f32"  => (0, vec!( tcx.types.f32 ), tcx.types.f32),
234             "exp2f64"  => (0, vec!( tcx.types.f64 ), tcx.types.f64),
235             "logf32"   => (0, vec!( tcx.types.f32 ), tcx.types.f32),
236             "logf64"   => (0, vec!( tcx.types.f64 ), tcx.types.f64),
237             "log10f32" => (0, vec!( tcx.types.f32 ), tcx.types.f32),
238             "log10f64" => (0, vec!( tcx.types.f64 ), tcx.types.f64),
239             "log2f32"  => (0, vec!( tcx.types.f32 ), tcx.types.f32),
240             "log2f64"  => (0, vec!( tcx.types.f64 ), tcx.types.f64),
241             "fmaf32" => {
242                 (0,
243                  vec!( tcx.types.f32, tcx.types.f32, tcx.types.f32 ),
244                  tcx.types.f32)
245             }
246             "fmaf64" => {
247                 (0,
248                  vec!( tcx.types.f64, tcx.types.f64, tcx.types.f64 ),
249                  tcx.types.f64)
250             }
251             "fabsf32"      => (0, vec!( tcx.types.f32 ), tcx.types.f32),
252             "fabsf64"      => (0, vec!( tcx.types.f64 ), tcx.types.f64),
253             "copysignf32"  => (0, vec!( tcx.types.f32, tcx.types.f32 ), tcx.types.f32),
254             "copysignf64"  => (0, vec!( tcx.types.f64, tcx.types.f64 ), tcx.types.f64),
255             "floorf32"     => (0, vec!( tcx.types.f32 ), tcx.types.f32),
256             "floorf64"     => (0, vec!( tcx.types.f64 ), tcx.types.f64),
257             "ceilf32"      => (0, vec!( tcx.types.f32 ), tcx.types.f32),
258             "ceilf64"      => (0, vec!( tcx.types.f64 ), tcx.types.f64),
259             "truncf32"     => (0, vec!( tcx.types.f32 ), tcx.types.f32),
260             "truncf64"     => (0, vec!( tcx.types.f64 ), tcx.types.f64),
261             "rintf32"      => (0, vec!( tcx.types.f32 ), tcx.types.f32),
262             "rintf64"      => (0, vec!( tcx.types.f64 ), tcx.types.f64),
263             "nearbyintf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32),
264             "nearbyintf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64),
265             "roundf32"     => (0, vec!( tcx.types.f32 ), tcx.types.f32),
266             "roundf64"     => (0, vec!( tcx.types.f64 ), tcx.types.f64),
267
268             "volatile_load" =>
269                 (1, vec!( tcx.mk_imm_ptr(param(ccx, 0)) ), param(ccx, 0)),
270             "volatile_store" =>
271                 (1, vec!( tcx.mk_mut_ptr(param(ccx, 0)), param(ccx, 0) ), tcx.mk_nil()),
272
273             "ctpop" | "ctlz" | "cttz" | "bswap" => (1, vec!(param(ccx, 0)), param(ccx, 0)),
274
275             "add_with_overflow" | "sub_with_overflow"  | "mul_with_overflow" =>
276                 (1, vec!(param(ccx, 0), param(ccx, 0)),
277                 tcx.mk_tup(vec!(param(ccx, 0), tcx.types.bool))),
278
279             "unchecked_div" | "unchecked_rem" =>
280                 (1, vec![param(ccx, 0), param(ccx, 0)], param(ccx, 0)),
281
282             "overflowing_add" | "overflowing_sub" | "overflowing_mul" =>
283                 (1, vec![param(ccx, 0), param(ccx, 0)], param(ccx, 0)),
284             "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" =>
285                 (1, vec![param(ccx, 0), param(ccx, 0)], param(ccx, 0)),
286
287             "assume" => (0, vec![tcx.types.bool], tcx.mk_nil()),
288
289             "discriminant_value" => (1, vec![
290                     tcx.mk_imm_ref(tcx.mk_region(ty::ReLateBound(ty::DebruijnIndex::new(1),
291                                                                   ty::BrAnon(0))),
292                                    param(ccx, 0))], tcx.types.u64),
293
294             "try" => {
295                 let mut_u8 = tcx.mk_mut_ptr(tcx.types.u8);
296                 let fn_ty = tcx.mk_bare_fn(ty::BareFnTy {
297                     unsafety: hir::Unsafety::Normal,
298                     abi: Abi::Rust,
299                     sig: ty::Binder(FnSig {
300                         inputs: vec![mut_u8],
301                         output: tcx.mk_nil(),
302                         variadic: false,
303                     }),
304                 });
305                 (0, vec![tcx.mk_fn_ptr(fn_ty), mut_u8, mut_u8], tcx.types.i32)
306             }
307
308             ref other => {
309                 struct_span_err!(tcx.sess, it.span, E0093,
310                                 "unrecognized intrinsic function: `{}`",
311                                 *other)
312                                 .span_label(it.span, &format!("unrecognized intrinsic"))
313                                 .emit();
314                 return;
315             }
316         };
317         (n_tps, inputs, output)
318     };
319     equate_intrinsic_type(ccx, it, n_tps, Abi::RustIntrinsic, inputs, output)
320 }
321
322 /// Type-check `extern "platform-intrinsic" { ... }` functions.
323 pub fn check_platform_intrinsic_type(ccx: &CrateCtxt,
324                                      it: &hir::ForeignItem) {
325     let param = |n| {
326         let name = token::intern(&format!("P{}", n));
327         ccx.tcx.mk_param(n, name)
328     };
329
330     let tcx = ccx.tcx;
331     let i_ty = tcx.lookup_item_type(tcx.map.local_def_id(it.id));
332     let i_n_tps = i_ty.generics.types.len();
333     let name = it.name.as_str();
334
335     let (n_tps, inputs, output) = match &*name {
336         "simd_eq" | "simd_ne" | "simd_lt" | "simd_le" | "simd_gt" | "simd_ge" => {
337             (2, vec![param(0), param(0)], param(1))
338         }
339         "simd_add" | "simd_sub" | "simd_mul" |
340         "simd_div" | "simd_shl" | "simd_shr" |
341         "simd_and" | "simd_or" | "simd_xor" => {
342             (1, vec![param(0), param(0)], param(0))
343         }
344         "simd_insert" => (2, vec![param(0), tcx.types.u32, param(1)], param(0)),
345         "simd_extract" => (2, vec![param(0), tcx.types.u32], param(1)),
346         "simd_cast" => (2, vec![param(0)], param(1)),
347         name if name.starts_with("simd_shuffle") => {
348             match name["simd_shuffle".len()..].parse() {
349                 Ok(n) => {
350                     let params = vec![param(0), param(0),
351                                       tcx.mk_ty(ty::TyArray(tcx.types.u32, n))];
352                     (2, params, param(1))
353                 }
354                 Err(_) => {
355                     span_err!(tcx.sess, it.span, E0439,
356                               "invalid `simd_shuffle`, needs length: `{}`", name);
357                     return
358                 }
359             }
360         }
361         _ => {
362             match intrinsics::Intrinsic::find(&name) {
363                 Some(intr) => {
364                     // this function is a platform specific intrinsic
365                     if i_n_tps != 0 {
366                         span_err!(tcx.sess, it.span, E0440,
367                                   "platform-specific intrinsic has wrong number of type \
368                                    parameters: found {}, expected 0",
369                                   i_n_tps);
370                         return
371                     }
372
373                     let mut structural_to_nomimal = HashMap::new();
374
375                     let sig = tcx.no_late_bound_regions(i_ty.ty.fn_sig()).unwrap();
376                     if intr.inputs.len() != sig.inputs.len() {
377                         span_err!(tcx.sess, it.span, E0444,
378                                   "platform-specific intrinsic has invalid number of \
379                                    arguments: found {}, expected {}",
380                                   intr.inputs.len(), sig.inputs.len());
381                         return
382                     }
383                     let input_pairs = intr.inputs.iter().zip(&sig.inputs);
384                     for (i, (expected_arg, arg)) in input_pairs.enumerate() {
385                         match_intrinsic_type_to_type(ccx, &format!("argument {}", i + 1), it.span,
386                                                      &mut structural_to_nomimal, expected_arg, arg);
387                     }
388                     match_intrinsic_type_to_type(ccx, "return value", it.span,
389                                                  &mut structural_to_nomimal,
390                                                  &intr.output, sig.output);
391                     return
392                 }
393                 None => {
394                     span_err!(tcx.sess, it.span, E0441,
395                               "unrecognized platform-specific intrinsic function: `{}`", name);
396                     return;
397                 }
398             }
399         }
400     };
401
402     equate_intrinsic_type(ccx, it, n_tps, Abi::PlatformIntrinsic,
403                           inputs, output)
404 }
405
406 // walk the expected type and the actual type in lock step, checking they're
407 // the same, in a kinda-structural way, i.e. `Vector`s have to be simd structs with
408 // exactly the right element type
409 fn match_intrinsic_type_to_type<'tcx, 'a>(
410         ccx: &CrateCtxt<'a, 'tcx>,
411         position: &str,
412         span: Span,
413         structural_to_nominal: &mut HashMap<&'a intrinsics::Type, ty::Ty<'tcx>>,
414         expected: &'a intrinsics::Type, t: ty::Ty<'tcx>)
415 {
416     use intrinsics::Type::*;
417
418     let simple_error = |real: &str, expected: &str| {
419         span_err!(ccx.tcx.sess, span, E0442,
420                   "intrinsic {} has wrong type: found {}, expected {}",
421                   position, real, expected)
422     };
423
424     match *expected {
425         Void => match t.sty {
426             ty::TyTuple(ref v) if v.is_empty() => {},
427             _ => simple_error(&format!("`{}`", t), "()"),
428         },
429         // (The width we pass to LLVM doesn't concern the type checker.)
430         Integer(signed, bits, _llvm_width) => match (signed, bits, &t.sty) {
431             (true,  8,  &ty::TyInt(ast::IntTy::I8)) |
432             (false, 8,  &ty::TyUint(ast::UintTy::U8)) |
433             (true,  16, &ty::TyInt(ast::IntTy::I16)) |
434             (false, 16, &ty::TyUint(ast::UintTy::U16)) |
435             (true,  32, &ty::TyInt(ast::IntTy::I32)) |
436             (false, 32, &ty::TyUint(ast::UintTy::U32)) |
437             (true,  64, &ty::TyInt(ast::IntTy::I64)) |
438             (false, 64, &ty::TyUint(ast::UintTy::U64)) => {},
439             _ => simple_error(&format!("`{}`", t),
440                               &format!("`{}{n}`",
441                                        if signed {"i"} else {"u"},
442                                        n = bits)),
443         },
444         Float(bits) => match (bits, &t.sty) {
445             (32, &ty::TyFloat(ast::FloatTy::F32)) |
446             (64, &ty::TyFloat(ast::FloatTy::F64)) => {},
447             _ => simple_error(&format!("`{}`", t),
448                               &format!("`f{n}`", n = bits)),
449         },
450         Pointer(ref inner_expected, ref _llvm_type, const_) => {
451             match t.sty {
452                 ty::TyRawPtr(ty::TypeAndMut { ty, mutbl }) => {
453                     if (mutbl == hir::MutImmutable) != const_ {
454                         simple_error(&format!("`{}`", t),
455                                      if const_ {"const pointer"} else {"mut pointer"})
456                     }
457                     match_intrinsic_type_to_type(ccx, position, span, structural_to_nominal,
458                                                  inner_expected, ty)
459                 }
460                 _ => simple_error(&format!("`{}`", t), "raw pointer"),
461             }
462         }
463         Vector(ref inner_expected, ref _llvm_type, len) => {
464             if !t.is_simd() {
465                 simple_error(&format!("non-simd type `{}`", t), "simd type");
466                 return;
467             }
468             let t_len = t.simd_size(ccx.tcx);
469             if len as usize != t_len {
470                 simple_error(&format!("vector with length {}", t_len),
471                              &format!("length {}", len));
472                 return;
473             }
474             let t_ty = t.simd_type(ccx.tcx);
475             {
476                 // check that a given structural type always has the same an intrinsic definition
477                 let previous = structural_to_nominal.entry(expected).or_insert(t);
478                 if *previous != t {
479                     // this gets its own error code because it is non-trivial
480                     span_err!(ccx.tcx.sess, span, E0443,
481                               "intrinsic {} has wrong type: found `{}`, expected `{}` which \
482                                was used for this vector type previously in this signature",
483                               position,
484                               t,
485                               *previous);
486                     return;
487                 }
488             }
489             match_intrinsic_type_to_type(ccx,
490                                          position,
491                                          span,
492                                          structural_to_nominal,
493                                          inner_expected,
494                                          t_ty)
495         }
496         Aggregate(_flatten, ref expected_contents) => {
497             match t.sty {
498                 ty::TyTuple(contents) => {
499                     if contents.len() != expected_contents.len() {
500                         simple_error(&format!("tuple with length {}", contents.len()),
501                                      &format!("tuple with length {}", expected_contents.len()));
502                         return
503                     }
504                     for (e, c) in expected_contents.iter().zip(contents) {
505                         match_intrinsic_type_to_type(ccx, position, span, structural_to_nominal,
506                                                      e, c)
507                     }
508                 }
509                 _ => simple_error(&format!("`{}`", t),
510                                   &format!("tuple")),
511             }
512         }
513     }
514 }