1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! This pass type-checks the MIR to ensure it is not broken.
12 #![allow(unreachable_code)]
14 use rustc::infer::{self, InferCtxt, InferOk};
15 use rustc::traits::{self, Reveal};
16 use rustc::ty::fold::TypeFoldable;
17 use rustc::ty::{self, Ty, TyCtxt, TypeVariants};
18 use rustc::middle::const_val::ConstVal;
20 use rustc::mir::tcx::LvalueTy;
21 use rustc::mir::transform::{MirPass, MirSource, Pass};
22 use rustc::mir::visit::Visitor;
25 use syntax_pos::{Span, DUMMY_SP};
27 use rustc_data_structures::indexed_vec::Idx;
29 fn mirbug(tcx: TyCtxt, span: Span, msg: &str) {
30 tcx.sess.diagnostic().span_bug(span, msg);
33 macro_rules! span_mirbug {
34 ($context:expr, $elem:expr, $($message:tt)*) => ({
35 mirbug($context.tcx(), $context.last_span,
36 &format!("broken MIR ({:?}): {}", $elem, format!($($message)*)))
40 macro_rules! span_mirbug_and_err {
41 ($context:expr, $elem:expr, $($message:tt)*) => ({
43 span_mirbug!($context, $elem, $($message)*);
49 enum FieldAccessError {
50 OutOfRange { field_count: usize }
53 /// Verifies that MIR types are sane to not crash further checks.
55 /// The sanitize_XYZ methods here take an MIR object and compute its
56 /// type, calling `span_mirbug` and returning an error type if there
58 struct TypeVerifier<'a, 'b: 'a, 'gcx: 'b+'tcx, 'tcx: 'b> {
59 cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>,
65 impl<'a, 'b, 'gcx, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'gcx, 'tcx> {
66 fn visit_span(&mut self, span: &Span) {
67 if *span != DUMMY_SP {
68 self.last_span = *span;
72 fn visit_lvalue(&mut self,
73 lvalue: &Lvalue<'tcx>,
74 _context: visit::LvalueContext,
76 self.sanitize_lvalue(lvalue, location);
79 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
80 self.super_constant(constant, location);
81 self.sanitize_type(constant, constant.ty);
84 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
85 self.super_rvalue(rvalue, location);
86 let rval_ty = rvalue.ty(self.mir, self.tcx());
87 self.sanitize_type(rvalue, rval_ty);
90 fn visit_mir(&mut self, mir: &Mir<'tcx>) {
91 self.sanitize_type(&"return type", mir.return_ty);
92 for local_decl in &mir.local_decls {
93 self.sanitize_type(local_decl, local_decl.ty);
95 if self.errors_reported {
102 impl<'a, 'b, 'gcx, 'tcx> TypeVerifier<'a, 'b, 'gcx, 'tcx> {
103 fn new(cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>, mir: &'a Mir<'tcx>) -> Self {
108 errors_reported: false
112 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
116 fn sanitize_type(&mut self, parent: &fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
117 if ty.needs_infer() || ty.has_escaping_regions() || ty.references_error() {
118 span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
124 fn sanitize_lvalue(&mut self, lvalue: &Lvalue<'tcx>, location: Location) -> LvalueTy<'tcx> {
125 debug!("sanitize_lvalue: {:?}", lvalue);
127 Lvalue::Local(index) => LvalueTy::Ty { ty: self.mir.local_decls[index].ty },
128 Lvalue::Static(box Static { def_id, ty: sty }) => {
129 let sty = self.sanitize_type(lvalue, sty);
130 let ty = self.tcx().item_type(def_id);
131 let ty = self.cx.normalize(&ty);
132 if let Err(terr) = self.cx.eq_types(self.last_span, ty, sty) {
134 self, lvalue, "bad static type ({:?}: {:?}): {:?}",
137 LvalueTy::Ty { ty: sty }
140 Lvalue::Projection(ref proj) => {
141 let base_ty = self.sanitize_lvalue(&proj.base, location);
142 if let LvalueTy::Ty { ty } = base_ty {
143 if ty.references_error() {
144 assert!(self.errors_reported);
145 return LvalueTy::Ty { ty: self.tcx().types.err };
148 self.sanitize_projection(base_ty, &proj.elem, lvalue, location)
153 fn sanitize_projection(&mut self,
154 base: LvalueTy<'tcx>,
155 pi: &LvalueElem<'tcx>,
156 lvalue: &Lvalue<'tcx>,
159 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, lvalue);
160 let tcx = self.tcx();
161 let base_ty = base.to_ty(tcx);
162 let span = self.last_span;
164 ProjectionElem::Deref => {
165 let deref_ty = base_ty.builtin_deref(true, ty::LvaluePreference::NoPreference);
167 ty: deref_ty.map(|t| t.ty).unwrap_or_else(|| {
168 span_mirbug_and_err!(
169 self, lvalue, "deref of non-pointer {:?}", base_ty)
173 ProjectionElem::Index(ref i) => {
174 self.visit_operand(i, location);
175 let index_ty = i.ty(self.mir, tcx);
176 if index_ty != tcx.types.usize {
178 ty: span_mirbug_and_err!(self, i, "index by non-usize {:?}", i)
182 ty: base_ty.builtin_index().unwrap_or_else(|| {
183 span_mirbug_and_err!(
184 self, lvalue, "index of non-array {:?}", base_ty)
189 ProjectionElem::ConstantIndex { .. } => {
190 // consider verifying in-bounds
192 ty: base_ty.builtin_index().unwrap_or_else(|| {
193 span_mirbug_and_err!(
194 self, lvalue, "index of non-array {:?}", base_ty)
198 ProjectionElem::Subslice { from, to } => {
200 ty: match base_ty.sty {
201 ty::TyArray(inner, size) => {
202 let min_size = (from as usize) + (to as usize);
203 if let Some(rest_size) = size.checked_sub(min_size) {
204 tcx.mk_array(inner, rest_size)
206 span_mirbug_and_err!(
207 self, lvalue, "taking too-small slice of {:?}", base_ty)
210 ty::TySlice(..) => base_ty,
212 span_mirbug_and_err!(
213 self, lvalue, "slice of non-array {:?}", base_ty)
218 ProjectionElem::Downcast(adt_def1, index) =>
220 ty::TyAdt(adt_def, substs) if adt_def.is_enum() && adt_def == adt_def1 => {
221 if index >= adt_def.variants.len() {
223 ty: span_mirbug_and_err!(
226 "cast to variant #{:?} but enum only has {:?}",
228 adt_def.variants.len())
239 ty: span_mirbug_and_err!(
240 self, lvalue, "can't downcast {:?} as {:?}",
244 ProjectionElem::Field(field, fty) => {
245 let fty = self.sanitize_type(lvalue, fty);
246 match self.field_ty(lvalue, base, field) {
248 if let Err(terr) = self.cx.eq_types(span, ty, fty) {
250 self, lvalue, "bad field access ({:?}: {:?}): {:?}",
254 Err(FieldAccessError::OutOfRange { field_count }) => {
256 self, lvalue, "accessed field #{} but variant only has {}",
257 field.index(), field_count)
260 LvalueTy::Ty { ty: fty }
265 fn error(&mut self) -> Ty<'tcx> {
266 self.errors_reported = true;
270 fn field_ty(&mut self,
272 base_ty: LvalueTy<'tcx>,
274 -> Result<Ty<'tcx>, FieldAccessError>
276 let tcx = self.tcx();
278 let (variant, substs) = match base_ty {
279 LvalueTy::Downcast { adt_def, substs, variant_index } => {
280 (&adt_def.variants[variant_index], substs)
282 LvalueTy::Ty { ty } => match ty.sty {
283 ty::TyAdt(adt_def, substs) if adt_def.is_univariant() => {
284 (&adt_def.variants[0], substs)
286 ty::TyClosure(def_id, substs) => {
287 return match substs.upvar_tys(def_id, tcx).nth(field.index()) {
289 None => Err(FieldAccessError::OutOfRange {
290 field_count: substs.upvar_tys(def_id, tcx).count()
294 ty::TyTuple(tys, _) => {
295 return match tys.get(field.index()) {
297 None => Err(FieldAccessError::OutOfRange {
298 field_count: tys.len()
302 _ => return Ok(span_mirbug_and_err!(
303 self, parent, "can't project out of {:?}", base_ty))
307 if let Some(field) = variant.fields.get(field.index()) {
308 Ok(self.cx.normalize(&field.ty(tcx, substs)))
310 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
315 pub struct TypeChecker<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
316 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
317 fulfillment_cx: traits::FulfillmentContext<'tcx>,
319 body_id: ast::NodeId,
322 impl<'a, 'gcx, 'tcx> TypeChecker<'a, 'gcx, 'tcx> {
323 fn new(infcx: &'a InferCtxt<'a, 'gcx, 'tcx>, body_id: ast::NodeId) -> Self {
326 fulfillment_cx: traits::FulfillmentContext::new(),
332 fn misc(&self, span: Span) -> traits::ObligationCause<'tcx> {
333 traits::ObligationCause::misc(span, self.body_id)
336 pub fn register_infer_ok_obligations<T>(&mut self, infer_ok: InferOk<'tcx, T>) -> T {
337 for obligation in infer_ok.obligations {
338 self.fulfillment_cx.register_predicate_obligation(self.infcx, obligation);
343 fn sub_types(&mut self, sup: Ty<'tcx>, sub: Ty<'tcx>)
344 -> infer::UnitResult<'tcx>
346 self.infcx.sub_types(false, &self.misc(self.last_span), sup, sub)
347 .map(|ok| self.register_infer_ok_obligations(ok))
350 fn eq_types(&mut self, span: Span, a: Ty<'tcx>, b: Ty<'tcx>)
351 -> infer::UnitResult<'tcx>
353 self.infcx.eq_types(false, &self.misc(span), a, b)
354 .map(|ok| self.register_infer_ok_obligations(ok))
357 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
361 fn check_stmt(&mut self, mir: &Mir<'tcx>, stmt: &Statement<'tcx>) {
362 debug!("check_stmt: {:?}", stmt);
363 let tcx = self.tcx();
365 StatementKind::Assign(ref lv, ref rv) => {
366 let lv_ty = lv.ty(mir, tcx).to_ty(tcx);
367 let rv_ty = rv.ty(mir, tcx);
368 if let Err(terr) = self.sub_types(rv_ty, lv_ty) {
369 span_mirbug!(self, stmt, "bad assignment ({:?} = {:?}): {:?}",
373 StatementKind::SetDiscriminant{ ref lvalue, variant_index } => {
374 let lvalue_type = lvalue.ty(mir, tcx).to_ty(tcx);
375 let adt = match lvalue_type.sty {
376 TypeVariants::TyAdt(adt, _) if adt.is_enum() => adt,
378 span_bug!(stmt.source_info.span,
379 "bad set discriminant ({:?} = {:?}): lhs is not an enum",
384 if variant_index >= adt.variants.len() {
385 span_bug!(stmt.source_info.span,
386 "bad set discriminant ({:?} = {:?}): value of of range",
391 StatementKind::StorageLive(ref lv) |
392 StatementKind::StorageDead(ref lv) => {
394 Lvalue::Local(_) => {}
396 span_mirbug!(self, stmt, "bad lvalue: expected local");
400 StatementKind::InlineAsm { .. } |
401 StatementKind::Nop => {}
405 fn check_terminator(&mut self,
407 term: &Terminator<'tcx>) {
408 debug!("check_terminator: {:?}", term);
409 let tcx = self.tcx();
411 TerminatorKind::Goto { .. } |
412 TerminatorKind::Resume |
413 TerminatorKind::Return |
414 TerminatorKind::Unreachable |
415 TerminatorKind::Drop { .. } => {
416 // no checks needed for these
420 TerminatorKind::DropAndReplace {
425 let lv_ty = location.ty(mir, tcx).to_ty(tcx);
426 let rv_ty = value.ty(mir, tcx);
427 if let Err(terr) = self.sub_types(rv_ty, lv_ty) {
428 span_mirbug!(self, term, "bad DropAndReplace ({:?} = {:?}): {:?}",
432 TerminatorKind::SwitchInt { ref discr, switch_ty, .. } => {
433 let discr_ty = discr.ty(mir, tcx);
434 if let Err(terr) = self.sub_types(discr_ty, switch_ty) {
435 span_mirbug!(self, term, "bad SwitchInt ({:?} on {:?}): {:?}",
436 switch_ty, discr_ty, terr);
438 if !switch_ty.is_integral() && !switch_ty.is_char() &&
441 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}",switch_ty);
443 // FIXME: check the values
445 TerminatorKind::Call { ref func, ref args, ref destination, .. } => {
446 let func_ty = func.ty(mir, tcx);
447 debug!("check_terminator: call, func_ty={:?}", func_ty);
448 let sig = match func_ty.sty {
449 ty::TyFnDef(.., sig) | ty::TyFnPtr(sig) => sig,
451 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
455 let sig = tcx.erase_late_bound_regions(&sig);
456 let sig = self.normalize(&sig);
457 self.check_call_dest(mir, term, &sig, destination);
459 if self.is_box_free(func) {
460 self.check_box_free_inputs(mir, term, &sig, args);
462 self.check_call_inputs(mir, term, &sig, args);
465 TerminatorKind::Assert { ref cond, ref msg, .. } => {
466 let cond_ty = cond.ty(mir, tcx);
467 if cond_ty != tcx.types.bool {
468 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
471 if let AssertMessage::BoundsCheck { ref len, ref index } = *msg {
472 if len.ty(mir, tcx) != tcx.types.usize {
473 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
475 if index.ty(mir, tcx) != tcx.types.usize {
476 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
483 fn check_call_dest(&mut self,
485 term: &Terminator<'tcx>,
486 sig: &ty::FnSig<'tcx>,
487 destination: &Option<(Lvalue<'tcx>, BasicBlock)>) {
488 let tcx = self.tcx();
490 Some((ref dest, _)) => {
491 let dest_ty = dest.ty(mir, tcx).to_ty(tcx);
492 if let Err(terr) = self.sub_types(sig.output(), dest_ty) {
493 span_mirbug!(self, term,
494 "call dest mismatch ({:?} <- {:?}): {:?}",
495 dest_ty, sig.output(), terr);
499 // FIXME(canndrew): This is_never should probably be an is_uninhabited
500 if !sig.output().is_never() {
501 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
507 fn check_call_inputs(&mut self,
509 term: &Terminator<'tcx>,
510 sig: &ty::FnSig<'tcx>,
511 args: &[Operand<'tcx>])
513 debug!("check_call_inputs({:?}, {:?})", sig, args);
514 if args.len() < sig.inputs().len() ||
515 (args.len() > sig.inputs().len() && !sig.variadic) {
516 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
518 for (n, (fn_arg, op_arg)) in sig.inputs().iter().zip(args).enumerate() {
519 let op_arg_ty = op_arg.ty(mir, self.tcx());
520 if let Err(terr) = self.sub_types(op_arg_ty, fn_arg) {
521 span_mirbug!(self, term, "bad arg #{:?} ({:?} <- {:?}): {:?}",
522 n, fn_arg, op_arg_ty, terr);
527 fn is_box_free(&self, operand: &Operand<'tcx>) -> bool {
529 &Operand::Constant(Constant {
530 literal: Literal::Value {
531 value: ConstVal::Function(def_id, _), ..
534 Some(def_id) == self.tcx().lang_items.box_free_fn()
540 fn check_box_free_inputs(&mut self,
542 term: &Terminator<'tcx>,
543 sig: &ty::FnSig<'tcx>,
544 args: &[Operand<'tcx>])
546 debug!("check_box_free_inputs");
548 // box_free takes a Box as a pointer. Allow for that.
550 if sig.inputs().len() != 1 {
551 span_mirbug!(self, term, "box_free should take 1 argument");
555 let pointee_ty = match sig.inputs()[0].sty {
556 ty::TyRawPtr(mt) => mt.ty,
558 span_mirbug!(self, term, "box_free should take a raw ptr");
564 span_mirbug!(self, term, "box_free called with wrong # of args");
568 let ty = args[0].ty(mir, self.tcx());
569 let arg_ty = match ty.sty {
570 ty::TyRawPtr(mt) => mt.ty,
571 ty::TyAdt(def, _) if def.is_box() => ty.boxed_ty(),
573 span_mirbug!(self, term, "box_free called with bad arg ty");
578 if let Err(terr) = self.sub_types(arg_ty, pointee_ty) {
579 span_mirbug!(self, term, "bad box_free arg ({:?} <- {:?}): {:?}",
580 pointee_ty, arg_ty, terr);
584 fn check_iscleanup(&mut self, mir: &Mir<'tcx>, block: &BasicBlockData<'tcx>)
586 let is_cleanup = block.is_cleanup;
587 self.last_span = block.terminator().source_info.span;
588 match block.terminator().kind {
589 TerminatorKind::Goto { target } =>
590 self.assert_iscleanup(mir, block, target, is_cleanup),
591 TerminatorKind::SwitchInt { ref targets, .. } => {
592 for target in targets {
593 self.assert_iscleanup(mir, block, *target, is_cleanup);
596 TerminatorKind::Resume => {
598 span_mirbug!(self, block, "resume on non-cleanup block!")
601 TerminatorKind::Return => {
603 span_mirbug!(self, block, "return on cleanup block")
606 TerminatorKind::Unreachable => {}
607 TerminatorKind::Drop { target, unwind, .. } |
608 TerminatorKind::DropAndReplace { target, unwind, .. } |
609 TerminatorKind::Assert { target, cleanup: unwind, .. } => {
610 self.assert_iscleanup(mir, block, target, is_cleanup);
611 if let Some(unwind) = unwind {
613 span_mirbug!(self, block, "unwind on cleanup block")
615 self.assert_iscleanup(mir, block, unwind, true);
618 TerminatorKind::Call { ref destination, cleanup, .. } => {
619 if let &Some((_, target)) = destination {
620 self.assert_iscleanup(mir, block, target, is_cleanup);
622 if let Some(cleanup) = cleanup {
624 span_mirbug!(self, block, "cleanup on cleanup block")
626 self.assert_iscleanup(mir, block, cleanup, true);
632 fn assert_iscleanup(&mut self,
638 if mir[bb].is_cleanup != iscleanuppad {
639 span_mirbug!(self, ctxt, "cleanuppad mismatch: {:?} should be {:?}",
644 fn typeck_mir(&mut self, mir: &Mir<'tcx>) {
645 self.last_span = mir.span;
646 debug!("run_on_mir: {:?}", mir.span);
647 for block in mir.basic_blocks() {
648 for stmt in &block.statements {
649 if stmt.source_info.span != DUMMY_SP {
650 self.last_span = stmt.source_info.span;
652 self.check_stmt(mir, stmt);
655 self.check_terminator(mir, block.terminator());
656 self.check_iscleanup(mir, block);
661 fn normalize<T>(&mut self, value: &T) -> T
662 where T: fmt::Debug + TypeFoldable<'tcx>
664 let mut selcx = traits::SelectionContext::new(self.infcx);
665 let cause = traits::ObligationCause::misc(self.last_span, ast::CRATE_NODE_ID);
666 let traits::Normalized { value, obligations } =
667 traits::normalize(&mut selcx, cause, value);
669 debug!("normalize: value={:?} obligations={:?}",
673 let mut fulfill_cx = &mut self.fulfillment_cx;
674 for obligation in obligations {
675 fulfill_cx.register_predicate_obligation(self.infcx, obligation);
681 fn verify_obligations(&mut self, mir: &Mir<'tcx>) {
682 self.last_span = mir.span;
683 if let Err(e) = self.fulfillment_cx.select_all_or_error(self.infcx) {
684 span_mirbug!(self, "", "errors selecting obligation: {:?}",
690 pub struct TypeckMir;
693 pub fn new() -> Self {
698 impl<'tcx> MirPass<'tcx> for TypeckMir {
699 fn run_pass<'a>(&mut self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
700 src: MirSource, mir: &mut Mir<'tcx>) {
701 debug!("run_pass: {}", tcx.node_path_str(src.item_id()));
703 if tcx.sess.err_count() > 0 {
704 // compiling a broken program can obviously result in a
705 // broken MIR, so try not to report duplicate errors.
708 let param_env = ty::ParameterEnvironment::for_item(tcx, src.item_id());
709 tcx.infer_ctxt(param_env, Reveal::UserFacing).enter(|infcx| {
710 let mut checker = TypeChecker::new(&infcx, src.item_id());
712 let mut verifier = TypeVerifier::new(&mut checker, mir);
713 verifier.visit_mir(mir);
714 if verifier.errors_reported {
715 // don't do further checks to avoid ICEs
719 checker.typeck_mir(mir);
720 checker.verify_obligations(mir);
725 impl Pass for TypeckMir {