rustc_mir_transform/impossible_predicates.rs
1//! Check if it's even possible to satisfy the 'where' clauses
2//! for this item.
3//!
4//! It's possible to `#!feature(trivial_bounds)]` to write
5//! a function with impossible to satisfy clauses, e.g.:
6//! `fn foo() where String: Copy {}`.
7//!
8//! We don't usually need to worry about this kind of case,
9//! since we would get a compilation error if the user tried
10//! to call it. However, since we optimize even without any
11//! calls to the function, we need to make sure that it even
12//! makes sense to try to evaluate the body.
13//!
14//! If there are unsatisfiable where clauses, then all bets are
15//! off, and we just give up.
16//!
17//! We manually filter the predicates, skipping anything that's not
18//! "global". We are in a potentially generic context
19//! (e.g. we are evaluating a function without instantiating generic
20//! parameters, so this filtering serves two purposes:
21//!
22//! 1. We skip evaluating any predicates that we would
23//! never be able prove are unsatisfiable (e.g. `<T as Foo>`
24//! 2. We avoid trying to normalize predicates involving generic
25//! parameters (e.g. `<T as Foo>::MyItem`). This can confuse
26//! the normalization code (leading to cycle errors), since
27//! it's usually never invoked in this way.
28
29use rustc_middle::mir::{Body, START_BLOCK, TerminatorKind};
30use rustc_middle::ty::{TyCtxt, TypeVisitableExt};
31use rustc_trait_selection::traits;
32use tracing::trace;
33
34use crate::pass_manager::MirPass;
35
36pub(crate) struct ImpossiblePredicates;
37
38impl<'tcx> MirPass<'tcx> for ImpossiblePredicates {
39 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
40 let predicates = tcx
41 .predicates_of(body.source.def_id())
42 .predicates
43 .iter()
44 .filter_map(|(p, _)| if p.is_global() { Some(*p) } else { None });
45 if traits::impossible_predicates(tcx, traits::elaborate(tcx, predicates).collect()) {
46 trace!("found unsatisfiable predicates for {:?}", body.source);
47 // Clear the body to only contain a single `unreachable` statement.
48 let bbs = body.basic_blocks.as_mut();
49 bbs.raw.truncate(1);
50 bbs[START_BLOCK].statements.clear();
51 bbs[START_BLOCK].terminator_mut().kind = TerminatorKind::Unreachable;
52 body.var_debug_info.clear();
53 body.local_decls.raw.truncate(body.arg_count + 1);
54 }
55 }
56
57 fn is_required(&self) -> bool {
58 true
59 }
60}