]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_passes/src/intrinsicck.rs
Rollup merge of #89509 - jhpratt:stabilize-const_unreachable_unchecked, r=oli-obk
[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         is_input: bool,
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,
152             _ => unreachable!(),
153         };
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) => {
168                 Some(asm_ty_isize)
169             }
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))
177                     }
178                     ty::Int(IntTy::I16) | ty::Uint(UintTy::U16) => {
179                         Some(InlineAsmType::VecI16(fields.len() as u64))
180                     }
181                     ty::Int(IntTy::I32) | ty::Uint(UintTy::U32) => {
182                         Some(InlineAsmType::VecI32(fields.len() as u64))
183                     }
184                     ty::Int(IntTy::I64) | ty::Uint(UintTy::U64) => {
185                         Some(InlineAsmType::VecI64(fields.len() as u64))
186                     }
187                     ty::Int(IntTy::I128) | ty::Uint(UintTy::U128) => {
188                         Some(InlineAsmType::VecI128(fields.len() as u64))
189                     }
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),
195                             _ => unreachable!(),
196                         })
197                     }
198                     ty::Float(FloatTy::F32) => Some(InlineAsmType::VecF32(fields.len() as u64)),
199                     ty::Float(FloatTy::F64) => Some(InlineAsmType::VecF64(fields.len() as u64)),
200                     _ => None,
201                 }
202             }
203             _ => None,
204         };
205         let asm_ty = match asm_ty {
206             Some(asm_ty) => asm_ty,
207             None => {
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);
210                 err.note(
211                     "only integers, floats, SIMD vectors, pointers and function pointers \
212                      can be used as arguments for inline assembly",
213                 );
214                 err.emit();
215                 return None;
216             }
217         };
218
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));
225             err.emit();
226         }
227
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.
230         //
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.
233         //
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
236         // size).
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);
241                 err.span_label(
242                     in_expr.span,
243                     &format!("type `{}`", self.typeck_results.expr_ty_adjusted(in_expr)),
244                 );
245                 err.span_label(expr.span, &format!("type `{}`", ty));
246                 err.note(
247                     "asm inout arguments must have the same type, \
248                     unless they are both pointers or integers of the same size",
249                 );
250                 err.emit();
251             }
252
253             // All of the later checks have already been done on the input, so
254             // let's not emit errors and warnings twice.
255             return Some(asm_ty);
256         }
257
258         // Check the type against the list of types supported by the selected
259         // register class.
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,
265             None => {
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();
270                 err.note(&format!(
271                     "register class `{}` supports these types: {}",
272                     reg_class.name(),
273                     supported_tys.join(", "),
274                 ));
275                 if let Some(suggest) = reg_class.suggest_class(asm_arch, asm_ty) {
276                     err.help(&format!(
277                         "consider using the `{}` register class instead",
278                         suggest.name()
279                     ));
280                 }
281                 err.emit();
282                 return Some(asm_ty);
283             }
284         };
285
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.
292         //
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)
300             {
301                 let msg = &format!("`{}` target feature is not enabled", feature);
302                 let mut err = self.tcx.sess.struct_span_err(expr.span, msg);
303                 err.note(&format!(
304                     "this is required to use type `{}` with register class `{}`",
305                     ty,
306                     reg_class.name(),
307                 ));
308                 err.emit();
309                 return Some(asm_ty);
310             }
311         }
312
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)
316         {
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
322                 {
323                     if operand_idx == idx && modifier.is_none() {
324                         spans.push(span);
325                     }
326                 }
327             }
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,
333                     expr.hir_id,
334                     spans,
335                     |lint| {
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");
339                         err.help(&format!(
340                             "use the `{}` modifier to have the register formatted as `{}`",
341                             suggested_modifier, suggested_result,
342                         ));
343                         err.help(&format!(
344                             "or use the `{}` modifier to keep the default formatting of `{}`",
345                             default_modifier, default_result,
346                         ));
347                         err.emit();
348                     },
349                 );
350             }
351         }
352
353         Some(asm_ty)
354     }
355
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.
365             //
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.
369             //
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())
377                     {
378                         match feature {
379                             Some(feature) => {
380                                 let feat_sym = Symbol::intern(feature);
381                                 if self.tcx.sess.target_features.contains(&feat_sym)
382                                     || attrs.target_features.contains(&feat_sym)
383                                 {
384                                     missing_required_features.clear();
385                                     break;
386                                 } else {
387                                     missing_required_features.push(feature);
388                                 }
389                             }
390                             None => {
391                                 missing_required_features.clear();
392                                 break;
393                             }
394                         }
395                     }
396
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[..] {
401                         [] => {}
402                         [feature] => {
403                             let msg = format!(
404                                 "register class `{}` requires the `{}` target feature",
405                                 reg_class.name(),
406                                 feature
407                             );
408                             self.tcx.sess.struct_span_err(*op_sp, &msg).emit();
409                             // register isn't enabled, don't do more checks
410                             continue;
411                         }
412                         features => {
413                             let msg = format!(
414                                 "register class `{}` requires at least one of the following target features: {}",
415                                 reg_class.name(),
416                                 features.join(", ")
417                             );
418                             self.tcx.sess.struct_span_err(*op_sp, &msg).emit();
419                             // register isn't enabled, don't do more checks
420                             continue;
421                         }
422                     }
423                 }
424             }
425
426             match *op {
427                 hir::InlineAsmOperand::In { reg, ref expr } => {
428                     self.check_asm_operand_type(
429                         idx,
430                         reg,
431                         expr,
432                         asm.template,
433                         true,
434                         None,
435                         &attrs.target_features,
436                     );
437                 }
438                 hir::InlineAsmOperand::Out { reg, late: _, ref expr } => {
439                     if let Some(expr) = expr {
440                         self.check_asm_operand_type(
441                             idx,
442                             reg,
443                             expr,
444                             asm.template,
445                             false,
446                             None,
447                             &attrs.target_features,
448                         );
449                     }
450                 }
451                 hir::InlineAsmOperand::InOut { reg, late: _, ref expr } => {
452                     self.check_asm_operand_type(
453                         idx,
454                         reg,
455                         expr,
456                         asm.template,
457                         false,
458                         None,
459                         &attrs.target_features,
460                     );
461                 }
462                 hir::InlineAsmOperand::SplitInOut { reg, late: _, ref in_expr, ref out_expr } => {
463                     let in_ty = self.check_asm_operand_type(
464                         idx,
465                         reg,
466                         in_expr,
467                         asm.template,
468                         true,
469                         None,
470                         &attrs.target_features,
471                     );
472                     if let Some(out_expr) = out_expr {
473                         self.check_asm_operand_type(
474                             idx,
475                             reg,
476                             out_expr,
477                             asm.template,
478                             false,
479                             Some((in_expr, in_ty)),
480                             &attrs.target_features,
481                         );
482                     }
483                 }
484                 hir::InlineAsmOperand::Const { .. } | hir::InlineAsmOperand::Sym { .. } => {}
485             }
486         }
487     }
488 }
489
490 impl Visitor<'tcx> for ItemVisitor<'tcx> {
491     type Map = intravisit::ErasedMap<'tcx>;
492
493     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
494         NestedVisitorMap::None
495     }
496
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);
504     }
505 }
506
507 impl Visitor<'tcx> for ExprVisitor<'tcx> {
508     type Map = intravisit::ErasedMap<'tcx>;
509
510     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
511         NestedVisitorMap::None
512     }
513
514     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
515         match expr.kind {
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);
525                     }
526                 }
527             }
528
529             hir::ExprKind::InlineAsm(asm) => self.check_asm(asm, expr.hir_id),
530
531             _ => {}
532         }
533
534         intravisit::walk_expr(self, expr);
535     }
536 }