]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_passes/src/intrinsicck.rs
Use AnonConst for asm! constants
[rust.git] / compiler / rustc_passes / src / intrinsicck.rs
1 use rustc_ast::InlineAsmTemplatePiece;
2 use rustc_errors::struct_span_err;
3 use rustc_hir as hir;
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;
16
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());
19 }
20
21 pub fn provide(providers: &mut Providers) {
22     *providers = Providers { check_mod_intrinsics, ..*providers };
23 }
24
25 struct ItemVisitor<'tcx> {
26     tcx: TyCtxt<'tcx>,
27 }
28
29 struct ExprVisitor<'tcx> {
30     tcx: TyCtxt<'tcx>,
31     typeck_results: &'tcx ty::TypeckResults<'tcx>,
32     param_env: ty::ParamEnv<'tcx>,
33 }
34
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),
40         _ => return ty,
41     };
42
43     if def.variants.len() == 2 && !def.repr.c() && def.repr.int.is_none() {
44         let data_idx;
45
46         let one = VariantIdx::new(1);
47         let zero = VariantIdx::new(0);
48
49         if def.variants[zero].fields.is_empty() {
50             data_idx = one;
51         } else if def.variants[one].fields.is_empty() {
52             data_idx = zero;
53         } else {
54             return ty;
55         }
56
57         if def.variants[data_idx].fields.len() == 1 {
58             return def.variants[data_idx].fields[0].ty(tcx, substs);
59         }
60     }
61
62     ty
63 }
64
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
69     }
70
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);
74
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) {
78                 return;
79             }
80
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")
90                         .emit();
91                     return;
92                 }
93             }
94         }
95
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)) => {
101                 if bad == ty {
102                     "this type does not have a fixed size".to_owned()
103                 } else {
104                     format!("size can vary because of {}", bad)
105                 }
106             }
107             Err(err) => err.to_string(),
108         };
109
110         let mut err = struct_span_err!(
111             self.tcx.sess,
112             span,
113             E0512,
114             "cannot transmute between types of different sizes, \
115                                         or dependently-sized types"
116         );
117         if from == to {
118             err.note(&format!("`{}` does not have a fixed size", from));
119         } else {
120             err.note(&format!("source type: `{}` ({})", from, skeleton_string(from, sk_from)))
121                 .note(&format!("target type: `{}` ({})", to, skeleton_string(to, sk_to)));
122         }
123         err.emit()
124     }
125
126     fn is_thin_ptr_ty(&self, ty: Ty<'tcx>) -> bool {
127         if ty.is_sized(self.tcx.at(DUMMY_SP), self.param_env) {
128             return true;
129         }
130         if let ty::Foreign(..) = ty.kind() {
131             return true;
132         }
133         false
134     }
135
136     fn check_asm_operand_type(
137         &self,
138         idx: usize,
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,
150             _ => unreachable!(),
151         };
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) => {
164                 Some(asm_ty_isize)
165             }
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))
173                     }
174                     ty::Int(IntTy::I16) | ty::Uint(UintTy::U16) => {
175                         Some(InlineAsmType::VecI16(fields.len() as u64))
176                     }
177                     ty::Int(IntTy::I32) | ty::Uint(UintTy::U32) => {
178                         Some(InlineAsmType::VecI32(fields.len() as u64))
179                     }
180                     ty::Int(IntTy::I64) | ty::Uint(UintTy::U64) => {
181                         Some(InlineAsmType::VecI64(fields.len() as u64))
182                     }
183                     ty::Int(IntTy::I128) | ty::Uint(UintTy::U128) => {
184                         Some(InlineAsmType::VecI128(fields.len() as u64))
185                     }
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),
191                             _ => unreachable!(),
192                         })
193                     }
194                     ty::Float(FloatTy::F32) => Some(InlineAsmType::VecF32(fields.len() as u64)),
195                     ty::Float(FloatTy::F64) => Some(InlineAsmType::VecF64(fields.len() as u64)),
196                     _ => None,
197                 }
198             }
199             _ => None,
200         };
201         let asm_ty = match asm_ty {
202             Some(asm_ty) => asm_ty,
203             None => {
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);
206                 err.note(
207                     "only integers, floats, SIMD vectors, pointers and function pointers \
208                      can be used as arguments for inline assembly",
209                 );
210                 err.emit();
211                 return None;
212             }
213         };
214
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));
221             err.emit();
222         }
223
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.
226         //
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.
229         //
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
232         // size).
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);
237                 err.span_label(
238                     in_expr.span,
239                     &format!("type `{}`", self.typeck_results.expr_ty_adjusted(in_expr)),
240                 );
241                 err.span_label(expr.span, &format!("type `{}`", ty));
242                 err.note(
243                     "asm inout arguments must have the same type, \
244                     unless they are both pointers or integers of the same size",
245                 );
246                 err.emit();
247             }
248
249             // All of the later checks have already been done on the input, so
250             // let's not emit errors and warnings twice.
251             return Some(asm_ty);
252         }
253
254         // Check the type against the list of types supported by the selected
255         // register class.
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,
261             None => {
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();
266                 err.note(&format!(
267                     "register class `{}` supports these types: {}",
268                     reg_class.name(),
269                     supported_tys.join(", "),
270                 ));
271                 if let Some(suggest) = reg_class.suggest_class(asm_arch, asm_ty) {
272                     err.help(&format!(
273                         "consider using the `{}` register class instead",
274                         suggest.name()
275                     ));
276                 }
277                 err.emit();
278                 return Some(asm_ty);
279             }
280         };
281
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.
288         //
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);
296                 err.note(&format!(
297                     "this is required to use type `{}` with register class `{}`",
298                     ty,
299                     reg_class.name(),
300                 ));
301                 err.emit();
302                 return Some(asm_ty);
303             }
304         }
305
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)
309         {
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
315                 {
316                     if operand_idx == idx && modifier.is_none() {
317                         spans.push(span);
318                     }
319                 }
320             }
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,
326                     expr.hir_id,
327                     spans,
328                     |lint| {
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");
332                         err.help(&format!(
333                             "use the `{}` modifier to have the register formatted as `{}`",
334                             suggested_modifier, suggested_result,
335                         ));
336                         err.help(&format!(
337                             "or use the `{}` modifier to keep the default formatting of `{}`",
338                             default_modifier, default_result,
339                         ));
340                         err.emit();
341                     },
342                 );
343             }
344         }
345
346         Some(asm_ty)
347     }
348
349     fn check_asm(&self, asm: &hir::InlineAsm<'tcx>) {
350         for (idx, (op, op_sp)) in asm.operands.iter().enumerate() {
351             match *op {
352                 hir::InlineAsmOperand::In { reg, ref expr } => {
353                     self.check_asm_operand_type(idx, reg, expr, asm.template, None);
354                 }
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);
358                     }
359                 }
360                 hir::InlineAsmOperand::InOut { reg, late: _, ref expr } => {
361                     self.check_asm_operand_type(idx, reg, expr, asm.template, None);
362                 }
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(
367                             idx,
368                             reg,
369                             out_expr,
370                             asm.template,
371                             Some((in_expr, in_ty)),
372                         );
373                     }
374                 }
375                 hir::InlineAsmOperand::Const { ref anon_const } => {
376                     let anon_const_def_id = self.tcx.hir().local_def_id(anon_const.hir_id);
377                     let value = ty::Const::from_anon_const(self.tcx, anon_const_def_id);
378                     match value.ty.kind() {
379                         ty::Int(_) | ty::Uint(_) | ty::Float(_) => {}
380                         _ => {
381                             let msg =
382                                 "asm `const` arguments must be integer or floating-point values";
383                             self.tcx.sess.span_err(*op_sp, msg);
384                         }
385                     }
386                 }
387                 hir::InlineAsmOperand::Sym { .. } => {}
388             }
389         }
390     }
391 }
392
393 impl Visitor<'tcx> for ItemVisitor<'tcx> {
394     type Map = intravisit::ErasedMap<'tcx>;
395
396     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
397         NestedVisitorMap::None
398     }
399
400     fn visit_nested_body(&mut self, body_id: hir::BodyId) {
401         let owner_def_id = self.tcx.hir().body_owner_def_id(body_id);
402         let body = self.tcx.hir().body(body_id);
403         let param_env = self.tcx.param_env(owner_def_id.to_def_id());
404         let typeck_results = self.tcx.typeck(owner_def_id);
405         ExprVisitor { tcx: self.tcx, param_env, typeck_results }.visit_body(body);
406         self.visit_body(body);
407     }
408 }
409
410 impl Visitor<'tcx> for ExprVisitor<'tcx> {
411     type Map = intravisit::ErasedMap<'tcx>;
412
413     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
414         NestedVisitorMap::None
415     }
416
417     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
418         match expr.kind {
419             hir::ExprKind::Path(ref qpath) => {
420                 let res = self.typeck_results.qpath_res(qpath, expr.hir_id);
421                 if let Res::Def(DefKind::Fn, did) = res {
422                     if self.def_id_is_transmute(did) {
423                         let typ = self.typeck_results.node_type(expr.hir_id);
424                         let sig = typ.fn_sig(self.tcx);
425                         let from = sig.inputs().skip_binder()[0];
426                         let to = sig.output().skip_binder();
427                         self.check_transmute(expr.span, from, to);
428                     }
429                 }
430             }
431
432             hir::ExprKind::InlineAsm(asm) => self.check_asm(asm),
433
434             _ => {}
435         }
436
437         intravisit::walk_expr(self, expr);
438     }
439 }