1 use rustc_ast::InlineAsmTemplatePiece;
2 use rustc_data_structures::stable_set::FxHashSet;
3 use rustc_errors::struct_span_err;
5 use rustc_hir::def::{DefKind, Res};
6 use rustc_hir::def_id::{DefId, LocalDefId};
7 use rustc_hir::intravisit::{self, Visitor};
8 use rustc_index::vec::Idx;
9 use rustc_middle::ty::layout::{LayoutError, SizeSkeleton};
10 use rustc_middle::ty::query::Providers;
11 use rustc_middle::ty::{self, FloatTy, IntTy, Ty, TyCtxt, UintTy};
12 use rustc_session::lint;
13 use rustc_span::{sym, Span, Symbol, DUMMY_SP};
14 use rustc_target::abi::{Pointer, VariantIdx};
15 use rustc_target::asm::{InlineAsmRegOrRegClass, InlineAsmType};
16 use rustc_target::spec::abi::Abi::RustIntrinsic;
18 fn check_mod_intrinsics(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
19 tcx.hir().visit_item_likes_in_module(module_def_id, &mut ItemVisitor { tcx }.as_deep_visitor());
22 pub fn provide(providers: &mut Providers) {
23 *providers = Providers { check_mod_intrinsics, ..*providers };
26 struct ItemVisitor<'tcx> {
30 struct ExprVisitor<'tcx> {
32 typeck_results: &'tcx ty::TypeckResults<'tcx>,
33 param_env: ty::ParamEnv<'tcx>,
36 /// If the type is `Option<T>`, it will return `T`, otherwise
37 /// the type itself. Works on most `Option`-like types.
38 fn unpack_option_like<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
39 let ty::Adt(def, substs) = *ty.kind() else { return ty };
41 if def.variants().len() == 2 && !def.repr().c() && def.repr().int.is_none() {
44 let one = VariantIdx::new(1);
45 let zero = VariantIdx::new(0);
47 if def.variant(zero).fields.is_empty() {
49 } else if def.variant(one).fields.is_empty() {
55 if def.variant(data_idx).fields.len() == 1 {
56 return def.variant(data_idx).fields[0].ty(tcx, substs);
63 impl<'tcx> ExprVisitor<'tcx> {
64 fn def_id_is_transmute(&self, def_id: DefId) -> bool {
65 self.tcx.fn_sig(def_id).abi() == RustIntrinsic
66 && self.tcx.item_name(def_id) == sym::transmute
69 fn check_transmute(&self, span: Span, from: Ty<'tcx>, to: Ty<'tcx>) {
70 let sk_from = SizeSkeleton::compute(from, self.tcx, self.param_env);
71 let sk_to = SizeSkeleton::compute(to, self.tcx, self.param_env);
73 // Check for same size using the skeletons.
74 if let (Ok(sk_from), Ok(sk_to)) = (sk_from, sk_to) {
75 if sk_from.same_size(sk_to) {
79 // Special-case transmuting from `typeof(function)` and
80 // `Option<typeof(function)>` to present a clearer error.
81 let from = unpack_option_like(self.tcx, from);
82 if let (&ty::FnDef(..), SizeSkeleton::Known(size_to)) = (from.kind(), sk_to) && size_to == Pointer.size(&self.tcx) {
83 struct_span_err!(self.tcx.sess, span, E0591, "can't transmute zero-sized type")
84 .note(&format!("source type: {from}"))
85 .note(&format!("target type: {to}"))
86 .help("cast with `as` to a pointer instead")
92 // Try to display a sensible error with as much information as possible.
93 let skeleton_string = |ty: Ty<'tcx>, sk| match sk {
94 Ok(SizeSkeleton::Known(size)) => format!("{} bits", size.bits()),
95 Ok(SizeSkeleton::Pointer { tail, .. }) => format!("pointer to `{tail}`"),
96 Err(LayoutError::Unknown(bad)) => {
98 "this type does not have a fixed size".to_owned()
100 format!("size can vary because of {bad}")
103 Err(err) => err.to_string(),
106 let mut err = struct_span_err!(
110 "cannot transmute between types of different sizes, \
111 or dependently-sized types"
114 err.note(&format!("`{from}` does not have a fixed size"));
116 err.note(&format!("source type: `{}` ({})", from, skeleton_string(from, sk_from)))
117 .note(&format!("target type: `{}` ({})", to, skeleton_string(to, sk_to)));
122 fn is_thin_ptr_ty(&self, ty: Ty<'tcx>) -> bool {
123 if ty.is_sized(self.tcx.at(DUMMY_SP), self.param_env) {
126 if let ty::Foreign(..) = ty.kind() {
132 fn check_asm_operand_type(
135 reg: InlineAsmRegOrRegClass,
136 expr: &hir::Expr<'tcx>,
137 template: &[InlineAsmTemplatePiece],
139 tied_input: Option<(&hir::Expr<'tcx>, Option<InlineAsmType>)>,
140 target_features: &FxHashSet<Symbol>,
141 ) -> Option<InlineAsmType> {
142 // Check the type against the allowed types for inline asm.
143 let ty = self.typeck_results.expr_ty_adjusted(expr);
144 let asm_ty_isize = match self.tcx.sess.target.pointer_width {
145 16 => InlineAsmType::I16,
146 32 => InlineAsmType::I32,
147 64 => InlineAsmType::I64,
150 let asm_ty = match *ty.kind() {
151 // `!` is allowed for input but not for output (issue #87802)
152 ty::Never if is_input => return None,
153 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 Some(asm_ty) = asm_ty else {
202 let msg = &format!("cannot use value of type `{ty}` for inline assembly");
203 let mut err = self.tcx.sess.struct_span_err(expr.span, msg);
205 "only integers, floats, SIMD vectors, pointers and function pointers \
206 can be used as arguments for inline assembly",
212 // Check that the type implements Copy. The only case where this can
213 // possibly fail is for SIMD types which don't #[derive(Copy)].
214 if !ty.is_copy_modulo_regions(self.tcx.at(DUMMY_SP), self.param_env) {
215 let msg = "arguments for inline assembly must be copyable";
216 let mut err = self.tcx.sess.struct_span_err(expr.span, msg);
217 err.note(&format!("`{ty}` does not implement the Copy trait"));
221 // Ideally we wouldn't need to do this, but LLVM's register allocator
222 // really doesn't like it when tied operands have different types.
224 // This is purely an LLVM limitation, but we have to live with it since
225 // there is no way to hide this with implicit conversions.
227 // For the purposes of this check we only look at the `InlineAsmType`,
228 // which means that pointers and integers are treated as identical (modulo
230 if let Some((in_expr, Some(in_asm_ty))) = tied_input {
231 if in_asm_ty != asm_ty {
232 let msg = "incompatible types for asm inout argument";
233 let mut err = self.tcx.sess.struct_span_err(vec![in_expr.span, expr.span], msg);
236 &format!("type `{}`", self.typeck_results.expr_ty_adjusted(in_expr)),
238 err.span_label(expr.span, &format!("type `{ty}`"));
240 "asm inout arguments must have the same type, \
241 unless they are both pointers or integers of the same size",
246 // All of the later checks have already been done on the input, so
247 // let's not emit errors and warnings twice.
251 // Check the type against the list of types supported by the selected
253 let asm_arch = self.tcx.sess.asm_arch.unwrap();
254 let reg_class = reg.reg_class();
255 let supported_tys = reg_class.supported_types(asm_arch);
256 let Some((_, feature)) = supported_tys.iter().find(|&&(t, _)| t == asm_ty) else {
257 let msg = &format!("type `{ty}` cannot be used with this register class");
258 let mut err = self.tcx.sess.struct_span_err(expr.span, msg);
259 let supported_tys: Vec<_> =
260 supported_tys.iter().map(|(t, _)| t.to_string()).collect();
262 "register class `{}` supports these types: {}",
264 supported_tys.join(", "),
266 if let Some(suggest) = reg_class.suggest_class(asm_arch, asm_ty) {
268 "consider using the `{}` register class instead",
276 // Check whether the selected type requires a target feature. Note that
277 // this is different from the feature check we did earlier. While the
278 // previous check checked that this register class is usable at all
279 // with the currently enabled features, some types may only be usable
280 // with a register class when a certain feature is enabled. We check
281 // this here since it depends on the results of typeck.
283 // Also note that this check isn't run when the operand type is never
284 // (!). In that case we still need the earlier check to verify that the
285 // register class is usable at all.
286 if let Some(feature) = feature {
287 if !target_features.contains(&feature) {
288 let msg = &format!("`{}` target feature is not enabled", feature);
289 let mut err = self.tcx.sess.struct_span_err(expr.span, msg);
291 "this is required to use type `{}` with register class `{}`",
300 // Check whether a modifier is suggested for using this type.
301 if let Some((suggested_modifier, suggested_result)) =
302 reg_class.suggest_modifier(asm_arch, asm_ty)
304 // Search for any use of this operand without a modifier and emit
305 // the suggestion for them.
306 let mut spans = vec![];
307 for piece in template {
308 if let &InlineAsmTemplatePiece::Placeholder { operand_idx, modifier, span } = piece
310 if operand_idx == idx && modifier.is_none() {
315 if !spans.is_empty() {
316 let (default_modifier, default_result) =
317 reg_class.default_modifier(asm_arch).unwrap();
318 self.tcx.struct_span_lint_hir(
319 lint::builtin::ASM_SUB_REGISTER,
323 let msg = "formatting may not be suitable for sub-register argument";
324 let mut err = lint.build(msg);
325 err.span_label(expr.span, "for this argument");
327 "use the `{suggested_modifier}` modifier to have the register formatted as `{suggested_result}`",
330 "or use the `{default_modifier}` modifier to keep the default formatting of `{default_result}`",
341 fn check_asm(&self, asm: &hir::InlineAsm<'tcx>, hir_id: hir::HirId) {
342 let hir = self.tcx.hir();
343 let enclosing_id = hir.enclosing_body_owner(hir_id);
344 let enclosing_def_id = hir.local_def_id(enclosing_id).to_def_id();
345 let target_features = self.tcx.asm_target_features(enclosing_def_id);
346 let asm_arch = self.tcx.sess.asm_arch.unwrap();
347 for (idx, (op, op_sp)) in asm.operands.iter().enumerate() {
348 // Validate register classes against currently enabled target
349 // features. We check that at least one type is available for
350 // the enabled features.
352 // We ignore target feature requirements for clobbers: if the
353 // feature is disabled then the compiler doesn't care what we
354 // do with the registers.
356 // Note that this is only possible for explicit register
357 // operands, which cannot be used in the asm string.
358 if let Some(reg) = op.reg() {
359 // Some explicit registers cannot be used depending on the
360 // target. Reject those here.
361 if let InlineAsmRegOrRegClass::Reg(reg) = reg {
362 if let Err(msg) = reg.validate(
364 self.tcx.sess.relocation_model(),
366 &self.tcx.sess.target,
369 let msg = format!("cannot use register `{}`: {}", reg.name(), msg);
370 self.tcx.sess.struct_span_err(*op_sp, &msg).emit();
375 if !op.is_clobber() {
376 let mut missing_required_features = vec![];
377 let reg_class = reg.reg_class();
378 for &(_, feature) in reg_class.supported_types(asm_arch) {
381 if target_features.contains(&feature) {
382 missing_required_features.clear();
385 missing_required_features.push(feature);
389 missing_required_features.clear();
395 // We are sorting primitive strs here and can use unstable sort here
396 missing_required_features.sort_unstable();
397 missing_required_features.dedup();
398 match &missing_required_features[..] {
402 "register class `{}` requires the `{}` target feature",
406 self.tcx.sess.struct_span_err(*op_sp, &msg).emit();
407 // register isn't enabled, don't do more checks
412 "register class `{}` requires at least one of the following target features: {}",
418 .collect::<String>(),
420 self.tcx.sess.struct_span_err(*op_sp, &msg).emit();
421 // register isn't enabled, don't do more checks
429 hir::InlineAsmOperand::In { reg, ref expr } => {
430 self.check_asm_operand_type(
440 hir::InlineAsmOperand::Out { reg, late: _, ref expr } => {
441 if let Some(expr) = expr {
442 self.check_asm_operand_type(
453 hir::InlineAsmOperand::InOut { reg, late: _, ref expr } => {
454 self.check_asm_operand_type(
464 hir::InlineAsmOperand::SplitInOut { reg, late: _, ref in_expr, ref out_expr } => {
465 let in_ty = self.check_asm_operand_type(
474 if let Some(out_expr) = out_expr {
475 self.check_asm_operand_type(
481 Some((in_expr, in_ty)),
486 hir::InlineAsmOperand::Const { .. } | hir::InlineAsmOperand::Sym { .. } => {}
492 impl<'tcx> Visitor<'tcx> for ItemVisitor<'tcx> {
493 fn visit_nested_body(&mut self, body_id: hir::BodyId) {
494 let owner_def_id = self.tcx.hir().body_owner_def_id(body_id);
495 let body = self.tcx.hir().body(body_id);
496 let param_env = self.tcx.param_env(owner_def_id.to_def_id());
497 let typeck_results = self.tcx.typeck(owner_def_id);
498 ExprVisitor { tcx: self.tcx, param_env, typeck_results }.visit_body(body);
499 self.visit_body(body);
503 impl<'tcx> Visitor<'tcx> for ExprVisitor<'tcx> {
504 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
506 hir::ExprKind::Path(ref qpath) => {
507 let res = self.typeck_results.qpath_res(qpath, expr.hir_id);
508 if let Res::Def(DefKind::Fn, did) = res
509 && self.def_id_is_transmute(did)
511 let typ = self.typeck_results.node_type(expr.hir_id);
512 let sig = typ.fn_sig(self.tcx);
513 let from = sig.inputs().skip_binder()[0];
514 let to = sig.output().skip_binder();
515 self.check_transmute(expr.span, from, to);
519 hir::ExprKind::InlineAsm(asm) => self.check_asm(asm, expr.hir_id),
524 intravisit::walk_expr(self, expr);