]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/rvalue_promotion.rs
Auto merge of #50724 - zackmdavis:applicability_rush, r=Manishearth
[rust.git] / src / librustc_passes / rvalue_promotion.rs
1 // Copyright 2012-2014 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 // Verifies that the types and values of const and static items
12 // are safe. The rules enforced by this module are:
13 //
14 // - For each *mutable* static item, it checks that its **type**:
15 //     - doesn't have a destructor
16 //     - doesn't own a box
17 //
18 // - For each *immutable* static item, it checks that its **value**:
19 //       - doesn't own a box
20 //       - doesn't contain a struct literal or a call to an enum variant / struct constructor where
21 //           - the type of the struct/enum has a dtor
22 //
23 // Rules Enforced Elsewhere:
24 // - It's not possible to take the address of a static item with unsafe interior. This is enforced
25 // by borrowck::gather_loans
26
27 use rustc::ty::cast::CastKind;
28 use rustc::hir::def::{Def, CtorKind};
29 use rustc::hir::def_id::DefId;
30 use rustc::hir::map::blocks::FnLikeNode;
31 use rustc::middle::expr_use_visitor as euv;
32 use rustc::middle::mem_categorization as mc;
33 use rustc::middle::mem_categorization::Categorization;
34 use rustc::ty::{self, Ty, TyCtxt};
35 use rustc::ty::maps::Providers;
36 use rustc::ty::subst::Substs;
37 use rustc::util::nodemap::{ItemLocalSet, NodeSet};
38 use rustc::hir;
39 use rustc_data_structures::sync::Lrc;
40 use syntax::ast;
41 use syntax::attr;
42 use syntax_pos::{Span, DUMMY_SP};
43 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
44
45 pub fn provide(providers: &mut Providers) {
46     *providers = Providers {
47         rvalue_promotable_map,
48         const_is_rvalue_promotable_to_static,
49         ..*providers
50     };
51 }
52
53 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
54     for &body_id in &tcx.hir.krate().body_ids {
55         let def_id = tcx.hir.body_owner_def_id(body_id);
56         tcx.const_is_rvalue_promotable_to_static(def_id);
57     }
58     tcx.sess.abort_if_errors();
59 }
60
61 fn const_is_rvalue_promotable_to_static<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
62                                                   def_id: DefId)
63                                                   -> bool
64 {
65     assert!(def_id.is_local());
66
67     let node_id = tcx.hir.as_local_node_id(def_id)
68                      .expect("rvalue_promotable_map invoked with non-local def-id");
69     let body_id = tcx.hir.body_owned_by(node_id);
70     let body_hir_id = tcx.hir.node_to_hir_id(body_id.node_id);
71     tcx.rvalue_promotable_map(def_id).contains(&body_hir_id.local_id)
72 }
73
74 fn rvalue_promotable_map<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
75                                    def_id: DefId)
76                                    -> Lrc<ItemLocalSet>
77 {
78     let outer_def_id = tcx.closure_base_def_id(def_id);
79     if outer_def_id != def_id {
80         return tcx.rvalue_promotable_map(outer_def_id);
81     }
82
83     let mut visitor = CheckCrateVisitor {
84         tcx,
85         tables: &ty::TypeckTables::empty(None),
86         in_fn: false,
87         in_static: false,
88         promotable: false,
89         mut_rvalue_borrows: NodeSet(),
90         param_env: ty::ParamEnv::empty(),
91         identity_substs: Substs::empty(),
92         result: ItemLocalSet(),
93     };
94
95     // `def_id` should be a `Body` owner
96     let node_id = tcx.hir.as_local_node_id(def_id)
97                      .expect("rvalue_promotable_map invoked with non-local def-id");
98     let body_id = tcx.hir.body_owned_by(node_id);
99     visitor.visit_nested_body(body_id);
100
101     Lrc::new(visitor.result)
102 }
103
104 struct CheckCrateVisitor<'a, 'tcx: 'a> {
105     tcx: TyCtxt<'a, 'tcx, 'tcx>,
106     in_fn: bool,
107     in_static: bool,
108     promotable: bool,
109     mut_rvalue_borrows: NodeSet,
110     param_env: ty::ParamEnv<'tcx>,
111     identity_substs: &'tcx Substs<'tcx>,
112     tables: &'a ty::TypeckTables<'tcx>,
113     result: ItemLocalSet,
114 }
115
116 impl<'a, 'gcx> CheckCrateVisitor<'a, 'gcx> {
117     // Returns true iff all the values of the type are promotable.
118     fn type_has_only_promotable_values(&mut self, ty: Ty<'gcx>) -> bool {
119         ty.is_freeze(self.tcx, self.param_env, DUMMY_SP) &&
120         !ty.needs_drop(self.tcx, self.param_env)
121     }
122
123     fn handle_const_fn_call(&mut self, def_id: DefId, ret_ty: Ty<'gcx>, span: Span) {
124         self.promotable &= self.type_has_only_promotable_values(ret_ty);
125
126         self.promotable &= if let Some(fn_id) = self.tcx.hir.as_local_node_id(def_id) {
127             FnLikeNode::from_node(self.tcx.hir.get(fn_id)).map_or(false, |fn_like| {
128                 fn_like.constness() == hir::Constness::Const
129             })
130         } else {
131             self.tcx.is_const_fn(def_id)
132         };
133
134         if let Some(&attr::Stability {
135             rustc_const_unstable: Some(attr::RustcConstUnstable {
136                 feature: ref feature_name
137             }),
138         .. }) = self.tcx.lookup_stability(def_id) {
139             self.promotable &=
140                 // feature-gate is enabled,
141                 self.tcx.features()
142                     .declared_lib_features
143                     .iter()
144                     .any(|&(ref sym, _)| sym == feature_name) ||
145
146                 // this comes from a crate with the feature-gate enabled,
147                 !def_id.is_local() ||
148
149                 // this comes from a macro that has #[allow_internal_unstable]
150                 span.allows_unstable();
151         }
152     }
153 }
154
155 impl<'a, 'tcx> Visitor<'tcx> for CheckCrateVisitor<'a, 'tcx> {
156     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
157         // note that we *do* visit nested bodies, because we override `visit_nested_body` below
158         NestedVisitorMap::None
159     }
160
161     fn visit_nested_body(&mut self, body_id: hir::BodyId) {
162         let item_id = self.tcx.hir.body_owner(body_id);
163         let item_def_id = self.tcx.hir.local_def_id(item_id);
164
165         let outer_in_fn = self.in_fn;
166         let outer_tables = self.tables;
167         let outer_param_env = self.param_env;
168         let outer_identity_substs = self.identity_substs;
169
170         self.in_fn = false;
171         self.in_static = false;
172
173         match self.tcx.hir.body_owner_kind(item_id) {
174             hir::BodyOwnerKind::Fn => self.in_fn = true,
175             hir::BodyOwnerKind::Static(_) => self.in_static = true,
176             _ => {}
177         };
178
179
180         self.tables = self.tcx.typeck_tables_of(item_def_id);
181         self.param_env = self.tcx.param_env(item_def_id);
182         self.identity_substs = Substs::identity_for_item(self.tcx, item_def_id);
183
184         let body = self.tcx.hir.body(body_id);
185
186         let tcx = self.tcx;
187         let param_env = self.param_env;
188         let region_scope_tree = self.tcx.region_scope_tree(item_def_id);
189         euv::ExprUseVisitor::new(self, tcx, param_env, &region_scope_tree, self.tables, None)
190             .consume_body(body);
191
192         self.visit_body(body);
193
194         self.in_fn = outer_in_fn;
195         self.tables = outer_tables;
196         self.param_env = outer_param_env;
197         self.identity_substs = outer_identity_substs;
198     }
199
200     fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt) {
201         match stmt.node {
202             hir::StmtDecl(ref decl, _) => {
203                 match decl.node {
204                     hir::DeclLocal(_) => {
205                         self.promotable = false;
206                     }
207                     // Item statements are allowed
208                     hir::DeclItem(_) => {}
209                 }
210             }
211             hir::StmtExpr(..) |
212             hir::StmtSemi(..) => {
213                 self.promotable = false;
214             }
215         }
216         intravisit::walk_stmt(self, stmt);
217     }
218
219     fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
220         let outer = self.promotable;
221         self.promotable = true;
222
223         let node_ty = self.tables.node_id_to_type(ex.hir_id);
224         check_expr(self, ex, node_ty);
225         check_adjustments(self, ex);
226
227         if let hir::ExprMatch(ref discr, ref arms, _) = ex.node {
228             // Compute the most demanding borrow from all the arms'
229             // patterns and set that on the discriminator.
230             let mut mut_borrow = false;
231             for pat in arms.iter().flat_map(|arm| &arm.pats) {
232                 if self.mut_rvalue_borrows.remove(&pat.id) {
233                     mut_borrow = true;
234                 }
235             }
236             if mut_borrow {
237                 self.mut_rvalue_borrows.insert(discr.id);
238             }
239         }
240
241         intravisit::walk_expr(self, ex);
242
243         // Handle borrows on (or inside the autorefs of) this expression.
244         if self.mut_rvalue_borrows.remove(&ex.id) {
245             self.promotable = false;
246         }
247
248         if self.promotable {
249             self.result.insert(ex.hir_id.local_id);
250         }
251         self.promotable &= outer;
252     }
253 }
254
255 /// This function is used to enforce the constraints on
256 /// const/static items. It walks through the *value*
257 /// of the item walking down the expression and evaluating
258 /// every nested expression. If the expression is not part
259 /// of a const/static item, it is qualified for promotion
260 /// instead of producing errors.
261 fn check_expr<'a, 'tcx>(v: &mut CheckCrateVisitor<'a, 'tcx>, e: &hir::Expr, node_ty: Ty<'tcx>) {
262     match node_ty.sty {
263         ty::TyAdt(def, _) if def.has_dtor(v.tcx) => {
264             v.promotable = false;
265         }
266         _ => {}
267     }
268
269     match e.node {
270         hir::ExprUnary(..) |
271         hir::ExprBinary(..) |
272         hir::ExprIndex(..) if v.tables.is_method_call(e) => {
273             v.promotable = false;
274         }
275         hir::ExprBox(_) => {
276             v.promotable = false;
277         }
278         hir::ExprUnary(op, _) => {
279             if op == hir::UnDeref {
280                 v.promotable = false;
281             }
282         }
283         hir::ExprBinary(op, ref lhs, _) => {
284             match v.tables.node_id_to_type(lhs.hir_id).sty {
285                 ty::TyRawPtr(_) => {
286                     assert!(op.node == hir::BiEq || op.node == hir::BiNe ||
287                             op.node == hir::BiLe || op.node == hir::BiLt ||
288                             op.node == hir::BiGe || op.node == hir::BiGt);
289
290                     v.promotable = false;
291                 }
292                 _ => {}
293             }
294         }
295         hir::ExprCast(ref from, _) => {
296             debug!("Checking const cast(id={})", from.id);
297             match v.tables.cast_kinds().get(from.hir_id) {
298                 None => v.tcx.sess.delay_span_bug(e.span, "no kind for cast"),
299                 Some(&CastKind::PtrAddrCast) | Some(&CastKind::FnPtrAddrCast) => {
300                     v.promotable = false;
301                 }
302                 _ => {}
303             }
304         }
305         hir::ExprPath(ref qpath) => {
306             let def = v.tables.qpath_def(qpath, e.hir_id);
307             match def {
308                 Def::VariantCtor(..) | Def::StructCtor(..) |
309                 Def::Fn(..) | Def::Method(..) =>  {}
310
311                 // References to a static that are themselves within a static
312                 // are inherently promotable with the exception
313                 //  of "#[thread_local]" statics, which may not
314                 // outlive the current function
315                 Def::Static(did, _) => {
316
317                     if v.in_static {
318                         let mut thread_local = false;
319
320                         for attr in &v.tcx.get_attrs(did)[..] {
321                             if attr.check_name("thread_local") {
322                                 debug!("Reference to Static(id={:?}) is unpromotable \
323                                        due to a #[thread_local] attribute", did);
324                                 v.promotable = false;
325                                 thread_local = true;
326                                 break;
327                             }
328                         }
329
330                         if !thread_local {
331                             debug!("Allowing promotion of reference to Static(id={:?})", did);
332                         }
333                     } else {
334                         debug!("Reference to Static(id={:?}) is unpromotable as it is not \
335                                referenced from a static", did);
336                         v.promotable = false;
337
338                     }
339                 }
340
341                 Def::Const(did) |
342                 Def::AssociatedConst(did) => {
343                     let promotable = if v.tcx.trait_of_item(did).is_some() {
344                         // Don't peek inside trait associated constants.
345                         false
346                     } else {
347                         v.tcx.at(e.span).const_is_rvalue_promotable_to_static(did)
348                     };
349
350                     // Just in case the type is more specific than the definition,
351                     // e.g. impl associated const with type parameters, check it.
352                     // Also, trait associated consts are relaxed by this.
353                     v.promotable &= promotable || v.type_has_only_promotable_values(node_ty);
354                 }
355
356                 _ => {
357                     v.promotable = false;
358                 }
359             }
360         }
361         hir::ExprCall(ref callee, _) => {
362             let mut callee = &**callee;
363             loop {
364                 callee = match callee.node {
365                     hir::ExprBlock(ref block, _) => match block.expr {
366                         Some(ref tail) => &tail,
367                         None => break
368                     },
369                     _ => break
370                 };
371             }
372             // The callee is an arbitrary expression, it doesn't necessarily have a definition.
373             let def = if let hir::ExprPath(ref qpath) = callee.node {
374                 v.tables.qpath_def(qpath, callee.hir_id)
375             } else {
376                 Def::Err
377             };
378             match def {
379                 Def::StructCtor(_, CtorKind::Fn) |
380                 Def::VariantCtor(_, CtorKind::Fn) => {}
381                 Def::Fn(did) => {
382                     v.handle_const_fn_call(did, node_ty, e.span)
383                 }
384                 Def::Method(did) => {
385                     match v.tcx.associated_item(did).container {
386                         ty::ImplContainer(_) => {
387                             v.handle_const_fn_call(did, node_ty, e.span)
388                         }
389                         ty::TraitContainer(_) => v.promotable = false
390                     }
391                 }
392                 _ => v.promotable = false
393             }
394         }
395         hir::ExprMethodCall(..) => {
396             if let Some(def) = v.tables.type_dependent_defs().get(e.hir_id) {
397                 let def_id = def.def_id();
398                 match v.tcx.associated_item(def_id).container {
399                     ty::ImplContainer(_) => v.handle_const_fn_call(def_id, node_ty, e.span),
400                     ty::TraitContainer(_) => v.promotable = false
401                 }
402             } else {
403                 v.tcx.sess.delay_span_bug(e.span, "no type-dependent def for method call");
404             }
405         }
406         hir::ExprStruct(..) => {
407             if let ty::TyAdt(adt, ..) = v.tables.expr_ty(e).sty {
408                 // unsafe_cell_type doesn't necessarily exist with no_core
409                 if Some(adt.did) == v.tcx.lang_items().unsafe_cell_type() {
410                     v.promotable = false;
411                 }
412             }
413         }
414
415         hir::ExprLit(_) |
416         hir::ExprAddrOf(..) |
417         hir::ExprRepeat(..) => {}
418
419         hir::ExprClosure(..) => {
420             // Paths in constant contexts cannot refer to local variables,
421             // as there are none, and thus closures can't have upvars there.
422             if v.tcx.with_freevars(e.id, |fv| !fv.is_empty()) {
423                 v.promotable = false;
424             }
425         }
426
427         hir::ExprBlock(..) |
428         hir::ExprIndex(..) |
429         hir::ExprField(..) |
430         hir::ExprArray(_) |
431         hir::ExprType(..) |
432         hir::ExprTup(..) => {}
433
434         // Conditional control flow (possible to implement).
435         hir::ExprMatch(..) |
436         hir::ExprIf(..) |
437
438         // Loops (not very meaningful in constants).
439         hir::ExprWhile(..) |
440         hir::ExprLoop(..) |
441
442         // More control flow (also not very meaningful).
443         hir::ExprBreak(..) |
444         hir::ExprAgain(_) |
445         hir::ExprRet(_) |
446
447         // Generator expressions
448         hir::ExprYield(_) |
449
450         // Expressions with side-effects.
451         hir::ExprAssign(..) |
452         hir::ExprAssignOp(..) |
453         hir::ExprInlineAsm(..) => {
454             v.promotable = false;
455         }
456     }
457 }
458
459 /// Check the adjustments of an expression
460 fn check_adjustments<'a, 'tcx>(v: &mut CheckCrateVisitor<'a, 'tcx>, e: &hir::Expr) {
461     use rustc::ty::adjustment::*;
462
463     let mut adjustments = v.tables.expr_adjustments(e).iter().peekable();
464     while let Some(adjustment) = adjustments.next() {
465         match adjustment.kind {
466             Adjust::NeverToAny |
467             Adjust::ReifyFnPointer |
468             Adjust::UnsafeFnPointer |
469             Adjust::ClosureFnPointer |
470             Adjust::MutToConstPointer |
471             Adjust::Borrow(_) |
472             Adjust::Unsize => {}
473
474             Adjust::Deref(_) => {
475                 if let Some(next_adjustment) = adjustments.peek() {
476                     if let Adjust::Borrow(_) = next_adjustment.kind {
477                         continue;
478                     }
479                 }
480                 v.promotable = false;
481                 break;
482             }
483         }
484     }
485 }
486
487 impl<'a, 'gcx, 'tcx> euv::Delegate<'tcx> for CheckCrateVisitor<'a, 'gcx> {
488     fn consume(&mut self,
489                _consume_id: ast::NodeId,
490                _consume_span: Span,
491                _cmt: &mc::cmt_,
492                _mode: euv::ConsumeMode) {}
493
494     fn borrow(&mut self,
495               borrow_id: ast::NodeId,
496               _borrow_span: Span,
497               cmt: &mc::cmt_<'tcx>,
498               _loan_region: ty::Region<'tcx>,
499               bk: ty::BorrowKind,
500               loan_cause: euv::LoanCause) {
501         // Kind of hacky, but we allow Unsafe coercions in constants.
502         // These occur when we convert a &T or *T to a *U, as well as
503         // when making a thin pointer (e.g., `*T`) into a fat pointer
504         // (e.g., `*Trait`).
505         match loan_cause {
506             euv::LoanCause::AutoUnsafe => {
507                 return;
508             }
509             _ => {}
510         }
511
512         let mut cur = cmt;
513         loop {
514             match cur.cat {
515                 Categorization::Rvalue(..) => {
516                     if loan_cause == euv::MatchDiscriminant {
517                         // Ignore the dummy immutable borrow created by EUV.
518                         break;
519                     }
520                     if bk.to_mutbl_lossy() == hir::MutMutable {
521                         self.mut_rvalue_borrows.insert(borrow_id);
522                     }
523                     break;
524                 }
525                 Categorization::StaticItem => {
526                     break;
527                 }
528                 Categorization::Deref(ref cmt, _) |
529                 Categorization::Downcast(ref cmt, _) |
530                 Categorization::Interior(ref cmt, _) => {
531                     cur = cmt;
532                 }
533
534                 Categorization::Upvar(..) |
535                 Categorization::Local(..) => break,
536             }
537         }
538     }
539
540     fn decl_without_init(&mut self, _id: ast::NodeId, _span: Span) {}
541     fn mutate(&mut self,
542               _assignment_id: ast::NodeId,
543               _assignment_span: Span,
544               _assignee_cmt: &mc::cmt_,
545               _mode: euv::MutateMode) {
546     }
547
548     fn matched_pat(&mut self, _: &hir::Pat, _: &mc::cmt_, _: euv::MatchMode) {}
549
550     fn consume_pat(&mut self, _consume_pat: &hir::Pat, _cmt: &mc::cmt_, _mode: euv::ConsumeMode) {}
551 }