1 use rustc_ast::InlineAsmTemplatePiece;
2 use rustc_errors::struct_span_err;
4 use rustc_hir::def::{DefKind, Res};
5 use rustc_hir::def_id::{DefId, LocalDefId};
6 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
7 use rustc_index::vec::Idx;
8 use rustc_middle::ty::layout::{LayoutError, SizeSkeleton};
9 use rustc_middle::ty::query::Providers;
10 use rustc_middle::ty::{self, FloatTy, IntTy, Ty, TyCtxt, UintTy};
11 use rustc_session::lint;
12 use rustc_span::{sym, Span, Symbol, DUMMY_SP};
13 use rustc_target::abi::{Pointer, VariantIdx};
14 use rustc_target::asm::{InlineAsmRegOrRegClass, InlineAsmType};
15 use rustc_target::spec::abi::Abi::RustIntrinsic;
17 fn check_mod_intrinsics(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
18 tcx.hir().visit_item_likes_in_module(module_def_id, &mut ItemVisitor { tcx }.as_deep_visitor());
21 pub fn provide(providers: &mut Providers) {
22 *providers = Providers { check_mod_intrinsics, ..*providers };
25 struct ItemVisitor<'tcx> {
29 struct ExprVisitor<'tcx> {
31 typeck_results: &'tcx ty::TypeckResults<'tcx>,
32 param_env: ty::ParamEnv<'tcx>,
35 /// If the type is `Option<T>`, it will return `T`, otherwise
36 /// the type itself. Works on most `Option`-like types.
37 fn unpack_option_like<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
38 let (def, substs) = match *ty.kind() {
39 ty::Adt(def, substs) => (def, substs),
43 if def.variants.len() == 2 && !def.repr.c() && def.repr.int.is_none() {
46 let one = VariantIdx::new(1);
47 let zero = VariantIdx::new(0);
49 if def.variants[zero].fields.is_empty() {
51 } else if def.variants[one].fields.is_empty() {
57 if def.variants[data_idx].fields.len() == 1 {
58 return def.variants[data_idx].fields[0].ty(tcx, substs);
65 impl ExprVisitor<'tcx> {
66 fn def_id_is_transmute(&self, def_id: DefId) -> bool {
67 self.tcx.fn_sig(def_id).abi() == RustIntrinsic
68 && self.tcx.item_name(def_id) == sym::transmute
71 fn check_transmute(&self, span: Span, from: Ty<'tcx>, to: Ty<'tcx>) {
72 let sk_from = SizeSkeleton::compute(from, self.tcx, self.param_env);
73 let sk_to = SizeSkeleton::compute(to, self.tcx, self.param_env);
75 // Check for same size using the skeletons.
76 if let (Ok(sk_from), Ok(sk_to)) = (sk_from, sk_to) {
77 if sk_from.same_size(sk_to) {
81 // Special-case transmuting from `typeof(function)` and
82 // `Option<typeof(function)>` to present a clearer error.
83 let from = unpack_option_like(self.tcx, from);
84 if let (&ty::FnDef(..), SizeSkeleton::Known(size_to)) = (from.kind(), sk_to) {
85 if size_to == Pointer.size(&self.tcx) {
86 struct_span_err!(self.tcx.sess, span, E0591, "can't transmute zero-sized type")
87 .note(&format!("source type: {}", from))
88 .note(&format!("target type: {}", to))
89 .help("cast with `as` to a pointer instead")
96 // Try to display a sensible error with as much information as possible.
97 let skeleton_string = |ty: Ty<'tcx>, sk| match sk {
98 Ok(SizeSkeleton::Known(size)) => format!("{} bits", size.bits()),
99 Ok(SizeSkeleton::Pointer { tail, .. }) => format!("pointer to `{}`", tail),
100 Err(LayoutError::Unknown(bad)) => {
102 "this type does not have a fixed size".to_owned()
104 format!("size can vary because of {}", bad)
107 Err(err) => err.to_string(),
110 let mut err = struct_span_err!(
114 "cannot transmute between types of different sizes, \
115 or dependently-sized types"
118 err.note(&format!("`{}` does not have a fixed size", from));
120 err.note(&format!("source type: `{}` ({})", from, skeleton_string(from, sk_from)))
121 .note(&format!("target type: `{}` ({})", to, skeleton_string(to, sk_to)));
126 fn is_thin_ptr_ty(&self, ty: Ty<'tcx>) -> bool {
127 if ty.is_sized(self.tcx.at(DUMMY_SP), self.param_env) {
130 if let ty::Foreign(..) = ty.kind() {
136 fn check_asm_operand_type(
139 reg: InlineAsmRegOrRegClass,
140 expr: &hir::Expr<'tcx>,
141 template: &[InlineAsmTemplatePiece],
142 tied_input: Option<(&hir::Expr<'tcx>, Option<InlineAsmType>)>,
143 ) -> Option<InlineAsmType> {
144 // Check the type against the allowed types for inline asm.
145 let ty = self.typeck_results.expr_ty_adjusted(expr);
146 let asm_ty_isize = match self.tcx.sess.target.pointer_width {
147 16 => InlineAsmType::I16,
148 32 => InlineAsmType::I32,
149 64 => InlineAsmType::I64,
152 let asm_ty = match *ty.kind() {
153 ty::Never | ty::Error(_) => return None,
154 ty::Int(IntTy::I8) | ty::Uint(UintTy::U8) => Some(InlineAsmType::I8),
155 ty::Int(IntTy::I16) | ty::Uint(UintTy::U16) => Some(InlineAsmType::I16),
156 ty::Int(IntTy::I32) | ty::Uint(UintTy::U32) => Some(InlineAsmType::I32),
157 ty::Int(IntTy::I64) | ty::Uint(UintTy::U64) => Some(InlineAsmType::I64),
158 ty::Int(IntTy::I128) | ty::Uint(UintTy::U128) => Some(InlineAsmType::I128),
159 ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize) => Some(asm_ty_isize),
160 ty::Float(FloatTy::F32) => Some(InlineAsmType::F32),
161 ty::Float(FloatTy::F64) => Some(InlineAsmType::F64),
162 ty::FnPtr(_) => Some(asm_ty_isize),
163 ty::RawPtr(ty::TypeAndMut { ty, mutbl: _ }) if self.is_thin_ptr_ty(ty) => {
166 ty::Adt(adt, substs) if adt.repr.simd() => {
167 let fields = &adt.non_enum_variant().fields;
168 let elem_ty = fields[0].ty(self.tcx, substs);
169 match elem_ty.kind() {
170 ty::Never | ty::Error(_) => return None,
171 ty::Int(IntTy::I8) | ty::Uint(UintTy::U8) => {
172 Some(InlineAsmType::VecI8(fields.len() as u64))
174 ty::Int(IntTy::I16) | ty::Uint(UintTy::U16) => {
175 Some(InlineAsmType::VecI16(fields.len() as u64))
177 ty::Int(IntTy::I32) | ty::Uint(UintTy::U32) => {
178 Some(InlineAsmType::VecI32(fields.len() as u64))
180 ty::Int(IntTy::I64) | ty::Uint(UintTy::U64) => {
181 Some(InlineAsmType::VecI64(fields.len() as u64))
183 ty::Int(IntTy::I128) | ty::Uint(UintTy::U128) => {
184 Some(InlineAsmType::VecI128(fields.len() as u64))
186 ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize) => {
187 Some(match self.tcx.sess.target.pointer_width {
188 16 => InlineAsmType::VecI16(fields.len() as u64),
189 32 => InlineAsmType::VecI32(fields.len() as u64),
190 64 => InlineAsmType::VecI64(fields.len() as u64),
194 ty::Float(FloatTy::F32) => Some(InlineAsmType::VecF32(fields.len() as u64)),
195 ty::Float(FloatTy::F64) => Some(InlineAsmType::VecF64(fields.len() as u64)),
201 let asm_ty = match asm_ty {
202 Some(asm_ty) => asm_ty,
204 let msg = &format!("cannot use value of type `{}` for inline assembly", ty);
205 let mut err = self.tcx.sess.struct_span_err(expr.span, msg);
207 "only integers, floats, SIMD vectors, pointers and function pointers \
208 can be used as arguments for inline assembly",
215 // Check that the type implements Copy. The only case where this can
216 // possibly fail is for SIMD types which don't #[derive(Copy)].
217 if !ty.is_copy_modulo_regions(self.tcx.at(DUMMY_SP), self.param_env) {
218 let msg = "arguments for inline assembly must be copyable";
219 let mut err = self.tcx.sess.struct_span_err(expr.span, msg);
220 err.note(&format!("`{}` does not implement the Copy trait", ty));
224 // Ideally we wouldn't need to do this, but LLVM's register allocator
225 // really doesn't like it when tied operands have different types.
227 // This is purely an LLVM limitation, but we have to live with it since
228 // there is no way to hide this with implicit conversions.
230 // For the purposes of this check we only look at the `InlineAsmType`,
231 // which means that pointers and integers are treated as identical (modulo
233 if let Some((in_expr, Some(in_asm_ty))) = tied_input {
234 if in_asm_ty != asm_ty {
235 let msg = "incompatible types for asm inout argument";
236 let mut err = self.tcx.sess.struct_span_err(vec![in_expr.span, expr.span], msg);
239 &format!("type `{}`", self.typeck_results.expr_ty_adjusted(in_expr)),
241 err.span_label(expr.span, &format!("type `{}`", ty));
243 "asm inout arguments must have the same type, \
244 unless they are both pointers or integers of the same size",
249 // All of the later checks have already been done on the input, so
250 // let's not emit errors and warnings twice.
254 // Check the type against the list of types supported by the selected
256 let asm_arch = self.tcx.sess.asm_arch.unwrap();
257 let reg_class = reg.reg_class();
258 let supported_tys = reg_class.supported_types(asm_arch);
259 let feature = match supported_tys.iter().find(|&&(t, _)| t == asm_ty) {
260 Some((_, feature)) => feature,
262 let msg = &format!("type `{}` cannot be used with this register class", ty);
263 let mut err = self.tcx.sess.struct_span_err(expr.span, msg);
264 let supported_tys: Vec<_> =
265 supported_tys.iter().map(|(t, _)| t.to_string()).collect();
267 "register class `{}` supports these types: {}",
269 supported_tys.join(", "),
271 if let Some(suggest) = reg_class.suggest_class(asm_arch, asm_ty) {
273 "consider using the `{}` register class instead",
282 // Check whether the selected type requires a target feature. Note that
283 // this is different from the feature check we did earlier in AST
284 // lowering. While AST lowering checked that this register class is
285 // usable at all with the currently enabled features, some types may
286 // only be usable with a register class when a certain feature is
287 // enabled. We check this here since it depends on the results of typeck.
289 // Also note that this check isn't run when the operand type is never
290 // (!). In that case we still need the earlier check in AST lowering to
291 // verify that the register class is usable at all.
292 if let Some(feature) = feature {
293 if !self.tcx.sess.target_features.contains(&Symbol::intern(feature)) {
294 let msg = &format!("`{}` target feature is not enabled", feature);
295 let mut err = self.tcx.sess.struct_span_err(expr.span, msg);
297 "this is required to use type `{}` with register class `{}`",
306 // Check whether a modifier is suggested for using this type.
307 if let Some((suggested_modifier, suggested_result)) =
308 reg_class.suggest_modifier(asm_arch, asm_ty)
310 // Search for any use of this operand without a modifier and emit
311 // the suggestion for them.
312 let mut spans = vec![];
313 for piece in template {
314 if let &InlineAsmTemplatePiece::Placeholder { operand_idx, modifier, span } = piece
316 if operand_idx == idx && modifier.is_none() {
321 if !spans.is_empty() {
322 let (default_modifier, default_result) =
323 reg_class.default_modifier(asm_arch).unwrap();
324 self.tcx.struct_span_lint_hir(
325 lint::builtin::ASM_SUB_REGISTER,
329 let msg = "formatting may not be suitable for sub-register argument";
330 let mut err = lint.build(msg);
331 err.span_label(expr.span, "for this argument");
333 "use the `{}` modifier to have the register formatted as `{}`",
334 suggested_modifier, suggested_result,
337 "or use the `{}` modifier to keep the default formatting of `{}`",
338 default_modifier, default_result,
349 fn check_asm(&self, asm: &hir::InlineAsm<'tcx>) {
350 for (idx, (op, _op_sp)) in asm.operands.iter().enumerate() {
352 hir::InlineAsmOperand::In { reg, ref expr } => {
353 self.check_asm_operand_type(idx, reg, expr, asm.template, None);
355 hir::InlineAsmOperand::Out { reg, late: _, ref expr } => {
356 if let Some(expr) = expr {
357 self.check_asm_operand_type(idx, reg, expr, asm.template, None);
360 hir::InlineAsmOperand::InOut { reg, late: _, ref expr } => {
361 self.check_asm_operand_type(idx, reg, expr, asm.template, None);
363 hir::InlineAsmOperand::SplitInOut { reg, late: _, ref in_expr, ref out_expr } => {
364 let in_ty = self.check_asm_operand_type(idx, reg, in_expr, asm.template, None);
365 if let Some(out_expr) = out_expr {
366 self.check_asm_operand_type(
371 Some((in_expr, in_ty)),
375 hir::InlineAsmOperand::Const { ref expr } => {
376 let ty = self.typeck_results.expr_ty_adjusted(expr);
378 ty::Int(_) | ty::Uint(_) | ty::Float(_) => {}
381 "asm `const` arguments must be integer or floating-point values";
382 self.tcx.sess.span_err(expr.span, msg);
386 hir::InlineAsmOperand::Sym { .. } => {}
392 impl Visitor<'tcx> for ItemVisitor<'tcx> {
393 type Map = intravisit::ErasedMap<'tcx>;
395 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
396 NestedVisitorMap::None
399 fn visit_nested_body(&mut self, body_id: hir::BodyId) {
400 let owner_def_id = self.tcx.hir().body_owner_def_id(body_id);
401 let body = self.tcx.hir().body(body_id);
402 let param_env = self.tcx.param_env(owner_def_id.to_def_id());
403 let typeck_results = self.tcx.typeck(owner_def_id);
404 ExprVisitor { tcx: self.tcx, param_env, typeck_results }.visit_body(body);
405 self.visit_body(body);
409 impl Visitor<'tcx> for ExprVisitor<'tcx> {
410 type Map = intravisit::ErasedMap<'tcx>;
412 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
413 NestedVisitorMap::None
416 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
418 hir::ExprKind::Path(ref qpath) => {
419 let res = self.typeck_results.qpath_res(qpath, expr.hir_id);
420 if let Res::Def(DefKind::Fn, did) = res {
421 if self.def_id_is_transmute(did) {
422 let typ = self.typeck_results.node_type(expr.hir_id);
423 let sig = typ.fn_sig(self.tcx);
424 let from = sig.inputs().skip_binder()[0];
425 let to = sig.output().skip_binder();
426 self.check_transmute(expr.span, from, to);
431 hir::ExprKind::InlineAsm(asm) => self.check_asm(asm),
436 intravisit::walk_expr(self, expr);