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::infer::TypeOrigin;
16 use rustc::ty::subst::Substs;
18 use rustc::ty::{self, Ty};
19 use {CrateCtxt, require_same_types};
21 use std::collections::{HashMap};
24 use syntax::parse::token;
29 fn equate_intrinsic_type<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
30 it: &hir::ForeignItem,
33 inputs: Vec<Ty<'tcx>>,
36 let def_id = tcx.map.local_def_id(it.id);
37 let i_ty = tcx.lookup_item_type(def_id);
39 let substs = Substs::for_item(tcx, def_id,
40 |_, _| tcx.mk_region(ty::ReErased),
41 |def, _| tcx.mk_param_from_def(def));
43 let fty = tcx.mk_fn_def(def_id, substs, tcx.mk_bare_fn(ty::BareFnTy {
44 unsafety: hir::Unsafety::Unsafe,
46 sig: ty::Binder(FnSig {
52 let i_n_tps = i_ty.generics.types.len();
54 let span = match it.node {
55 hir::ForeignItemFn(_, ref generics) => generics.span().unwrap_or(it.span),
56 hir::ForeignItemStatic(_, _) => it.span
59 struct_span_err!(tcx.sess, span, E0094,
60 "intrinsic has wrong number of type \
61 parameters: found {}, expected {}",
63 .span_label(span, &format!("expected {} type parameter", n_tps))
66 require_same_types(ccx,
67 TypeOrigin::IntrinsicType(it.span),
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)
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");
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)),
92 tcx.mk_tup(vec!(param(ccx, 0), tcx.types.bool))),
93 "load" => (1, vec!(tcx.mk_imm_ptr(param(ccx, 0))),
95 "store" => (1, vec!(tcx.mk_mut_ptr(param(ccx, 0)), param(ccx, 0)),
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)),
103 "fence" | "singlethreadfence" => {
104 (0, Vec::new(), tcx.mk_nil())
107 struct_span_err!(tcx.sess, it.span, E0092,
108 "unrecognized atomic operation function: `{}`", op)
109 .span_label(it.span, &format!("unrecognized atomic operation"))
114 (n_tps, inputs, output)
115 } else if &name[..] == "abort" || &name[..] == "unreachable" {
116 (0, Vec::new(), tcx.types.never)
118 let (n_tps, inputs, output) = match &name[..] {
119 "breakpoint" => (0, Vec::new(), tcx.mk_nil()),
121 "pref_align_of" | "min_align_of" => (1, Vec::new(), ccx.tcx.types.usize),
122 "size_of_val" | "min_align_of_val" => {
124 tcx.mk_imm_ref(tcx.mk_region(ty::ReLateBound(ty::DebruijnIndex::new(1),
127 ], ccx.tcx.types.usize)
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)),
137 tcx.mk_mut_ptr(param(ccx, 0)),
143 (1, vec![tcx.mk_mut_ptr(param(ccx, 0))], tcx.mk_nil())
145 "needs_drop" => (1, Vec::new(), ccx.tcx.types.bool),
147 "type_name" => (1, Vec::new(), tcx.mk_static_str()),
148 "type_id" => (1, Vec::new(), ccx.tcx.types.u64),
149 "offset" | "arith_offset" => {
152 tcx.mk_ptr(ty::TypeAndMut {
154 mutbl: hir::MutImmutable
158 tcx.mk_ptr(ty::TypeAndMut {
160 mutbl: hir::MutImmutable
163 "copy" | "copy_nonoverlapping" => {
166 tcx.mk_ptr(ty::TypeAndMut {
168 mutbl: hir::MutImmutable
170 tcx.mk_ptr(ty::TypeAndMut {
172 mutbl: hir::MutMutable
178 "volatile_copy_memory" | "volatile_copy_nonoverlapping_memory" => {
181 tcx.mk_ptr(ty::TypeAndMut {
183 mutbl: hir::MutMutable
185 tcx.mk_ptr(ty::TypeAndMut {
187 mutbl: hir::MutImmutable
193 "write_bytes" | "volatile_set_memory" => {
196 tcx.mk_ptr(ty::TypeAndMut {
198 mutbl: hir::MutMutable
205 "sqrtf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32),
206 "sqrtf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64),
209 vec!( tcx.types.f32, tcx.types.i32 ),
214 vec!( tcx.types.f64, tcx.types.i32 ),
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),
223 vec!( tcx.types.f32, tcx.types.f32 ),
228 vec!( tcx.types.f64, tcx.types.f64 ),
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),
243 vec!( tcx.types.f32, tcx.types.f32, tcx.types.f32 ),
248 vec!( tcx.types.f64, tcx.types.f64, tcx.types.f64 ),
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),
269 (1, vec!( tcx.mk_imm_ptr(param(ccx, 0)) ), param(ccx, 0)),
271 (1, vec!( tcx.mk_mut_ptr(param(ccx, 0)), param(ccx, 0) ), tcx.mk_nil()),
273 "ctpop" | "ctlz" | "cttz" | "bswap" => (1, vec!(param(ccx, 0)), param(ccx, 0)),
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))),
279 "unchecked_div" | "unchecked_rem" =>
280 (1, vec![param(ccx, 0), param(ccx, 0)], param(ccx, 0)),
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)),
287 "assume" => (0, vec![tcx.types.bool], tcx.mk_nil()),
289 "discriminant_value" => (1, vec![
290 tcx.mk_imm_ref(tcx.mk_region(ty::ReLateBound(ty::DebruijnIndex::new(1),
292 param(ccx, 0))], tcx.types.u64),
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,
299 sig: ty::Binder(FnSig {
300 inputs: vec![mut_u8],
301 output: tcx.mk_nil(),
305 (0, vec![tcx.mk_fn_ptr(fn_ty), mut_u8, mut_u8], tcx.types.i32)
309 struct_span_err!(tcx.sess, it.span, E0093,
310 "unrecognized intrinsic function: `{}`",
312 .span_label(it.span, &format!("unrecognized intrinsic"))
317 (n_tps, inputs, output)
319 equate_intrinsic_type(ccx, it, n_tps, Abi::RustIntrinsic, inputs, output)
322 /// Type-check `extern "platform-intrinsic" { ... }` functions.
323 pub fn check_platform_intrinsic_type(ccx: &CrateCtxt,
324 it: &hir::ForeignItem) {
326 let name = token::intern(&format!("P{}", n));
327 ccx.tcx.mk_param(n, name)
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();
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))
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))
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() {
350 let params = vec![param(0), param(0),
351 tcx.mk_ty(ty::TyArray(tcx.types.u32, n))];
352 (2, params, param(1))
355 span_err!(tcx.sess, it.span, E0439,
356 "invalid `simd_shuffle`, needs length: `{}`", name);
362 match intrinsics::Intrinsic::find(&name) {
364 // this function is a platform specific intrinsic
366 span_err!(tcx.sess, it.span, E0440,
367 "platform-specific intrinsic has wrong number of type \
368 parameters: found {}, expected 0",
373 let mut structural_to_nomimal = HashMap::new();
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());
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);
388 match_intrinsic_type_to_type(ccx, "return value", it.span,
389 &mut structural_to_nomimal,
390 &intr.output, sig.output);
394 span_err!(tcx.sess, it.span, E0441,
395 "unrecognized platform-specific intrinsic function: `{}`", name);
402 equate_intrinsic_type(ccx, it, n_tps, Abi::PlatformIntrinsic,
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>,
413 structural_to_nominal: &mut HashMap<&'a intrinsics::Type, ty::Ty<'tcx>>,
414 expected: &'a intrinsics::Type, t: ty::Ty<'tcx>)
416 use intrinsics::Type::*;
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)
425 Void => match t.sty {
426 ty::TyTuple(ref v) if v.is_empty() => {},
427 _ => simple_error(&format!("`{}`", t), "()"),
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),
441 if signed {"i"} else {"u"},
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)),
450 Pointer(ref inner_expected, ref _llvm_type, const_) => {
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"})
457 match_intrinsic_type_to_type(ccx, position, span, structural_to_nominal,
460 _ => simple_error(&format!("`{}`", t), "raw pointer"),
463 Vector(ref inner_expected, ref _llvm_type, len) => {
465 simple_error(&format!("non-simd type `{}`", t), "simd type");
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));
474 let t_ty = t.simd_type(ccx.tcx);
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);
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",
489 match_intrinsic_type_to_type(ccx,
492 structural_to_nominal,
496 Aggregate(_flatten, ref expected_contents) => {
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()));
504 for (e, c) in expected_contents.iter().zip(contents) {
505 match_intrinsic_type_to_type(ccx, position, span, structural_to_nominal,
509 _ => simple_error(&format!("`{}`", t),