]> git.lizzy.rs Git - rust.git/blob - src/librustc/cfg/construct.rs
f7ffbe8c65833af10c0a040c39df216296a7cd42
[rust.git] / src / librustc / cfg / construct.rs
1 use crate::cfg::*;
2 use crate::middle::region;
3 use rustc_data_structures::graph::implementation as graph;
4 use syntax::ptr::P;
5 use crate::ty::{self, TyCtxt};
6
7 use crate::hir::{self, PatKind};
8 use crate::hir::def_id::DefId;
9
10 struct CFGBuilder<'a, 'tcx: 'a> {
11     tcx: TyCtxt<'a, 'tcx, 'tcx>,
12     owner_def_id: DefId,
13     tables: &'a ty::TypeckTables<'tcx>,
14     graph: CFGGraph,
15     fn_exit: CFGIndex,
16     loop_scopes: Vec<LoopScope>,
17     breakable_block_scopes: Vec<BlockScope>,
18 }
19
20 #[derive(Copy, Clone)]
21 struct BlockScope {
22     block_expr_id: hir::ItemLocalId, // id of breakable block expr node
23     break_index: CFGIndex, // where to go on `break`
24 }
25
26 #[derive(Copy, Clone)]
27 struct LoopScope {
28     loop_id: hir::ItemLocalId,     // id of loop/while node
29     continue_index: CFGIndex, // where to go on a `loop`
30     break_index: CFGIndex,    // where to go on a `break`
31 }
32
33 pub fn construct<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
34                            body: &hir::Body) -> CFG {
35     let mut graph = graph::Graph::new();
36     let entry = graph.add_node(CFGNodeData::Entry);
37
38     // `fn_exit` is target of return exprs, which lies somewhere
39     // outside input `body`. (Distinguishing `fn_exit` and `body_exit`
40     // also resolves chicken-and-egg problem that arises if you try to
41     // have return exprs jump to `body_exit` during construction.)
42     let fn_exit = graph.add_node(CFGNodeData::Exit);
43     let body_exit;
44
45     // Find the tables for this body.
46     let owner_def_id = tcx.hir().local_def_id(tcx.hir().body_owner(body.id()));
47     let tables = tcx.typeck_tables_of(owner_def_id);
48
49     let mut cfg_builder = CFGBuilder {
50         tcx,
51         owner_def_id,
52         tables,
53         graph,
54         fn_exit,
55         loop_scopes: Vec::new(),
56         breakable_block_scopes: Vec::new(),
57     };
58     body_exit = cfg_builder.expr(&body.value, entry);
59     cfg_builder.add_contained_edge(body_exit, fn_exit);
60     let CFGBuilder { graph, .. } = cfg_builder;
61     CFG {
62         owner_def_id,
63         graph,
64         entry,
65         exit: fn_exit,
66     }
67 }
68
69 impl<'a, 'tcx> CFGBuilder<'a, 'tcx> {
70     fn block(&mut self, blk: &hir::Block, pred: CFGIndex) -> CFGIndex {
71         if blk.targeted_by_break {
72             let expr_exit = self.add_ast_node(blk.hir_id.local_id, &[]);
73
74             self.breakable_block_scopes.push(BlockScope {
75                 block_expr_id: blk.hir_id.local_id,
76                 break_index: expr_exit,
77             });
78
79             let mut stmts_exit = pred;
80             for stmt in &blk.stmts {
81                 stmts_exit = self.stmt(stmt, stmts_exit);
82             }
83             let blk_expr_exit = self.opt_expr(&blk.expr, stmts_exit);
84             self.add_contained_edge(blk_expr_exit, expr_exit);
85
86             self.breakable_block_scopes.pop();
87
88             expr_exit
89         } else {
90             let mut stmts_exit = pred;
91             for stmt in &blk.stmts {
92                 stmts_exit = self.stmt(stmt, stmts_exit);
93             }
94
95             let expr_exit = self.opt_expr(&blk.expr, stmts_exit);
96
97             self.add_ast_node(blk.hir_id.local_id, &[expr_exit])
98         }
99     }
100
101     fn stmt(&mut self, stmt: &hir::Stmt, pred: CFGIndex) -> CFGIndex {
102         let exit = match stmt.node {
103             hir::StmtKind::Local(ref local) => {
104                 let init_exit = self.opt_expr(&local.init, pred);
105                 self.pat(&local.pat, init_exit)
106             }
107             hir::StmtKind::Item(_) => {
108                 pred
109             }
110             hir::StmtKind::Expr(ref expr) |
111             hir::StmtKind::Semi(ref expr) => {
112                 self.expr(&expr, pred)
113             }
114         };
115         self.add_ast_node(stmt.hir_id.local_id, &[exit])
116     }
117
118     fn pat(&mut self, pat: &hir::Pat, pred: CFGIndex) -> CFGIndex {
119         match pat.node {
120             PatKind::Binding(.., None) |
121             PatKind::Path(_) |
122             PatKind::Lit(..) |
123             PatKind::Range(..) |
124             PatKind::Wild => self.add_ast_node(pat.hir_id.local_id, &[pred]),
125
126             PatKind::Box(ref subpat) |
127             PatKind::Ref(ref subpat, _) |
128             PatKind::Binding(.., Some(ref subpat)) => {
129                 let subpat_exit = self.pat(&subpat, pred);
130                 self.add_ast_node(pat.hir_id.local_id, &[subpat_exit])
131             }
132
133             PatKind::TupleStruct(_, ref subpats, _) |
134             PatKind::Tuple(ref subpats, _) => {
135                 let pats_exit = self.pats_all(subpats.iter(), pred);
136                 self.add_ast_node(pat.hir_id.local_id, &[pats_exit])
137             }
138
139             PatKind::Struct(_, ref subpats, _) => {
140                 let pats_exit = self.pats_all(subpats.iter().map(|f| &f.node.pat), pred);
141                 self.add_ast_node(pat.hir_id.local_id, &[pats_exit])
142             }
143
144             PatKind::Slice(ref pre, ref vec, ref post) => {
145                 let pre_exit = self.pats_all(pre.iter(), pred);
146                 let vec_exit = self.pats_all(vec.iter(), pre_exit);
147                 let post_exit = self.pats_all(post.iter(), vec_exit);
148                 self.add_ast_node(pat.hir_id.local_id, &[post_exit])
149             }
150         }
151     }
152
153     fn pats_all<'b, I: Iterator<Item=&'b P<hir::Pat>>>(&mut self,
154                                           pats: I,
155                                           pred: CFGIndex) -> CFGIndex {
156         //! Handles case where all of the patterns must match.
157         pats.fold(pred, |pred, pat| self.pat(&pat, pred))
158     }
159
160     fn expr(&mut self, expr: &hir::Expr, pred: CFGIndex) -> CFGIndex {
161         match expr.node {
162             hir::ExprKind::Block(ref blk, _) => {
163                 let blk_exit = self.block(&blk, pred);
164                 self.add_ast_node(expr.hir_id.local_id, &[blk_exit])
165             }
166
167             hir::ExprKind::If(ref cond, ref then, None) => {
168                 //
169                 //     [pred]
170                 //       |
171                 //       v 1
172                 //     [cond]
173                 //       |
174                 //      / \
175                 //     /   \
176                 //    v 2   *
177                 //  [then]  |
178                 //    |     |
179                 //    v 3   v 4
180                 //   [..expr..]
181                 //
182                 let cond_exit = self.expr(&cond, pred);                // 1
183                 let then_exit = self.expr(&then, cond_exit);          // 2
184                 self.add_ast_node(expr.hir_id.local_id, &[cond_exit, then_exit])      // 3,4
185             }
186
187             hir::ExprKind::If(ref cond, ref then, Some(ref otherwise)) => {
188                 //
189                 //     [pred]
190                 //       |
191                 //       v 1
192                 //     [cond]
193                 //       |
194                 //      / \
195                 //     /   \
196                 //    v 2   v 3
197                 //  [then][otherwise]
198                 //    |     |
199                 //    v 4   v 5
200                 //   [..expr..]
201                 //
202                 let cond_exit = self.expr(&cond, pred);                // 1
203                 let then_exit = self.expr(&then, cond_exit);          // 2
204                 let else_exit = self.expr(&otherwise, cond_exit);      // 3
205                 self.add_ast_node(expr.hir_id.local_id, &[then_exit, else_exit])      // 4, 5
206             }
207
208             hir::ExprKind::While(ref cond, ref body, _) => {
209                 //
210                 //         [pred]
211                 //           |
212                 //           v 1
213                 //       [loopback] <--+ 5
214                 //           |         |
215                 //           v 2       |
216                 //   +-----[cond]      |
217                 //   |       |         |
218                 //   |       v 4       |
219                 //   |     [body] -----+
220                 //   v 3
221                 // [expr]
222                 //
223                 // Note that `break` and `continue` statements
224                 // may cause additional edges.
225
226                 let loopback = self.add_dummy_node(&[pred]);              // 1
227
228                 // Create expr_exit without pred (cond_exit)
229                 let expr_exit = self.add_ast_node(expr.hir_id.local_id, &[]);         // 3
230
231                 // The LoopScope needs to be on the loop_scopes stack while evaluating the
232                 // condition and the body of the loop (both can break out of the loop)
233                 self.loop_scopes.push(LoopScope {
234                     loop_id: expr.hir_id.local_id,
235                     continue_index: loopback,
236                     break_index: expr_exit
237                 });
238
239                 let cond_exit = self.expr(&cond, loopback);             // 2
240
241                 // Add pred (cond_exit) to expr_exit
242                 self.add_contained_edge(cond_exit, expr_exit);
243
244                 let body_exit = self.block(&body, cond_exit);          // 4
245                 self.add_contained_edge(body_exit, loopback);            // 5
246                 self.loop_scopes.pop();
247                 expr_exit
248             }
249
250             hir::ExprKind::Loop(ref body, _, _) => {
251                 //
252                 //     [pred]
253                 //       |
254                 //       v 1
255                 //   [loopback] <---+
256                 //       |      4   |
257                 //       v 3        |
258                 //     [body] ------+
259                 //
260                 //     [expr] 2
261                 //
262                 // Note that `break` and `loop` statements
263                 // may cause additional edges.
264
265                 let loopback = self.add_dummy_node(&[pred]);              // 1
266                 let expr_exit = self.add_ast_node(expr.hir_id.local_id, &[]);          // 2
267                 self.loop_scopes.push(LoopScope {
268                     loop_id: expr.hir_id.local_id,
269                     continue_index: loopback,
270                     break_index: expr_exit,
271                 });
272                 let body_exit = self.block(&body, loopback);           // 3
273                 self.add_contained_edge(body_exit, loopback);            // 4
274                 self.loop_scopes.pop();
275                 expr_exit
276             }
277
278             hir::ExprKind::Match(ref discr, ref arms, _) => {
279                 self.match_(expr.hir_id.local_id, &discr, &arms, pred)
280             }
281
282             hir::ExprKind::Binary(op, ref l, ref r) if op.node.is_lazy() => {
283                 //
284                 //     [pred]
285                 //       |
286                 //       v 1
287                 //      [l]
288                 //       |
289                 //      / \
290                 //     /   \
291                 //    v 2  *
292                 //   [r]   |
293                 //    |    |
294                 //    v 3  v 4
295                 //   [..exit..]
296                 //
297                 let l_exit = self.expr(&l, pred);                      // 1
298                 let r_exit = self.expr(&r, l_exit);                    // 2
299                 self.add_ast_node(expr.hir_id.local_id, &[l_exit, r_exit])            // 3,4
300             }
301
302             hir::ExprKind::Ret(ref v) => {
303                 let v_exit = self.opt_expr(v, pred);
304                 let b = self.add_ast_node(expr.hir_id.local_id, &[v_exit]);
305                 self.add_returning_edge(expr, b);
306                 self.add_unreachable_node()
307             }
308
309             hir::ExprKind::Break(destination, ref opt_expr) => {
310                 let v = self.opt_expr(opt_expr, pred);
311                 let (target_scope, break_dest) =
312                     self.find_scope_edge(expr, destination, ScopeCfKind::Break);
313                 let b = self.add_ast_node(expr.hir_id.local_id, &[v]);
314                 self.add_exiting_edge(expr, b, target_scope, break_dest);
315                 self.add_unreachable_node()
316             }
317
318             hir::ExprKind::Continue(destination) => {
319                 let (target_scope, cont_dest) =
320                     self.find_scope_edge(expr, destination, ScopeCfKind::Continue);
321                 let a = self.add_ast_node(expr.hir_id.local_id, &[pred]);
322                 self.add_exiting_edge(expr, a, target_scope, cont_dest);
323                 self.add_unreachable_node()
324             }
325
326             hir::ExprKind::Array(ref elems) => {
327                 self.straightline(expr, pred, elems.iter().map(|e| &*e))
328             }
329
330             hir::ExprKind::Call(ref func, ref args) => {
331                 self.call(expr, pred, &func, args.iter().map(|e| &*e))
332             }
333
334             hir::ExprKind::MethodCall(.., ref args) => {
335                 self.call(expr, pred, &args[0], args[1..].iter().map(|e| &*e))
336             }
337
338             hir::ExprKind::Index(ref l, ref r) |
339             hir::ExprKind::Binary(_, ref l, ref r) if self.tables.is_method_call(expr) => {
340                 self.call(expr, pred, &l, Some(&**r).into_iter())
341             }
342
343             hir::ExprKind::Unary(_, ref e) if self.tables.is_method_call(expr) => {
344                 self.call(expr, pred, &e, None::<hir::Expr>.iter())
345             }
346
347             hir::ExprKind::Tup(ref exprs) => {
348                 self.straightline(expr, pred, exprs.iter().map(|e| &*e))
349             }
350
351             hir::ExprKind::Struct(_, ref fields, ref base) => {
352                 let field_cfg = self.straightline(expr, pred, fields.iter().map(|f| &*f.expr));
353                 self.opt_expr(base, field_cfg)
354             }
355
356             hir::ExprKind::Assign(ref l, ref r) |
357             hir::ExprKind::AssignOp(_, ref l, ref r) => {
358                 self.straightline(expr, pred, [r, l].iter().map(|&e| &**e))
359             }
360
361             hir::ExprKind::Index(ref l, ref r) |
362             hir::ExprKind::Binary(_, ref l, ref r) => { // N.B., && and || handled earlier
363                 self.straightline(expr, pred, [l, r].iter().map(|&e| &**e))
364             }
365
366             hir::ExprKind::Box(ref e) |
367             hir::ExprKind::AddrOf(_, ref e) |
368             hir::ExprKind::Cast(ref e, _) |
369             hir::ExprKind::Type(ref e, _) |
370             hir::ExprKind::Unary(_, ref e) |
371             hir::ExprKind::Field(ref e, _) |
372             hir::ExprKind::Yield(ref e) |
373             hir::ExprKind::Repeat(ref e, _) => {
374                 self.straightline(expr, pred, Some(&**e).into_iter())
375             }
376
377             hir::ExprKind::InlineAsm(_, ref outputs, ref inputs) => {
378                 let post_outputs = self.exprs(outputs.iter().map(|e| &*e), pred);
379                 let post_inputs = self.exprs(inputs.iter().map(|e| &*e), post_outputs);
380                 self.add_ast_node(expr.hir_id.local_id, &[post_inputs])
381             }
382
383             hir::ExprKind::Closure(..) |
384             hir::ExprKind::Lit(..) |
385             hir::ExprKind::Path(_) |
386             hir::ExprKind::Err => {
387                 self.straightline(expr, pred, None::<hir::Expr>.iter())
388             }
389         }
390     }
391
392     fn call<'b, I: Iterator<Item=&'b hir::Expr>>(&mut self,
393             call_expr: &hir::Expr,
394             pred: CFGIndex,
395             func_or_rcvr: &hir::Expr,
396             args: I) -> CFGIndex {
397         let func_or_rcvr_exit = self.expr(func_or_rcvr, pred);
398         let ret = self.straightline(call_expr, func_or_rcvr_exit, args);
399         let m = self.tcx.hir().get_module_parent(call_expr.id);
400         if self.tcx.is_ty_uninhabited_from(m, self.tables.expr_ty(call_expr)) {
401             self.add_unreachable_node()
402         } else {
403             ret
404         }
405     }
406
407     fn exprs<'b, I: Iterator<Item=&'b hir::Expr>>(&mut self,
408                                              exprs: I,
409                                              pred: CFGIndex) -> CFGIndex {
410         //! Constructs graph for `exprs` evaluated in order
411         exprs.fold(pred, |p, e| self.expr(e, p))
412     }
413
414     fn opt_expr(&mut self,
415                 opt_expr: &Option<P<hir::Expr>>,
416                 pred: CFGIndex) -> CFGIndex {
417         //! Constructs graph for `opt_expr` evaluated, if Some
418         opt_expr.iter().fold(pred, |p, e| self.expr(&e, p))
419     }
420
421     fn straightline<'b, I: Iterator<Item=&'b hir::Expr>>(&mut self,
422                     expr: &hir::Expr,
423                     pred: CFGIndex,
424                     subexprs: I) -> CFGIndex {
425         //! Handles case of an expression that evaluates `subexprs` in order
426
427         let subexprs_exit = self.exprs(subexprs, pred);
428         self.add_ast_node(expr.hir_id.local_id, &[subexprs_exit])
429     }
430
431     fn match_(&mut self, id: hir::ItemLocalId, discr: &hir::Expr,
432               arms: &[hir::Arm], pred: CFGIndex) -> CFGIndex {
433         // The CFG for match expression is quite complex, so no ASCII
434         // art for it (yet).
435         //
436         // The CFG generated below matches roughly what MIR contains.
437         // Each pattern and guard is visited in parallel, with
438         // arms containing multiple patterns generating multiple nodes
439         // for the same guard expression. The guard expressions chain
440         // into each other from top to bottom, with a specific
441         // exception to allow some additional valid programs
442         // (explained below). MIR differs slightly in that the
443         // pattern matching may continue after a guard but the visible
444         // behaviour should be the same.
445         //
446         // What is going on is explained in further comments.
447
448         // Visit the discriminant expression
449         let discr_exit = self.expr(discr, pred);
450
451         // Add a node for the exit of the match expression as a whole.
452         let expr_exit = self.add_ast_node(id, &[]);
453
454         // Keep track of the previous guard expressions
455         let mut prev_guards = Vec::new();
456
457         for arm in arms {
458             // Add an exit node for when we've visited all the
459             // patterns and the guard (if there is one) in the arm.
460             let arm_exit = self.add_dummy_node(&[]);
461
462             for pat in &arm.pats {
463                 // Visit the pattern, coming from the discriminant exit
464                 let mut pat_exit = self.pat(&pat, discr_exit);
465
466                 // If there is a guard expression, handle it here
467                 if let Some(ref guard) = arm.guard {
468                     // Add a dummy node for the previous guard
469                     // expression to target
470                     let guard_start = self.add_dummy_node(&[pat_exit]);
471                     // Visit the guard expression
472                     let guard_exit = match guard {
473                         hir::Guard::If(ref e) => self.expr(e, guard_start),
474                     };
475                     // #47295: We used to have very special case code
476                     // here for when a pair of arms are both formed
477                     // solely from constants, and if so, not add these
478                     // edges.  But this was not actually sound without
479                     // other constraints that we stopped enforcing at
480                     // some point.
481                     while let Some(prev) = prev_guards.pop() {
482                         self.add_contained_edge(prev, guard_start);
483                     }
484
485                     // Push the guard onto the list of previous guards
486                     prev_guards.push(guard_exit);
487
488                     // Update the exit node for the pattern
489                     pat_exit = guard_exit;
490                 }
491
492                 // Add an edge from the exit of this pattern to the
493                 // exit of the arm
494                 self.add_contained_edge(pat_exit, arm_exit);
495             }
496
497             // Visit the body of this arm
498             let body_exit = self.expr(&arm.body, arm_exit);
499
500             // Link the body to the exit of the expression
501             self.add_contained_edge(body_exit, expr_exit);
502         }
503
504         expr_exit
505     }
506
507     fn add_dummy_node(&mut self, preds: &[CFGIndex]) -> CFGIndex {
508         self.add_node(CFGNodeData::Dummy, preds)
509     }
510
511     fn add_ast_node(&mut self, id: hir::ItemLocalId, preds: &[CFGIndex]) -> CFGIndex {
512         self.add_node(CFGNodeData::AST(id), preds)
513     }
514
515     fn add_unreachable_node(&mut self) -> CFGIndex {
516         self.add_node(CFGNodeData::Unreachable, &[])
517     }
518
519     fn add_node(&mut self, data: CFGNodeData, preds: &[CFGIndex]) -> CFGIndex {
520         let node = self.graph.add_node(data);
521         for &pred in preds {
522             self.add_contained_edge(pred, node);
523         }
524         node
525     }
526
527     fn add_contained_edge(&mut self,
528                           source: CFGIndex,
529                           target: CFGIndex) {
530         let data = CFGEdgeData {exiting_scopes: vec![] };
531         self.graph.add_edge(source, target, data);
532     }
533
534     fn add_exiting_edge(&mut self,
535                         from_expr: &hir::Expr,
536                         from_index: CFGIndex,
537                         target_scope: region::Scope,
538                         to_index: CFGIndex) {
539         let mut data = CFGEdgeData { exiting_scopes: vec![] };
540         let mut scope = region::Scope {
541             id: from_expr.hir_id.local_id,
542             data: region::ScopeData::Node
543         };
544         let region_scope_tree = self.tcx.region_scope_tree(self.owner_def_id);
545         while scope != target_scope {
546             data.exiting_scopes.push(scope.item_local_id());
547             scope = region_scope_tree.encl_scope(scope);
548         }
549         self.graph.add_edge(from_index, to_index, data);
550     }
551
552     fn add_returning_edge(&mut self,
553                           _from_expr: &hir::Expr,
554                           from_index: CFGIndex) {
555         let data = CFGEdgeData {
556             exiting_scopes: self.loop_scopes.iter()
557                                             .rev()
558                                             .map(|&LoopScope { loop_id: id, .. }| id)
559                                             .collect()
560         };
561         self.graph.add_edge(from_index, self.fn_exit, data);
562     }
563
564     fn find_scope_edge(&self,
565                   expr: &hir::Expr,
566                   destination: hir::Destination,
567                   scope_cf_kind: ScopeCfKind) -> (region::Scope, CFGIndex) {
568
569         match destination.target_id {
570             Ok(loop_id) => {
571                 for b in &self.breakable_block_scopes {
572                     if b.block_expr_id == self.tcx.hir().node_to_hir_id(loop_id).local_id {
573                         let scope = region::Scope {
574                             id: self.tcx.hir().node_to_hir_id(loop_id).local_id,
575                             data: region::ScopeData::Node
576                         };
577                         return (scope, match scope_cf_kind {
578                             ScopeCfKind::Break => b.break_index,
579                             ScopeCfKind::Continue => bug!("can't continue to block"),
580                         });
581                     }
582                 }
583                 for l in &self.loop_scopes {
584                     if l.loop_id == self.tcx.hir().node_to_hir_id(loop_id).local_id {
585                         let scope = region::Scope {
586                             id: self.tcx.hir().node_to_hir_id(loop_id).local_id,
587                             data: region::ScopeData::Node
588                         };
589                         return (scope, match scope_cf_kind {
590                             ScopeCfKind::Break => l.break_index,
591                             ScopeCfKind::Continue => l.continue_index,
592                         });
593                     }
594                 }
595                 span_bug!(expr.span, "no scope for id {}", loop_id);
596             }
597             Err(err) => span_bug!(expr.span, "scope error: {}",  err),
598         }
599     }
600 }
601
602 #[derive(Copy, Clone, Eq, PartialEq)]
603 enum ScopeCfKind {
604     Break,
605     Continue,
606 }