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],
143 tied_input: Option<(&hir::Expr<'tcx>, Option<InlineAsmType>)>,
144 target_features: &[Symbol],
145 ) -> Option<InlineAsmType> {
146 // Check the type against the allowed types for inline asm.
147 let ty = self.typeck_results.expr_ty_adjusted(expr);
148 let asm_ty_isize = match self.tcx.sess.target.pointer_width {
149 16 => InlineAsmType::I16,
150 32 => InlineAsmType::I32,
151 64 => InlineAsmType::I64,
154 let asm_ty = match *ty.kind() {
155 // `!` is allowed for input but not for output (issue #87802)
156 ty::Never if is_input => return None,
157 ty::Error(_) => return None,
158 ty::Int(IntTy::I8) | ty::Uint(UintTy::U8) => Some(InlineAsmType::I8),
159 ty::Int(IntTy::I16) | ty::Uint(UintTy::U16) => Some(InlineAsmType::I16),
160 ty::Int(IntTy::I32) | ty::Uint(UintTy::U32) => Some(InlineAsmType::I32),
161 ty::Int(IntTy::I64) | ty::Uint(UintTy::U64) => Some(InlineAsmType::I64),
162 ty::Int(IntTy::I128) | ty::Uint(UintTy::U128) => Some(InlineAsmType::I128),
163 ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize) => Some(asm_ty_isize),
164 ty::Float(FloatTy::F32) => Some(InlineAsmType::F32),
165 ty::Float(FloatTy::F64) => Some(InlineAsmType::F64),
166 ty::FnPtr(_) => Some(asm_ty_isize),
167 ty::RawPtr(ty::TypeAndMut { ty, mutbl: _ }) if self.is_thin_ptr_ty(ty) => {
170 ty::Adt(adt, substs) if adt.repr.simd() => {
171 let fields = &adt.non_enum_variant().fields;
172 let elem_ty = fields[0].ty(self.tcx, substs);
173 match elem_ty.kind() {
174 ty::Never | ty::Error(_) => return None,
175 ty::Int(IntTy::I8) | ty::Uint(UintTy::U8) => {
176 Some(InlineAsmType::VecI8(fields.len() as u64))
178 ty::Int(IntTy::I16) | ty::Uint(UintTy::U16) => {
179 Some(InlineAsmType::VecI16(fields.len() as u64))
181 ty::Int(IntTy::I32) | ty::Uint(UintTy::U32) => {
182 Some(InlineAsmType::VecI32(fields.len() as u64))
184 ty::Int(IntTy::I64) | ty::Uint(UintTy::U64) => {
185 Some(InlineAsmType::VecI64(fields.len() as u64))
187 ty::Int(IntTy::I128) | ty::Uint(UintTy::U128) => {
188 Some(InlineAsmType::VecI128(fields.len() as u64))
190 ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize) => {
191 Some(match self.tcx.sess.target.pointer_width {
192 16 => InlineAsmType::VecI16(fields.len() as u64),
193 32 => InlineAsmType::VecI32(fields.len() as u64),
194 64 => InlineAsmType::VecI64(fields.len() as u64),
198 ty::Float(FloatTy::F32) => Some(InlineAsmType::VecF32(fields.len() as u64)),
199 ty::Float(FloatTy::F64) => Some(InlineAsmType::VecF64(fields.len() as u64)),
205 let asm_ty = match asm_ty {
206 Some(asm_ty) => asm_ty,
208 let msg = &format!("cannot use value of type `{}` for inline assembly", ty);
209 let mut err = self.tcx.sess.struct_span_err(expr.span, msg);
211 "only integers, floats, SIMD vectors, pointers and function pointers \
212 can be used as arguments for inline assembly",
219 // Check that the type implements Copy. The only case where this can
220 // possibly fail is for SIMD types which don't #[derive(Copy)].
221 if !ty.is_copy_modulo_regions(self.tcx.at(DUMMY_SP), self.param_env) {
222 let msg = "arguments for inline assembly must be copyable";
223 let mut err = self.tcx.sess.struct_span_err(expr.span, msg);
224 err.note(&format!("`{}` does not implement the Copy trait", ty));
228 // Ideally we wouldn't need to do this, but LLVM's register allocator
229 // really doesn't like it when tied operands have different types.
231 // This is purely an LLVM limitation, but we have to live with it since
232 // there is no way to hide this with implicit conversions.
234 // For the purposes of this check we only look at the `InlineAsmType`,
235 // which means that pointers and integers are treated as identical (modulo
237 if let Some((in_expr, Some(in_asm_ty))) = tied_input {
238 if in_asm_ty != asm_ty {
239 let msg = "incompatible types for asm inout argument";
240 let mut err = self.tcx.sess.struct_span_err(vec![in_expr.span, expr.span], msg);
243 &format!("type `{}`", self.typeck_results.expr_ty_adjusted(in_expr)),
245 err.span_label(expr.span, &format!("type `{}`", ty));
247 "asm inout arguments must have the same type, \
248 unless they are both pointers or integers of the same size",
253 // All of the later checks have already been done on the input, so
254 // let's not emit errors and warnings twice.
258 // Check the type against the list of types supported by the selected
260 let asm_arch = self.tcx.sess.asm_arch.unwrap();
261 let reg_class = reg.reg_class();
262 let supported_tys = reg_class.supported_types(asm_arch);
263 let feature = match supported_tys.iter().find(|&&(t, _)| t == asm_ty) {
264 Some((_, feature)) => feature,
266 let msg = &format!("type `{}` cannot be used with this register class", ty);
267 let mut err = self.tcx.sess.struct_span_err(expr.span, msg);
268 let supported_tys: Vec<_> =
269 supported_tys.iter().map(|(t, _)| t.to_string()).collect();
271 "register class `{}` supports these types: {}",
273 supported_tys.join(", "),
275 if let Some(suggest) = reg_class.suggest_class(asm_arch, asm_ty) {
277 "consider using the `{}` register class instead",
286 // Check whether the selected type requires a target feature. Note that
287 // this is different from the feature check we did earlier. While the
288 // previous check checked that this register class is usable at all
289 // with the currently enabled features, some types may only be usable
290 // with a register class when a certain feature is enabled. We check
291 // this here since it depends on the results of typeck.
293 // Also note that this check isn't run when the operand type is never
294 // (!). In that case we still need the earlier check to verify that the
295 // register class is usable at all.
296 if let Some(feature) = feature {
297 let feat_sym = Symbol::intern(feature);
298 if !self.tcx.sess.target_features.contains(&feat_sym)
299 && !target_features.contains(&feat_sym)
301 let msg = &format!("`{}` target feature is not enabled", feature);
302 let mut err = self.tcx.sess.struct_span_err(expr.span, msg);
304 "this is required to use type `{}` with register class `{}`",
313 // Check whether a modifier is suggested for using this type.
314 if let Some((suggested_modifier, suggested_result)) =
315 reg_class.suggest_modifier(asm_arch, asm_ty)
317 // Search for any use of this operand without a modifier and emit
318 // the suggestion for them.
319 let mut spans = vec![];
320 for piece in template {
321 if let &InlineAsmTemplatePiece::Placeholder { operand_idx, modifier, span } = piece
323 if operand_idx == idx && modifier.is_none() {
328 if !spans.is_empty() {
329 let (default_modifier, default_result) =
330 reg_class.default_modifier(asm_arch).unwrap();
331 self.tcx.struct_span_lint_hir(
332 lint::builtin::ASM_SUB_REGISTER,
336 let msg = "formatting may not be suitable for sub-register argument";
337 let mut err = lint.build(msg);
338 err.span_label(expr.span, "for this argument");
340 "use the `{}` modifier to have the register formatted as `{}`",
341 suggested_modifier, suggested_result,
344 "or use the `{}` modifier to keep the default formatting of `{}`",
345 default_modifier, default_result,
356 fn check_asm(&self, asm: &hir::InlineAsm<'tcx>, hir_id: hir::HirId) {
357 let hir = self.tcx.hir();
358 let enclosing_id = hir.enclosing_body_owner(hir_id);
359 let enclosing_def_id = hir.local_def_id(enclosing_id).to_def_id();
360 let attrs = self.tcx.codegen_fn_attrs(enclosing_def_id);
361 for (idx, (op, op_sp)) in asm.operands.iter().enumerate() {
362 // Validate register classes against currently enabled target
363 // features. We check that at least one type is available for
364 // the enabled features.
366 // We ignore target feature requirements for clobbers: if the
367 // feature is disabled then the compiler doesn't care what we
368 // do with the registers.
370 // Note that this is only possible for explicit register
371 // operands, which cannot be used in the asm string.
372 if let Some(reg) = op.reg() {
373 if !op.is_clobber() {
374 let mut missing_required_features = vec![];
375 let reg_class = reg.reg_class();
376 for &(_, feature) in reg_class.supported_types(self.tcx.sess.asm_arch.unwrap())
380 let feat_sym = Symbol::intern(feature);
381 if self.tcx.sess.target_features.contains(&feat_sym)
382 || attrs.target_features.contains(&feat_sym)
384 missing_required_features.clear();
387 missing_required_features.push(feature);
391 missing_required_features.clear();
397 // We are sorting primitive strs here and can use unstable sort here
398 missing_required_features.sort_unstable();
399 missing_required_features.dedup();
400 match &missing_required_features[..] {
404 "register class `{}` requires the `{}` target feature",
408 self.tcx.sess.struct_span_err(*op_sp, &msg).emit();
409 // register isn't enabled, don't do more checks
414 "register class `{}` requires at least one of the following target features: {}",
418 self.tcx.sess.struct_span_err(*op_sp, &msg).emit();
419 // register isn't enabled, don't do more checks
427 hir::InlineAsmOperand::In { reg, ref expr } => {
428 self.check_asm_operand_type(
435 &attrs.target_features,
438 hir::InlineAsmOperand::Out { reg, late: _, ref expr } => {
439 if let Some(expr) = expr {
440 self.check_asm_operand_type(
447 &attrs.target_features,
451 hir::InlineAsmOperand::InOut { reg, late: _, ref expr } => {
452 self.check_asm_operand_type(
459 &attrs.target_features,
462 hir::InlineAsmOperand::SplitInOut { reg, late: _, ref in_expr, ref out_expr } => {
463 let in_ty = self.check_asm_operand_type(
470 &attrs.target_features,
472 if let Some(out_expr) = out_expr {
473 self.check_asm_operand_type(
479 Some((in_expr, in_ty)),
480 &attrs.target_features,
484 hir::InlineAsmOperand::Const { .. } | hir::InlineAsmOperand::Sym { .. } => {}
490 impl Visitor<'tcx> for ItemVisitor<'tcx> {
491 type Map = intravisit::ErasedMap<'tcx>;
493 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
494 NestedVisitorMap::None
497 fn visit_nested_body(&mut self, body_id: hir::BodyId) {
498 let owner_def_id = self.tcx.hir().body_owner_def_id(body_id);
499 let body = self.tcx.hir().body(body_id);
500 let param_env = self.tcx.param_env(owner_def_id.to_def_id());
501 let typeck_results = self.tcx.typeck(owner_def_id);
502 ExprVisitor { tcx: self.tcx, param_env, typeck_results }.visit_body(body);
503 self.visit_body(body);
507 impl Visitor<'tcx> for ExprVisitor<'tcx> {
508 type Map = intravisit::ErasedMap<'tcx>;
510 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
511 NestedVisitorMap::None
514 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
516 hir::ExprKind::Path(ref qpath) => {
517 let res = self.typeck_results.qpath_res(qpath, expr.hir_id);
518 if let Res::Def(DefKind::Fn, did) = res {
519 if self.def_id_is_transmute(did) {
520 let typ = self.typeck_results.node_type(expr.hir_id);
521 let sig = typ.fn_sig(self.tcx);
522 let from = sig.inputs().skip_binder()[0];
523 let to = sig.output().skip_binder();
524 self.check_transmute(expr.span, from, to);
529 hir::ExprKind::InlineAsm(asm) => self.check_asm(asm, expr.hir_id),
534 intravisit::walk_expr(self, expr);