]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_transform/src/add_retag.rs
Rollup merge of #98184 - compiler-errors:elided-lifetime-in-impl-nll, r=cjgillot
[rust.git] / compiler / rustc_mir_transform / src / add_retag.rs
1 //! This pass adds validation calls (AcquireValid, ReleaseValid) where appropriate.
2 //! It has to be run really early, before transformations like inlining, because
3 //! introducing these calls *adds* UB -- so, conceptually, this pass is actually part
4 //! of MIR building, and only after this pass we think of the program has having the
5 //! normal MIR semantics.
6
7 use crate::MirPass;
8 use rustc_middle::mir::*;
9 use rustc_middle::ty::{self, Ty, TyCtxt};
10
11 pub struct AddRetag;
12
13 /// Determines whether this place is "stable": Whether, if we evaluate it again
14 /// after the assignment, we can be sure to obtain the same place value.
15 /// (Concurrent accesses by other threads are no problem as these are anyway non-atomic
16 /// copies.  Data races are UB.)
17 fn is_stable(place: PlaceRef<'_>) -> bool {
18     place.projection.iter().all(|elem| {
19         match elem {
20             // Which place this evaluates to can change with any memory write,
21             // so cannot assume this to be stable.
22             ProjectionElem::Deref => false,
23             // Array indices are interesting, but MIR building generates a *fresh*
24             // temporary for every array access, so the index cannot be changed as
25             // a side-effect.
26             ProjectionElem::Index { .. } |
27             // The rest is completely boring, they just offset by a constant.
28             ProjectionElem::Field { .. } |
29             ProjectionElem::ConstantIndex { .. } |
30             ProjectionElem::Subslice { .. } |
31             ProjectionElem::Downcast { .. } => true,
32         }
33     })
34 }
35
36 /// Determine whether this type may be a reference (or box), and thus needs retagging.
37 fn may_be_reference(ty: Ty<'_>) -> bool {
38     match ty.kind() {
39         // Primitive types that are not references
40         ty::Bool
41         | ty::Char
42         | ty::Float(_)
43         | ty::Int(_)
44         | ty::Uint(_)
45         | ty::RawPtr(..)
46         | ty::FnPtr(..)
47         | ty::Str
48         | ty::FnDef(..)
49         | ty::Never => false,
50         // References
51         ty::Ref(..) => true,
52         ty::Adt(..) if ty.is_box() => true,
53         // Compound types are not references
54         ty::Array(..) | ty::Slice(..) | ty::Tuple(..) | ty::Adt(..) => false,
55         // Conservative fallback
56         _ => true,
57     }
58 }
59
60 /// Determines whether or not this LocalDecl is temp, if not it needs retagging.
61 fn is_not_temp<'tcx>(local_decl: &LocalDecl<'tcx>) -> bool {
62     if let Some(local_info) = &local_decl.local_info {
63         match local_info.as_ref() {
64             LocalInfo::DerefTemp => return false,
65             _ => (),
66         };
67     }
68     return true;
69 }
70
71 impl<'tcx> MirPass<'tcx> for AddRetag {
72     fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
73         sess.opts.debugging_opts.mir_emit_retag
74     }
75
76     fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
77         // We need an `AllCallEdges` pass before we can do any work.
78         super::add_call_guards::AllCallEdges.run_pass(tcx, body);
79
80         let (span, arg_count) = (body.span, body.arg_count);
81         let (basic_blocks, local_decls) = body.basic_blocks_and_local_decls_mut();
82         let needs_retag = |place: &Place<'tcx>| {
83             // FIXME: Instead of giving up for unstable places, we should introduce
84             // a temporary and retag on that.
85             is_stable(place.as_ref())
86                 && may_be_reference(place.ty(&*local_decls, tcx).ty)
87                 && is_not_temp(&local_decls[place.local])
88         };
89         let place_base_raw = |place: &Place<'tcx>| {
90             // If this is a `Deref`, get the type of what we are deref'ing.
91             let deref_base =
92                 place.projection.iter().rposition(|p| matches!(p, ProjectionElem::Deref));
93             if let Some(deref_base) = deref_base {
94                 let base_proj = &place.projection[..deref_base];
95                 let ty = Place::ty_from(place.local, base_proj, &*local_decls, tcx).ty;
96                 ty.is_unsafe_ptr()
97             } else {
98                 // Not a deref, and thus not raw.
99                 false
100             }
101         };
102
103         // PART 1
104         // Retag arguments at the beginning of the start block.
105         {
106             // FIXME: Consider using just the span covering the function
107             // argument declaration.
108             let source_info = SourceInfo::outermost(span);
109             // Gather all arguments, skip return value.
110             let places = local_decls
111                 .iter_enumerated()
112                 .skip(1)
113                 .take(arg_count)
114                 .map(|(local, _)| Place::from(local))
115                 .filter(needs_retag);
116             // Emit their retags.
117             basic_blocks[START_BLOCK].statements.splice(
118                 0..0,
119                 places.map(|place| Statement {
120                     source_info,
121                     kind: StatementKind::Retag(RetagKind::FnEntry, Box::new(place)),
122                 }),
123             );
124         }
125
126         // PART 2
127         // Retag return values of functions.  Also escape-to-raw the argument of `drop`.
128         // We collect the return destinations because we cannot mutate while iterating.
129         let returns = basic_blocks
130             .iter_mut()
131             .filter_map(|block_data| {
132                 match block_data.terminator().kind {
133                     TerminatorKind::Call { target: Some(target), destination, .. }
134                         if needs_retag(&destination) =>
135                     {
136                         // Remember the return destination for later
137                         Some((block_data.terminator().source_info, destination, target))
138                     }
139
140                     // `Drop` is also a call, but it doesn't return anything so we are good.
141                     TerminatorKind::Drop { .. } | TerminatorKind::DropAndReplace { .. } => None,
142                     // Not a block ending in a Call -> ignore.
143                     _ => None,
144                 }
145             })
146             .collect::<Vec<_>>();
147         // Now we go over the returns we collected to retag the return values.
148         for (source_info, dest_place, dest_block) in returns {
149             basic_blocks[dest_block].statements.insert(
150                 0,
151                 Statement {
152                     source_info,
153                     kind: StatementKind::Retag(RetagKind::Default, Box::new(dest_place)),
154                 },
155             );
156         }
157
158         // PART 3
159         // Add retag after assignment.
160         for block_data in basic_blocks {
161             // We want to insert statements as we iterate.  To this end, we
162             // iterate backwards using indices.
163             for i in (0..block_data.statements.len()).rev() {
164                 let (retag_kind, place) = match block_data.statements[i].kind {
165                     // Retag-as-raw after escaping to a raw pointer, if the referent
166                     // is not already a raw pointer.
167                     StatementKind::Assign(box (lplace, Rvalue::AddressOf(_, ref rplace)))
168                         if !place_base_raw(rplace) =>
169                     {
170                         (RetagKind::Raw, lplace)
171                     }
172                     // Retag after assignments of reference type.
173                     StatementKind::Assign(box (ref place, ref rvalue)) if needs_retag(place) => {
174                         let kind = match rvalue {
175                             Rvalue::Ref(_, borrow_kind, _)
176                                 if borrow_kind.allows_two_phase_borrow() =>
177                             {
178                                 RetagKind::TwoPhase
179                             }
180                             _ => RetagKind::Default,
181                         };
182                         (kind, *place)
183                     }
184                     // Do nothing for the rest
185                     _ => continue,
186                 };
187                 // Insert a retag after the statement.
188                 let source_info = block_data.statements[i].source_info;
189                 block_data.statements.insert(
190                     i + 1,
191                     Statement {
192                         source_info,
193                         kind: StatementKind::Retag(retag_kind, Box::new(place)),
194                     },
195                 );
196             }
197         }
198     }
199 }