]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/add_retag.rs
Migrate from Place enum to Place struct
[rust.git] / src / librustc_mir / transform / 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 rustc::ty::{self, Ty, TyCtxt};
8 use rustc::mir::*;
9 use crate::transform::{MirPass, MirSource};
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(
18     place: &Place<'_>,
19 ) -> bool {
20     if let Some(proj) = &place.projection {
21         match proj.elem {
22             // Which place this evaluates to can change with any memory write,
23             // so cannot assume this to be stable.
24             ProjectionElem::Deref =>
25                 false,
26             // Array indices are intersting, but MIR building generates a *fresh*
27             // temporary for every array access, so the index cannot be changed as
28             // a side-effect.
29             ProjectionElem::Index { .. } |
30             // The rest is completely boring, they just offset by a constant.
31             ProjectionElem::Field { .. } |
32             ProjectionElem::ConstantIndex { .. } |
33             ProjectionElem::Subslice { .. } |
34             ProjectionElem::Downcast { .. } =>
35                 is_stable(&Place {
36                     base: place.base.clone(),
37                     projection: proj.base.clone(),
38                 }),
39         }
40     } else {
41         true
42     }
43 }
44
45 /// Determine whether this type may have a reference in it, recursing below compound types but
46 /// not below references.
47 fn may_have_reference<'tcx>(ty: Ty<'tcx>, tcx: TyCtxt<'tcx>) -> bool {
48     match ty.sty {
49         // Primitive types that are not references
50         ty::Bool | ty::Char |
51         ty::Float(_) | ty::Int(_) | ty::Uint(_) |
52         ty::RawPtr(..) | ty::FnPtr(..) |
53         ty::Str | ty::FnDef(..) | ty::Never =>
54             false,
55         // References
56         ty::Ref(..) => true,
57         ty::Adt(..) if ty.is_box() => true,
58         // Compound types
59         ty::Array(ty, ..) | ty::Slice(ty) =>
60             may_have_reference(ty, tcx),
61         ty::Tuple(tys) =>
62             tys.iter().any(|ty| may_have_reference(ty.expect_ty(), tcx)),
63         ty::Adt(adt, substs) =>
64             adt.variants.iter().any(|v| v.fields.iter().any(|f|
65                 may_have_reference(f.ty(tcx, substs), tcx)
66             )),
67         // Conservative fallback
68         _ => true,
69     }
70 }
71
72 impl MirPass for AddRetag {
73     fn run_pass<'tcx>(&self, tcx: TyCtxt<'tcx>, _src: MirSource<'tcx>, body: &mut Body<'tcx>) {
74         if !tcx.sess.opts.debugging_opts.mir_emit_retag {
75             return;
76         }
77         let (span, arg_count) = (body.span, body.arg_count);
78         let (basic_blocks, local_decls) = body.basic_blocks_and_local_decls_mut();
79         let needs_retag = |place: &Place<'tcx>| {
80             // FIXME: Instead of giving up for unstable places, we should introduce
81             // a temporary and retag on that.
82             is_stable(place) && may_have_reference(place.ty(&*local_decls, tcx).ty, tcx)
83         };
84
85         // PART 1
86         // Retag arguments at the beginning of the start block.
87         {
88             let source_info = SourceInfo {
89                 scope: OUTERMOST_SOURCE_SCOPE,
90                 span: span, // FIXME: Consider using just the span covering the function
91                             // argument declaration.
92             };
93             // Gather all arguments, skip return value.
94             let places = local_decls.iter_enumerated().skip(1).take(arg_count)
95                     .map(|(local, _)| Place::from(local))
96                     .filter(needs_retag)
97                     .collect::<Vec<_>>();
98             // Emit their retags.
99             basic_blocks[START_BLOCK].statements.splice(0..0,
100                 places.into_iter().map(|place| Statement {
101                     source_info,
102                     kind: StatementKind::Retag(RetagKind::FnEntry, place),
103                 })
104             );
105         }
106
107         // PART 2
108         // Retag return values of functions.  Also escape-to-raw the argument of `drop`.
109         // We collect the return destinations because we cannot mutate while iterating.
110         let mut returns: Vec<(SourceInfo, Place<'tcx>, BasicBlock)> = Vec::new();
111         for block_data in basic_blocks.iter_mut() {
112             match block_data.terminator().kind {
113                 TerminatorKind::Call { ref destination, .. } => {
114                     // Remember the return destination for later
115                     if let Some(ref destination) = destination {
116                         if needs_retag(&destination.0) {
117                             returns.push((
118                                 block_data.terminator().source_info,
119                                 destination.0.clone(),
120                                 destination.1,
121                             ));
122                         }
123                     }
124                 }
125                 TerminatorKind::Drop { .. } |
126                 TerminatorKind::DropAndReplace { .. } => {
127                     // `Drop` is also a call, but it doesn't return anything so we are good.
128                 }
129                 _ => {
130                     // Not a block ending in a Call -> ignore.
131                 }
132             }
133         }
134         // Now we go over the returns we collected to retag the return values.
135         for (source_info, dest_place, dest_block) in returns {
136             basic_blocks[dest_block].statements.insert(0, Statement {
137                 source_info,
138                 kind: StatementKind::Retag(RetagKind::Default, dest_place),
139             });
140         }
141
142         // PART 3
143         // Add retag after assignment.
144         for block_data in basic_blocks {
145             // We want to insert statements as we iterate.  To this end, we
146             // iterate backwards using indices.
147             for i in (0..block_data.statements.len()).rev() {
148                 let (retag_kind, place) = match block_data.statements[i].kind {
149                     // If we are casting *from* a reference, we may have to retag-as-raw.
150                     StatementKind::Assign(ref place, box Rvalue::Cast(
151                         CastKind::Misc,
152                         ref src,
153                         dest_ty,
154                     )) => {
155                         let src_ty = src.ty(&*local_decls, tcx);
156                         if src_ty.is_region_ptr() {
157                             // The only `Misc` casts on references are those creating raw pointers.
158                             assert!(dest_ty.is_unsafe_ptr());
159                             (RetagKind::Raw, place.clone())
160                         } else {
161                             // Some other cast, no retag
162                             continue
163                         }
164                     }
165                     // Assignments of reference or ptr type are the ones where we may have
166                     // to update tags.  This includes `x = &[mut] ...` and hence
167                     // we also retag after taking a reference!
168                     StatementKind::Assign(ref place, box ref rvalue) if needs_retag(place) => {
169                         let kind = match rvalue {
170                             Rvalue::Ref(_, borrow_kind, _)
171                                 if borrow_kind.allows_two_phase_borrow()
172                             =>
173                                 RetagKind::TwoPhase,
174                             _ =>
175                                 RetagKind::Default,
176                         };
177                         (kind, place.clone())
178                     }
179                     // Do nothing for the rest
180                     _ => continue,
181                 };
182                 // Insert a retag after the statement.
183                 let source_info = block_data.statements[i].source_info;
184                 block_data.statements.insert(i+1, Statement {
185                     source_info,
186                     kind: StatementKind::Retag(retag_kind, place),
187                 });
188             }
189         }
190     }
191 }