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.
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.
11 //! Type-checking for the rust-intrinsic and platform-intrinsic
12 //! intrinsics that the compiler exposes.
15 use rustc::traits::{ObligationCause, ObligationCauseCode};
16 use rustc::ty::subst::Substs;
17 use rustc::ty::{self, TyCtxt, Ty};
18 use rustc::util::nodemap::FxHashMap;
19 use require_same_types;
23 use syntax::symbol::Symbol;
30 fn equate_intrinsic_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
31 it: &hir::ForeignItem,
34 inputs: Vec<Ty<'tcx>>,
36 let def_id = tcx.hir.local_def_id(it.id);
38 let substs = Substs::for_item(tcx, def_id,
39 |_, _| tcx.types.re_erased,
40 |def, _| tcx.mk_param_from_def(def));
42 let fty = tcx.mk_fn_def(def_id, substs, ty::Binder(tcx.mk_fn_sig(
46 hir::Unsafety::Unsafe,
49 let i_n_tps = tcx.item_generics(def_id).types.len();
51 let span = match it.node {
52 hir::ForeignItemFn(_, _, ref generics) => generics.span,
53 hir::ForeignItemStatic(..) => it.span
56 struct_span_err!(tcx.sess, span, E0094,
57 "intrinsic has wrong number of type \
58 parameters: found {}, expected {}",
60 .span_label(span, &format!("expected {} type parameter", n_tps))
63 require_same_types(tcx,
64 &ObligationCause::new(it.span,
66 ObligationCauseCode::IntrinsicType),
67 tcx.item_type(def_id),
72 /// Remember to add all intrinsics here, in librustc_trans/trans/intrinsic.rs,
73 /// and in libcore/intrinsics.rs
74 pub fn check_intrinsic_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
75 it: &hir::ForeignItem) {
76 let param = |n| tcx.mk_param(n, Symbol::intern(&format!("P{}", n)));
77 let name = it.name.as_str();
78 let (n_tps, inputs, output) = if name.starts_with("atomic_") {
79 let split : Vec<&str> = name.split('_').collect();
80 assert!(split.len() >= 2, "Atomic intrinsic not correct format");
82 //We only care about the operation here
83 let (n_tps, inputs, output) = match split[1] {
84 "cxchg" | "cxchgweak" => (1, vec![tcx.mk_mut_ptr(param(0)),
87 tcx.intern_tup(&[param(0), tcx.types.bool], false)),
88 "load" => (1, vec![tcx.mk_imm_ptr(param(0))],
90 "store" => (1, vec![tcx.mk_mut_ptr(param(0)), param(0)],
93 "xchg" | "xadd" | "xsub" | "and" | "nand" | "or" | "xor" | "max" |
94 "min" | "umax" | "umin" => {
95 (1, vec![tcx.mk_mut_ptr(param(0)), param(0)],
98 "fence" | "singlethreadfence" => {
99 (0, Vec::new(), tcx.mk_nil())
102 struct_span_err!(tcx.sess, it.span, E0092,
103 "unrecognized atomic operation function: `{}`", op)
104 .span_label(it.span, &format!("unrecognized atomic operation"))
109 (n_tps, inputs, output)
110 } else if &name[..] == "abort" || &name[..] == "unreachable" {
111 (0, Vec::new(), tcx.types.never)
113 let (n_tps, inputs, output) = match &name[..] {
114 "breakpoint" => (0, Vec::new(), tcx.mk_nil()),
116 "pref_align_of" | "min_align_of" => (1, Vec::new(), tcx.types.usize),
117 "size_of_val" | "min_align_of_val" => {
119 tcx.mk_imm_ref(tcx.mk_region(ty::ReLateBound(ty::DebruijnIndex::new(1),
124 "rustc_peek" => (1, vec![param(0)], param(0)),
125 "init" => (1, Vec::new(), param(0)),
126 "uninit" => (1, Vec::new(), param(0)),
127 "transmute" => (2, vec![ param(0) ], param(1)),
131 tcx.mk_mut_ptr(param(0)),
137 (1, vec![tcx.mk_mut_ptr(param(0))], tcx.mk_nil())
139 "needs_drop" => (1, Vec::new(), tcx.types.bool),
141 "type_name" => (1, Vec::new(), tcx.mk_static_str()),
142 "type_id" => (1, Vec::new(), tcx.types.u64),
143 "offset" | "arith_offset" => {
146 tcx.mk_ptr(ty::TypeAndMut {
148 mutbl: hir::MutImmutable
152 tcx.mk_ptr(ty::TypeAndMut {
154 mutbl: hir::MutImmutable
157 "copy" | "copy_nonoverlapping" => {
160 tcx.mk_ptr(ty::TypeAndMut {
162 mutbl: hir::MutImmutable
164 tcx.mk_ptr(ty::TypeAndMut {
166 mutbl: hir::MutMutable
172 "volatile_copy_memory" | "volatile_copy_nonoverlapping_memory" => {
175 tcx.mk_ptr(ty::TypeAndMut {
177 mutbl: hir::MutMutable
179 tcx.mk_ptr(ty::TypeAndMut {
181 mutbl: hir::MutImmutable
187 "write_bytes" | "volatile_set_memory" => {
190 tcx.mk_ptr(ty::TypeAndMut {
192 mutbl: hir::MutMutable
199 "sqrtf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
200 "sqrtf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
203 vec![ tcx.types.f32, tcx.types.i32 ],
208 vec![ tcx.types.f64, tcx.types.i32 ],
211 "sinf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
212 "sinf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
213 "cosf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
214 "cosf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
217 vec![ tcx.types.f32, tcx.types.f32 ],
222 vec![ tcx.types.f64, tcx.types.f64 ],
225 "expf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
226 "expf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
227 "exp2f32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
228 "exp2f64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
229 "logf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
230 "logf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
231 "log10f32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
232 "log10f64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
233 "log2f32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
234 "log2f64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
237 vec![ tcx.types.f32, tcx.types.f32, tcx.types.f32 ],
242 vec![ tcx.types.f64, tcx.types.f64, tcx.types.f64 ],
245 "fabsf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
246 "fabsf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
247 "copysignf32" => (0, vec![ tcx.types.f32, tcx.types.f32 ], tcx.types.f32),
248 "copysignf64" => (0, vec![ tcx.types.f64, tcx.types.f64 ], tcx.types.f64),
249 "floorf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
250 "floorf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
251 "ceilf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
252 "ceilf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
253 "truncf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
254 "truncf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
255 "rintf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
256 "rintf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
257 "nearbyintf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
258 "nearbyintf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
259 "roundf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
260 "roundf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
263 (1, vec![ tcx.mk_imm_ptr(param(0)) ], param(0)),
265 (1, vec![ tcx.mk_mut_ptr(param(0)), param(0) ], tcx.mk_nil()),
267 "ctpop" | "ctlz" | "cttz" | "bswap" => (1, vec![param(0)], param(0)),
269 "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" =>
270 (1, vec![param(0), param(0)],
271 tcx.intern_tup(&[param(0), tcx.types.bool], false)),
273 "unchecked_div" | "unchecked_rem" =>
274 (1, vec![param(0), param(0)], param(0)),
275 "unchecked_shl" | "unchecked_shr" =>
276 (1, vec![param(0), param(0)], param(0)),
278 "overflowing_add" | "overflowing_sub" | "overflowing_mul" =>
279 (1, vec![param(0), param(0)], param(0)),
280 "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" =>
281 (1, vec![param(0), param(0)], param(0)),
283 "assume" => (0, vec![tcx.types.bool], tcx.mk_nil()),
284 "likely" => (0, vec![tcx.types.bool], tcx.types.bool),
285 "unlikely" => (0, vec![tcx.types.bool], tcx.types.bool),
287 "discriminant_value" => (1, vec![
288 tcx.mk_imm_ref(tcx.mk_region(ty::ReLateBound(ty::DebruijnIndex::new(1),
290 param(0))], tcx.types.u64),
293 let mut_u8 = tcx.mk_mut_ptr(tcx.types.u8);
294 let fn_ty = ty::Binder(tcx.mk_fn_sig(
298 hir::Unsafety::Normal,
301 (0, vec![tcx.mk_fn_ptr(fn_ty), mut_u8, mut_u8], tcx.types.i32)
305 struct_span_err!(tcx.sess, it.span, E0093,
306 "unrecognized intrinsic function: `{}`",
308 .span_label(it.span, &format!("unrecognized intrinsic"))
313 (n_tps, inputs, output)
315 equate_intrinsic_type(tcx, it, n_tps, Abi::RustIntrinsic, inputs, output)
318 /// Type-check `extern "platform-intrinsic" { ... }` functions.
319 pub fn check_platform_intrinsic_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
320 it: &hir::ForeignItem) {
322 let name = Symbol::intern(&format!("P{}", n));
323 tcx.mk_param(n, name)
326 let def_id = tcx.hir.local_def_id(it.id);
327 let i_n_tps = tcx.item_generics(def_id).types.len();
328 let name = it.name.as_str();
330 let (n_tps, inputs, output) = match &*name {
331 "simd_eq" | "simd_ne" | "simd_lt" | "simd_le" | "simd_gt" | "simd_ge" => {
332 (2, vec![param(0), param(0)], param(1))
334 "simd_add" | "simd_sub" | "simd_mul" |
335 "simd_div" | "simd_shl" | "simd_shr" |
336 "simd_and" | "simd_or" | "simd_xor" => {
337 (1, vec![param(0), param(0)], param(0))
339 "simd_insert" => (2, vec![param(0), tcx.types.u32, param(1)], param(0)),
340 "simd_extract" => (2, vec![param(0), tcx.types.u32], param(1)),
341 "simd_cast" => (2, vec![param(0)], param(1)),
342 name if name.starts_with("simd_shuffle") => {
343 match name["simd_shuffle".len()..].parse() {
345 let params = vec![param(0), param(0),
346 tcx.mk_ty(ty::TyArray(tcx.types.u32, n))];
347 (2, params, param(1))
350 span_err!(tcx.sess, it.span, E0439,
351 "invalid `simd_shuffle`, needs length: `{}`", name);
357 match intrinsics::Intrinsic::find(&name) {
359 // this function is a platform specific intrinsic
361 span_err!(tcx.sess, it.span, E0440,
362 "platform-specific intrinsic has wrong number of type \
363 parameters: found {}, expected 0",
368 let mut structural_to_nomimal = FxHashMap();
370 let sig = tcx.item_type(def_id).fn_sig();
371 let sig = tcx.no_late_bound_regions(&sig).unwrap();
372 if intr.inputs.len() != sig.inputs().len() {
373 span_err!(tcx.sess, it.span, E0444,
374 "platform-specific intrinsic has invalid number of \
375 arguments: found {}, expected {}",
376 sig.inputs().len(), intr.inputs.len());
379 let input_pairs = intr.inputs.iter().zip(sig.inputs());
380 for (i, (expected_arg, arg)) in input_pairs.enumerate() {
381 match_intrinsic_type_to_type(tcx, &format!("argument {}", i + 1), it.span,
382 &mut structural_to_nomimal, expected_arg, arg);
384 match_intrinsic_type_to_type(tcx, "return value", it.span,
385 &mut structural_to_nomimal,
386 &intr.output, sig.output());
390 span_err!(tcx.sess, it.span, E0441,
391 "unrecognized platform-specific intrinsic function: `{}`", name);
398 equate_intrinsic_type(tcx, it, n_tps, Abi::PlatformIntrinsic,
402 // walk the expected type and the actual type in lock step, checking they're
403 // the same, in a kinda-structural way, i.e. `Vector`s have to be simd structs with
404 // exactly the right element type
405 fn match_intrinsic_type_to_type<'a, 'tcx>(
406 tcx: TyCtxt<'a, 'tcx, 'tcx>,
409 structural_to_nominal: &mut FxHashMap<&'a intrinsics::Type, ty::Ty<'tcx>>,
410 expected: &'a intrinsics::Type, t: ty::Ty<'tcx>)
412 use intrinsics::Type::*;
414 let simple_error = |real: &str, expected: &str| {
415 span_err!(tcx.sess, span, E0442,
416 "intrinsic {} has wrong type: found {}, expected {}",
417 position, real, expected)
421 Void => match t.sty {
422 ty::TyTuple(ref v, _) if v.is_empty() => {},
423 _ => simple_error(&format!("`{}`", t), "()"),
425 // (The width we pass to LLVM doesn't concern the type checker.)
426 Integer(signed, bits, _llvm_width) => match (signed, bits, &t.sty) {
427 (true, 8, &ty::TyInt(ast::IntTy::I8)) |
428 (false, 8, &ty::TyUint(ast::UintTy::U8)) |
429 (true, 16, &ty::TyInt(ast::IntTy::I16)) |
430 (false, 16, &ty::TyUint(ast::UintTy::U16)) |
431 (true, 32, &ty::TyInt(ast::IntTy::I32)) |
432 (false, 32, &ty::TyUint(ast::UintTy::U32)) |
433 (true, 64, &ty::TyInt(ast::IntTy::I64)) |
434 (false, 64, &ty::TyUint(ast::UintTy::U64)) |
435 (true, 128, &ty::TyInt(ast::IntTy::I128)) |
436 (false, 128, &ty::TyUint(ast::UintTy::U128)) => {},
437 _ => simple_error(&format!("`{}`", t),
439 if signed {"i"} else {"u"},
442 Float(bits) => match (bits, &t.sty) {
443 (32, &ty::TyFloat(ast::FloatTy::F32)) |
444 (64, &ty::TyFloat(ast::FloatTy::F64)) => {},
445 _ => simple_error(&format!("`{}`", t),
446 &format!("`f{n}`", n = bits)),
448 Pointer(ref inner_expected, ref _llvm_type, const_) => {
450 ty::TyRawPtr(ty::TypeAndMut { ty, mutbl }) => {
451 if (mutbl == hir::MutImmutable) != const_ {
452 simple_error(&format!("`{}`", t),
453 if const_ {"const pointer"} else {"mut pointer"})
455 match_intrinsic_type_to_type(tcx, position, span, structural_to_nominal,
458 _ => simple_error(&format!("`{}`", t), "raw pointer"),
461 Vector(ref inner_expected, ref _llvm_type, len) => {
463 simple_error(&format!("non-simd type `{}`", t), "simd type");
466 let t_len = t.simd_size(tcx);
467 if len as usize != t_len {
468 simple_error(&format!("vector with length {}", t_len),
469 &format!("length {}", len));
472 let t_ty = t.simd_type(tcx);
474 // check that a given structural type always has the same an intrinsic definition
475 let previous = structural_to_nominal.entry(expected).or_insert(t);
477 // this gets its own error code because it is non-trivial
478 span_err!(tcx.sess, span, E0443,
479 "intrinsic {} has wrong type: found `{}`, expected `{}` which \
480 was used for this vector type previously in this signature",
487 match_intrinsic_type_to_type(tcx,
490 structural_to_nominal,
494 Aggregate(_flatten, ref expected_contents) => {
496 ty::TyTuple(contents, _) => {
497 if contents.len() != expected_contents.len() {
498 simple_error(&format!("tuple with length {}", contents.len()),
499 &format!("tuple with length {}", expected_contents.len()));
502 for (e, c) in expected_contents.iter().zip(contents) {
503 match_intrinsic_type_to_type(tcx, position, span, structural_to_nominal,
507 _ => simple_error(&format!("`{}`", t),