]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/add_retag.rs
Rollup merge of #69949 - rust-lang:triagebot-ping-alias, r=Mark-Simulacrum
[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 crate::transform::{MirPass, MirSource};
8 use rustc::mir::*;
9 use rustc::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<'tcx>) -> 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 impl<'tcx> MirPass<'tcx> for AddRetag {
61     fn run_pass(&self, tcx: TyCtxt<'tcx>, _src: MirSource<'tcx>, body: &mut BodyAndCache<'tcx>) {
62         if !tcx.sess.opts.debugging_opts.mir_emit_retag {
63             return;
64         }
65         let (span, arg_count) = (body.span, body.arg_count);
66         let (basic_blocks, local_decls) = body.basic_blocks_and_local_decls_mut();
67         let needs_retag = |place: &Place<'tcx>| {
68             // FIXME: Instead of giving up for unstable places, we should introduce
69             // a temporary and retag on that.
70             is_stable(place.as_ref()) && may_be_reference(place.ty(&*local_decls, tcx).ty)
71         };
72
73         // PART 1
74         // Retag arguments at the beginning of the start block.
75         {
76             let source_info = SourceInfo {
77                 scope: OUTERMOST_SOURCE_SCOPE,
78                 span, // FIXME: Consider using just the span covering the function
79                       // argument declaration.
80             };
81             // Gather all arguments, skip return value.
82             let places = local_decls
83                 .iter_enumerated()
84                 .skip(1)
85                 .take(arg_count)
86                 .map(|(local, _)| Place::from(local))
87                 .filter(needs_retag)
88                 .collect::<Vec<_>>();
89             // Emit their retags.
90             basic_blocks[START_BLOCK].statements.splice(
91                 0..0,
92                 places.into_iter().map(|place| Statement {
93                     source_info,
94                     kind: StatementKind::Retag(RetagKind::FnEntry, box (place)),
95                 }),
96             );
97         }
98
99         // PART 2
100         // Retag return values of functions.  Also escape-to-raw the argument of `drop`.
101         // We collect the return destinations because we cannot mutate while iterating.
102         let mut returns: Vec<(SourceInfo, Place<'tcx>, BasicBlock)> = Vec::new();
103         for block_data in basic_blocks.iter_mut() {
104             match block_data.terminator().kind {
105                 TerminatorKind::Call { ref destination, .. } => {
106                     // Remember the return destination for later
107                     if let Some(ref destination) = destination {
108                         if needs_retag(&destination.0) {
109                             returns.push((
110                                 block_data.terminator().source_info,
111                                 destination.0,
112                                 destination.1,
113                             ));
114                         }
115                     }
116                 }
117                 TerminatorKind::Drop { .. } | TerminatorKind::DropAndReplace { .. } => {
118                     // `Drop` is also a call, but it doesn't return anything so we are good.
119                 }
120                 _ => {
121                     // Not a block ending in a Call -> ignore.
122                 }
123             }
124         }
125         // Now we go over the returns we collected to retag the return values.
126         for (source_info, dest_place, dest_block) in returns {
127             basic_blocks[dest_block].statements.insert(
128                 0,
129                 Statement {
130                     source_info,
131                     kind: StatementKind::Retag(RetagKind::Default, box (dest_place)),
132                 },
133             );
134         }
135
136         // PART 3
137         // Add retag after assignment.
138         for block_data in basic_blocks {
139             // We want to insert statements as we iterate.  To this end, we
140             // iterate backwards using indices.
141             for i in (0..block_data.statements.len()).rev() {
142                 let (retag_kind, place) = match block_data.statements[i].kind {
143                     // Retag-as-raw after escaping to a raw pointer.
144                     StatementKind::Assign(box (place, Rvalue::AddressOf(..))) => {
145                         (RetagKind::Raw, place)
146                     }
147                     // Assignments of reference or ptr type are the ones where we may have
148                     // to update tags.  This includes `x = &[mut] ...` and hence
149                     // we also retag after taking a reference!
150                     StatementKind::Assign(box (ref place, ref rvalue)) if needs_retag(place) => {
151                         let kind = match rvalue {
152                             Rvalue::Ref(_, borrow_kind, _)
153                                 if borrow_kind.allows_two_phase_borrow() =>
154                             {
155                                 RetagKind::TwoPhase
156                             }
157                             _ => RetagKind::Default,
158                         };
159                         (kind, *place)
160                     }
161                     // Do nothing for the rest
162                     _ => continue,
163                 };
164                 // Insert a retag after the statement.
165                 let source_info = block_data.statements[i].source_info;
166                 block_data.statements.insert(
167                     i + 1,
168                     Statement { source_info, kind: StatementKind::Retag(retag_kind, box (place)) },
169                 );
170             }
171         }
172     }
173 }