]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/rustc_peek.rs
Rollup merge of #47846 - roblabla:bugfix-ocaml, r=kennytm
[rust.git] / src / librustc_mir / transform / rustc_peek.rs
1 // Copyright 2012-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.
4 //
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.
10
11 use syntax::abi::{Abi};
12 use syntax::ast;
13 use syntax_pos::Span;
14
15 use rustc::ty::{self, TyCtxt};
16 use rustc::mir::{self, Mir, Location};
17 use rustc_data_structures::indexed_set::IdxSetBuf;
18 use rustc_data_structures::indexed_vec::Idx;
19 use transform::{MirPass, MirSource};
20
21 use dataflow::{do_dataflow, DebugFormatted};
22 use dataflow::MoveDataParamEnv;
23 use dataflow::BitDenotation;
24 use dataflow::DataflowResults;
25 use dataflow::{DefinitelyInitializedPlaces, MaybeInitializedPlaces, MaybeUninitializedPlaces};
26 use dataflow::move_paths::{MovePathIndex, LookupResult};
27 use dataflow::move_paths::{HasMoveData, MoveData};
28 use dataflow;
29
30 use dataflow::has_rustc_mir_with;
31
32 pub struct SanityCheck;
33
34 impl MirPass for SanityCheck {
35     fn run_pass<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
36                           src: MirSource, mir: &mut Mir<'tcx>) {
37         let def_id = src.def_id;
38         let id = tcx.hir.as_local_node_id(def_id).unwrap();
39         if !tcx.has_attr(def_id, "rustc_mir_borrowck") {
40             debug!("skipping rustc_peek::SanityCheck on {}", tcx.item_path_str(def_id));
41             return;
42         } else {
43             debug!("running rustc_peek::SanityCheck on {}", tcx.item_path_str(def_id));
44         }
45
46         let attributes = tcx.get_attrs(def_id);
47         let param_env = tcx.param_env(def_id);
48         let move_data = MoveData::gather_moves(mir, tcx).unwrap();
49         let mdpe = MoveDataParamEnv { move_data: move_data, param_env: param_env };
50         let dead_unwinds = IdxSetBuf::new_empty(mir.basic_blocks().len());
51         let flow_inits =
52             do_dataflow(tcx, mir, id, &attributes, &dead_unwinds,
53                         MaybeInitializedPlaces::new(tcx, mir, &mdpe),
54                         |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]));
55         let flow_uninits =
56             do_dataflow(tcx, mir, id, &attributes, &dead_unwinds,
57                         MaybeUninitializedPlaces::new(tcx, mir, &mdpe),
58                         |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]));
59         let flow_def_inits =
60             do_dataflow(tcx, mir, id, &attributes, &dead_unwinds,
61                         DefinitelyInitializedPlaces::new(tcx, mir, &mdpe),
62                         |bd, i| DebugFormatted::new(&bd.move_data().move_paths[i]));
63
64         if has_rustc_mir_with(&attributes, "rustc_peek_maybe_init").is_some() {
65             sanity_check_via_rustc_peek(tcx, mir, id, &attributes, &flow_inits);
66         }
67         if has_rustc_mir_with(&attributes, "rustc_peek_maybe_uninit").is_some() {
68             sanity_check_via_rustc_peek(tcx, mir, id, &attributes, &flow_uninits);
69         }
70         if has_rustc_mir_with(&attributes, "rustc_peek_definite_init").is_some() {
71             sanity_check_via_rustc_peek(tcx, mir, id, &attributes, &flow_def_inits);
72         }
73         if has_rustc_mir_with(&attributes, "stop_after_dataflow").is_some() {
74             tcx.sess.fatal("stop_after_dataflow ended compilation");
75         }
76     }
77 }
78
79 /// This function scans `mir` for all calls to the intrinsic
80 /// `rustc_peek` that have the expression form `rustc_peek(&expr)`.
81 ///
82 /// For each such call, determines what the dataflow bit-state is for
83 /// the L-value corresponding to `expr`; if the bit-state is a 1, then
84 /// that call to `rustc_peek` is ignored by the sanity check. If the
85 /// bit-state is a 0, then this pass emits a error message saying
86 /// "rustc_peek: bit not set".
87 ///
88 /// The intention is that one can write unit tests for dataflow by
89 /// putting code into a compile-fail test and using `rustc_peek` to
90 /// make observations about the results of dataflow static analyses.
91 ///
92 /// (If there are any calls to `rustc_peek` that do not match the
93 /// expression form above, then that emits an error as well, but those
94 /// errors are not intended to be used for unit tests.)
95 pub fn sanity_check_via_rustc_peek<'a, 'tcx, O>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
96                                                 mir: &Mir<'tcx>,
97                                                 id: ast::NodeId,
98                                                 _attributes: &[ast::Attribute],
99                                                 results: &DataflowResults<O>)
100     where O: BitDenotation<Idx=MovePathIndex> + HasMoveData<'tcx>
101 {
102     debug!("sanity_check_via_rustc_peek id: {:?}", id);
103     // FIXME: this is not DRY. Figure out way to abstract this and
104     // `dataflow::build_sets`. (But note it is doing non-standard
105     // stuff, so such generalization may not be realistic.)
106
107     for bb in mir.basic_blocks().indices() {
108         each_block(tcx, mir, results, bb);
109     }
110 }
111
112 fn each_block<'a, 'tcx, O>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
113                            mir: &Mir<'tcx>,
114                            results: &DataflowResults<O>,
115                            bb: mir::BasicBlock) where
116     O: BitDenotation<Idx=MovePathIndex> + HasMoveData<'tcx>
117 {
118     let move_data = results.0.operator.move_data();
119     let mir::BasicBlockData { ref statements, ref terminator, is_cleanup: _ } = mir[bb];
120
121     let (args, span) = match is_rustc_peek(tcx, terminator) {
122         Some(args_and_span) => args_and_span,
123         None => return,
124     };
125     assert!(args.len() == 1);
126     let peek_arg_place = match args[0] {
127         mir::Operand::Copy(ref place @ mir::Place::Local(_)) |
128         mir::Operand::Move(ref place @ mir::Place::Local(_)) => Some(place),
129         _ => None,
130     };
131
132     let peek_arg_place = match peek_arg_place {
133         Some(arg) => arg,
134         None => {
135             tcx.sess.diagnostic().span_err(
136                 span, "dataflow::sanity_check cannot feed a non-temp to rustc_peek.");
137             return;
138         }
139     };
140
141     let mut entry = results.0.sets.on_entry_set_for(bb.index()).to_owned();
142     let mut gen = results.0.sets.gen_set_for(bb.index()).to_owned();
143     let mut kill = results.0.sets.kill_set_for(bb.index()).to_owned();
144
145     // Emulate effect of all statements in the block up to (but not
146     // including) the borrow within `peek_arg_place`. Do *not* include
147     // call to `peek_arg_place` itself (since we are peeking the state
148     // of the argument at time immediate preceding Call to
149     // `rustc_peek`).
150
151     let mut sets = dataflow::BlockSets { on_entry: &mut entry,
152                                       gen_set: &mut gen,
153                                       kill_set: &mut kill };
154
155     for (j, stmt) in statements.iter().enumerate() {
156         debug!("rustc_peek: ({:?},{}) {:?}", bb, j, stmt);
157         let (place, rvalue) = match stmt.kind {
158             mir::StatementKind::Assign(ref place, ref rvalue) => {
159                 (place, rvalue)
160             }
161             mir::StatementKind::StorageLive(_) |
162             mir::StatementKind::StorageDead(_) |
163             mir::StatementKind::InlineAsm { .. } |
164             mir::StatementKind::EndRegion(_) |
165             mir::StatementKind::Validate(..) |
166             mir::StatementKind::Nop => continue,
167             mir::StatementKind::SetDiscriminant{ .. } =>
168                 span_bug!(stmt.source_info.span,
169                           "sanity_check should run before Deaggregator inserts SetDiscriminant"),
170         };
171
172         if place == peek_arg_place {
173             if let mir::Rvalue::Ref(_, mir::BorrowKind::Shared, ref peeking_at_place) = *rvalue {
174                 // Okay, our search is over.
175                 match move_data.rev_lookup.find(peeking_at_place) {
176                     LookupResult::Exact(peek_mpi) => {
177                         let bit_state = sets.on_entry.contains(&peek_mpi);
178                         debug!("rustc_peek({:?} = &{:?}) bit_state: {}",
179                                place, peeking_at_place, bit_state);
180                         if !bit_state {
181                             tcx.sess.span_err(span, "rustc_peek: bit not set");
182                         }
183                     }
184                     LookupResult::Parent(..) => {
185                         tcx.sess.span_err(span, "rustc_peek: argument untracked");
186                     }
187                 }
188                 return;
189             } else {
190                 // Our search should have been over, but the input
191                 // does not match expectations of `rustc_peek` for
192                 // this sanity_check.
193                 let msg = "rustc_peek: argument expression \
194                            must be immediate borrow of form `&expr`";
195                 tcx.sess.span_err(span, msg);
196             }
197         }
198
199         let lhs_mpi = move_data.rev_lookup.find(place);
200
201         debug!("rustc_peek: computing effect on place: {:?} ({:?}) in stmt: {:?}",
202                place, lhs_mpi, stmt);
203         // reset GEN and KILL sets before emulating their effect.
204         for e in sets.gen_set.words_mut() { *e = 0; }
205         for e in sets.kill_set.words_mut() { *e = 0; }
206         results.0.operator.before_statement_effect(
207             &mut sets, Location { block: bb, statement_index: j });
208         results.0.operator.statement_effect(
209             &mut sets, Location { block: bb, statement_index: j });
210         sets.on_entry.union(sets.gen_set);
211         sets.on_entry.subtract(sets.kill_set);
212     }
213
214     results.0.operator.before_terminator_effect(
215         &mut sets,
216         Location { block: bb, statement_index: statements.len() });
217
218     tcx.sess.span_err(span, &format!("rustc_peek: MIR did not match \
219                                       anticipated pattern; note that \
220                                       rustc_peek expects input of \
221                                       form `&expr`"));
222 }
223
224 fn is_rustc_peek<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
225                            terminator: &'a Option<mir::Terminator<'tcx>>)
226                            -> Option<(&'a [mir::Operand<'tcx>], Span)> {
227     if let Some(mir::Terminator { ref kind, source_info, .. }) = *terminator {
228         if let mir::TerminatorKind::Call { func: ref oper, ref args, .. } = *kind {
229             if let mir::Operand::Constant(ref func) = *oper {
230                 if let ty::TyFnDef(def_id, _) = func.ty.sty {
231                     let abi = tcx.fn_sig(def_id).abi();
232                     let name = tcx.item_name(def_id);
233                     if abi == Abi::RustIntrinsic &&  name == "rustc_peek" {
234                         return Some((args, source_info.span));
235                     }
236                 }
237             }
238         }
239     }
240     return None;
241 }