]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/qualify_consts.rs
Rollup merge of #48151 - echochamber:update_range_example, r=estebank
[rust.git] / src / librustc_mir / transform / qualify_consts.rs
1 // Copyright 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 //! A pass that qualifies constness of temporaries in constants,
12 //! static initializers and functions and also drives promotion.
13 //!
14 //! The Qualif flags below can be used to also provide better
15 //! diagnostics as to why a constant rvalue wasn't promoted.
16
17 use rustc_data_structures::bitvec::BitVector;
18 use rustc_data_structures::indexed_set::IdxSetBuf;
19 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
20 use rustc_data_structures::fx::FxHashSet;
21 use rustc::hir;
22 use rustc::hir::def_id::DefId;
23 use rustc::middle::const_val::ConstVal;
24 use rustc::traits::{self, Reveal};
25 use rustc::ty::{self, TyCtxt, Ty, TypeFoldable};
26 use rustc::ty::cast::CastTy;
27 use rustc::ty::maps::Providers;
28 use rustc::mir::*;
29 use rustc::mir::traversal::ReversePostorder;
30 use rustc::mir::visit::{PlaceContext, Visitor};
31 use rustc::middle::lang_items;
32 use syntax::abi::Abi;
33 use syntax::attr;
34 use syntax::ast::LitKind;
35 use syntax::feature_gate::UnstableFeatures;
36 use syntax_pos::{Span, DUMMY_SP};
37
38 use std::fmt;
39 use std::rc::Rc;
40 use std::usize;
41
42 use transform::{MirPass, MirSource};
43 use super::promote_consts::{self, Candidate, TempState};
44
45 bitflags! {
46     // Borrows of temporaries can be promoted only if
47     // they have none of these qualifications, with
48     // the exception of `STATIC_REF` (in statics only).
49     struct Qualif: u8 {
50         // Constant containing interior mutability (UnsafeCell).
51         const MUTABLE_INTERIOR  = 1 << 0;
52
53         // Constant containing an ADT that implements Drop.
54         const NEEDS_DROP        = 1 << 1;
55
56         // Function argument.
57         const FN_ARGUMENT       = 1 << 2;
58
59         // Static place or move from a static.
60         const STATIC            = 1 << 3;
61
62         // Reference to a static.
63         const STATIC_REF        = 1 << 4;
64
65         // Not constant at all - non-`const fn` calls, asm!,
66         // pointer comparisons, ptr-to-int casts, etc.
67         const NOT_CONST         = 1 << 5;
68
69         // Refers to temporaries which cannot be promoted as
70         // promote_consts decided they weren't simple enough.
71         const NOT_PROMOTABLE    = 1 << 6;
72
73         // Const items can only have MUTABLE_INTERIOR
74         // and NOT_PROMOTABLE without producing an error.
75         const CONST_ERROR       = !Qualif::MUTABLE_INTERIOR.bits &
76                                   !Qualif::NOT_PROMOTABLE.bits;
77     }
78 }
79
80 impl<'a, 'tcx> Qualif {
81     /// Remove flags which are impossible for the given type.
82     fn restrict(&mut self, ty: Ty<'tcx>,
83                 tcx: TyCtxt<'a, 'tcx, 'tcx>,
84                 param_env: ty::ParamEnv<'tcx>) {
85         if ty.is_freeze(tcx, param_env, DUMMY_SP) {
86             *self = *self - Qualif::MUTABLE_INTERIOR;
87         }
88         if !ty.needs_drop(tcx, param_env) {
89             *self = *self - Qualif::NEEDS_DROP;
90         }
91     }
92 }
93
94 /// What kind of item we are in.
95 #[derive(Copy, Clone, PartialEq, Eq)]
96 enum Mode {
97     Const,
98     Static,
99     StaticMut,
100     ConstFn,
101     Fn
102 }
103
104 impl fmt::Display for Mode {
105     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
106         match *self {
107             Mode::Const => write!(f, "constant"),
108             Mode::Static | Mode::StaticMut => write!(f, "static"),
109             Mode::ConstFn => write!(f, "constant function"),
110             Mode::Fn => write!(f, "function")
111         }
112     }
113 }
114
115 struct Qualifier<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
116     mode: Mode,
117     span: Span,
118     def_id: DefId,
119     mir: &'a Mir<'tcx>,
120     rpo: ReversePostorder<'a, 'tcx>,
121     tcx: TyCtxt<'a, 'gcx, 'tcx>,
122     param_env: ty::ParamEnv<'tcx>,
123     temp_qualif: IndexVec<Local, Option<Qualif>>,
124     return_qualif: Option<Qualif>,
125     qualif: Qualif,
126     const_fn_arg_vars: BitVector,
127     temp_promotion_state: IndexVec<Local, TempState>,
128     promotion_candidates: Vec<Candidate>
129 }
130
131 impl<'a, 'tcx> Qualifier<'a, 'tcx, 'tcx> {
132     fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
133            def_id: DefId,
134            mir: &'a Mir<'tcx>,
135            mode: Mode)
136            -> Qualifier<'a, 'tcx, 'tcx> {
137         let mut rpo = traversal::reverse_postorder(mir);
138         let temps = promote_consts::collect_temps(mir, &mut rpo);
139         rpo.reset();
140
141         let param_env = tcx.param_env(def_id);
142
143         let mut temp_qualif = IndexVec::from_elem(None, &mir.local_decls);
144         for arg in mir.args_iter() {
145             let mut qualif = Qualif::NEEDS_DROP;
146             qualif.restrict(mir.local_decls[arg].ty, tcx, param_env);
147             temp_qualif[arg] = Some(qualif);
148         }
149
150         Qualifier {
151             mode,
152             span: mir.span,
153             def_id,
154             mir,
155             rpo,
156             tcx,
157             param_env,
158             temp_qualif,
159             return_qualif: None,
160             qualif: Qualif::empty(),
161             const_fn_arg_vars: BitVector::new(mir.local_decls.len()),
162             temp_promotion_state: temps,
163             promotion_candidates: vec![]
164         }
165     }
166
167     // FIXME(eddyb) we could split the errors into meaningful
168     // categories, but enabling full miri would make that
169     // slightly pointless (even with feature-gating).
170     fn not_const(&mut self) {
171         self.add(Qualif::NOT_CONST);
172         if self.mode != Mode::Fn {
173             let mut err = struct_span_err!(
174                 self.tcx.sess,
175                 self.span,
176                 E0019,
177                 "{} contains unimplemented expression type",
178                 self.mode
179             );
180             if self.tcx.sess.teach(&err.get_code().unwrap()) {
181                 err.note("A function call isn't allowed in the const's initialization expression \
182                           because the expression's value must be known at compile-time.");
183                 err.note("Remember: you can't use a function call inside a const's initialization \
184                           expression! However, you can use it anywhere else.");
185             }
186             err.emit();
187         }
188     }
189
190     /// Error about extra statements in a constant.
191     fn statement_like(&mut self) {
192         self.add(Qualif::NOT_CONST);
193         if self.mode != Mode::Fn {
194             let mut err = struct_span_err!(
195                 self.tcx.sess,
196                 self.span,
197                 E0016,
198                 "blocks in {}s are limited to items and tail expressions",
199                 self.mode
200             );
201             if self.tcx.sess.teach(&err.get_code().unwrap()) {
202                 err.note("Blocks in constants may only contain items (such as constant, function \
203                           definition, etc...) and a tail expression.");
204                 err.help("To avoid it, you have to replace the non-item object.");
205             }
206             err.emit();
207         }
208     }
209
210     /// Add the given qualification to self.qualif.
211     fn add(&mut self, qualif: Qualif) {
212         self.qualif = self.qualif | qualif;
213     }
214
215     /// Add the given type's qualification to self.qualif.
216     fn add_type(&mut self, ty: Ty<'tcx>) {
217         self.add(Qualif::MUTABLE_INTERIOR | Qualif::NEEDS_DROP);
218         self.qualif.restrict(ty, self.tcx, self.param_env);
219     }
220
221     /// Within the provided closure, self.qualif will start
222     /// out empty, and its value after the closure returns will
223     /// be combined with the value before the call to nest.
224     fn nest<F: FnOnce(&mut Self)>(&mut self, f: F) {
225         let original = self.qualif;
226         self.qualif = Qualif::empty();
227         f(self);
228         self.add(original);
229     }
230
231     /// Check if a Local with the current qualifications is promotable.
232     fn can_promote(&mut self) -> bool {
233         // References to statics are allowed, but only in other statics.
234         if self.mode == Mode::Static || self.mode == Mode::StaticMut {
235             (self.qualif - Qualif::STATIC_REF).is_empty()
236         } else {
237             self.qualif.is_empty()
238         }
239     }
240
241     /// Check if a Place with the current qualifications could
242     /// be consumed, by either an operand or a Deref projection.
243     fn try_consume(&mut self) -> bool {
244         if self.qualif.intersects(Qualif::STATIC) && self.mode != Mode::Fn {
245             let msg = if self.mode == Mode::Static ||
246                          self.mode == Mode::StaticMut {
247                 "cannot refer to other statics by value, use the \
248                  address-of operator or a constant instead"
249             } else {
250                 "cannot refer to statics by value, use a constant instead"
251             };
252             struct_span_err!(self.tcx.sess, self.span, E0394, "{}", msg)
253                 .span_label(self.span, "referring to another static by value")
254                 .note("use the address-of operator or a constant instead")
255                 .emit();
256
257             // Replace STATIC with NOT_CONST to avoid further errors.
258             self.qualif = self.qualif - Qualif::STATIC;
259             self.add(Qualif::NOT_CONST);
260
261             false
262         } else {
263             true
264         }
265     }
266
267     /// Assign the current qualification to the given destination.
268     fn assign(&mut self, dest: &Place<'tcx>, location: Location) {
269         let qualif = self.qualif;
270         let span = self.span;
271         let store = |slot: &mut Option<Qualif>| {
272             if slot.is_some() {
273                 span_bug!(span, "multiple assignments to {:?}", dest);
274             }
275             *slot = Some(qualif);
276         };
277
278         // Only handle promotable temps in non-const functions.
279         if self.mode == Mode::Fn {
280             if let Place::Local(index) = *dest {
281                 if self.mir.local_kind(index) == LocalKind::Temp
282                 && self.temp_promotion_state[index].is_promotable() {
283                     debug!("store to promotable temp {:?}", index);
284                     store(&mut self.temp_qualif[index]);
285                 }
286             }
287             return;
288         }
289
290         match *dest {
291             Place::Local(index) if self.mir.local_kind(index) == LocalKind::Temp => {
292                 debug!("store to temp {:?}", index);
293                 store(&mut self.temp_qualif[index])
294             }
295             Place::Local(index) if self.mir.local_kind(index) == LocalKind::ReturnPointer => {
296                 debug!("store to return place {:?}", index);
297                 store(&mut self.return_qualif)
298             }
299
300             Place::Projection(box Projection {
301                 base: Place::Local(index),
302                 elem: ProjectionElem::Deref
303             }) if self.mir.local_kind(index) == LocalKind::Temp
304                && self.mir.local_decls[index].ty.is_box()
305                && self.temp_qualif[index].map_or(false, |qualif| {
306                     qualif.intersects(Qualif::NOT_CONST)
307                }) => {
308                 // Part of `box expr`, we should've errored
309                 // already for the Box allocation Rvalue.
310             }
311
312             // This must be an explicit assignment.
313             _ => {
314                 // Catch more errors in the destination.
315                 self.visit_place(dest, PlaceContext::Store, location);
316                 self.statement_like();
317             }
318         }
319     }
320
321     /// Qualify a whole const, static initializer or const fn.
322     fn qualify_const(&mut self) -> (Qualif, Rc<IdxSetBuf<Local>>) {
323         debug!("qualifying {} {:?}", self.mode, self.def_id);
324
325         let mir = self.mir;
326
327         let mut seen_blocks = BitVector::new(mir.basic_blocks().len());
328         let mut bb = START_BLOCK;
329         loop {
330             seen_blocks.insert(bb.index());
331
332             self.visit_basic_block_data(bb, &mir[bb]);
333
334             let target = match mir[bb].terminator().kind {
335                 TerminatorKind::Goto { target } |
336                 TerminatorKind::Drop { target, .. } |
337                 TerminatorKind::Assert { target, .. } |
338                 TerminatorKind::Call { destination: Some((_, target)), .. } => {
339                     Some(target)
340                 }
341
342                 // Non-terminating calls cannot produce any value.
343                 TerminatorKind::Call { destination: None, .. } => {
344                     break;
345                 }
346
347                 TerminatorKind::SwitchInt {..} |
348                 TerminatorKind::DropAndReplace { .. } |
349                 TerminatorKind::Resume |
350                 TerminatorKind::Abort |
351                 TerminatorKind::GeneratorDrop |
352                 TerminatorKind::Yield { .. } |
353                 TerminatorKind::Unreachable |
354                 TerminatorKind::FalseEdges { .. } |
355                 TerminatorKind::FalseUnwind { .. } => None,
356
357                 TerminatorKind::Return => {
358                     // Check for unused values. This usually means
359                     // there are extra statements in the AST.
360                     for temp in mir.temps_iter() {
361                         if self.temp_qualif[temp].is_none() {
362                             continue;
363                         }
364
365                         let state = self.temp_promotion_state[temp];
366                         if let TempState::Defined { location, uses: 0 } = state {
367                             let data = &mir[location.block];
368                             let stmt_idx = location.statement_index;
369
370                             // Get the span for the initialization.
371                             let source_info = if stmt_idx < data.statements.len() {
372                                 data.statements[stmt_idx].source_info
373                             } else {
374                                 data.terminator().source_info
375                             };
376                             self.span = source_info.span;
377
378                             // Treat this as a statement in the AST.
379                             self.statement_like();
380                         }
381                     }
382
383                     // Make sure there are no extra unassigned variables.
384                     self.qualif = Qualif::NOT_CONST;
385                     for index in mir.vars_iter() {
386                         if !self.const_fn_arg_vars.contains(index.index()) {
387                             debug!("unassigned variable {:?}", index);
388                             self.assign(&Place::Local(index), Location {
389                                 block: bb,
390                                 statement_index: usize::MAX,
391                             });
392                         }
393                     }
394
395                     break;
396                 }
397             };
398
399             match target {
400                 // No loops allowed.
401                 Some(target) if !seen_blocks.contains(target.index()) => {
402                     bb = target;
403                 }
404                 _ => {
405                     self.not_const();
406                     break;
407                 }
408             }
409         }
410
411         self.qualif = self.return_qualif.unwrap_or(Qualif::NOT_CONST);
412
413         // Account for errors in consts by using the
414         // conservative type qualification instead.
415         if self.qualif.intersects(Qualif::CONST_ERROR) {
416             self.qualif = Qualif::empty();
417             let return_ty = mir.return_ty();
418             self.add_type(return_ty);
419         }
420
421
422         // Collect all the temps we need to promote.
423         let mut promoted_temps = IdxSetBuf::new_empty(self.temp_promotion_state.len());
424
425         for candidate in &self.promotion_candidates {
426             match *candidate {
427                 Candidate::Ref(Location { block: bb, statement_index: stmt_idx }) => {
428                     match self.mir[bb].statements[stmt_idx].kind {
429                         StatementKind::Assign(_, Rvalue::Ref(_, _, Place::Local(index))) => {
430                             promoted_temps.add(&index);
431                         }
432                         _ => {}
433                     }
434                 }
435                 Candidate::Argument { .. } => {}
436             }
437         }
438
439         (self.qualif, Rc::new(promoted_temps))
440     }
441 }
442
443 /// Accumulates an Rvalue or Call's effects in self.qualif.
444 /// For functions (constant or not), it also records
445 /// candidates for promotion in promotion_candidates.
446 impl<'a, 'tcx> Visitor<'tcx> for Qualifier<'a, 'tcx, 'tcx> {
447     fn visit_local(&mut self,
448                    &local: &Local,
449                    _: PlaceContext<'tcx>,
450                    _: Location) {
451         let kind = self.mir.local_kind(local);
452         match kind {
453             LocalKind::ReturnPointer => {
454                 self.not_const();
455             }
456             LocalKind::Var => {
457                 self.add(Qualif::NOT_CONST);
458             }
459             LocalKind::Arg |
460             LocalKind::Temp => {
461                 if let LocalKind::Arg = kind {
462                     self.add(Qualif::FN_ARGUMENT);
463                 }
464
465                 if !self.temp_promotion_state[local].is_promotable() {
466                     self.add(Qualif::NOT_PROMOTABLE);
467                 }
468
469                 if let Some(qualif) = self.temp_qualif[local] {
470                     self.add(qualif);
471                 } else {
472                     self.not_const();
473                 }
474             }
475         }
476     }
477
478     fn visit_place(&mut self,
479                     place: &Place<'tcx>,
480                     context: PlaceContext<'tcx>,
481                     location: Location) {
482         match *place {
483             Place::Local(ref local) => self.visit_local(local, context, location),
484             Place::Static(ref global) => {
485                 self.add(Qualif::STATIC);
486
487                 if self.mode != Mode::Fn {
488                     for attr in &self.tcx.get_attrs(global.def_id)[..] {
489                         if attr.check_name("thread_local") {
490                             span_err!(self.tcx.sess, self.span, E0625,
491                                       "thread-local statics cannot be \
492                                        accessed at compile-time");
493                             self.add(Qualif::NOT_CONST);
494                             return;
495                         }
496                     }
497                 }
498
499                 if self.mode == Mode::Const || self.mode == Mode::ConstFn {
500                     let mut err = struct_span_err!(self.tcx.sess, self.span, E0013,
501                                                    "{}s cannot refer to statics, use \
502                                                     a constant instead", self.mode);
503                     if self.tcx.sess.teach(&err.get_code().unwrap()) {
504                         err.note(
505                             "Static and const variables can refer to other const variables. But a \
506                              const variable cannot refer to a static variable."
507                         );
508                         err.help(
509                             "To fix this, the value can be extracted as a const and then used."
510                         );
511                     }
512                     err.emit()
513                 }
514             }
515             Place::Projection(ref proj) => {
516                 self.nest(|this| {
517                     this.super_place(place, context, location);
518                     match proj.elem {
519                         ProjectionElem::Deref => {
520                             if !this.try_consume() {
521                                 return;
522                             }
523
524                             if this.qualif.intersects(Qualif::STATIC_REF) {
525                                 this.qualif = this.qualif - Qualif::STATIC_REF;
526                                 this.add(Qualif::STATIC);
527                             }
528
529                             let base_ty = proj.base.ty(this.mir, this.tcx).to_ty(this.tcx);
530                             if let ty::TyRawPtr(_) = base_ty.sty {
531                                 this.add(Qualif::NOT_CONST);
532                                 if this.mode != Mode::Fn {
533                                     let mut err = struct_span_err!(
534                                         this.tcx.sess,
535                                         this.span,
536                                         E0396,
537                                         "raw pointers cannot be dereferenced in {}s",
538                                         this.mode
539                                     );
540                                     err.span_label(this.span,
541                                                    "dereference of raw pointer in constant");
542                                     if this.tcx.sess.teach(&err.get_code().unwrap()) {
543                                         err.note(
544                                             "The value behind a raw pointer can't be determined \
545                                              at compile-time (or even link-time), which means it \
546                                              can't be used in a constant expression."
547                                         );
548                                         err.help("A possible fix is to dereference your pointer \
549                                                   at some point in run-time.");
550                                     }
551                                     err.emit();
552                                 }
553                             }
554                         }
555
556                         ProjectionElem::Field(..) |
557                         ProjectionElem::Index(_) => {
558                             if this.mode != Mode::Fn &&
559                                this.qualif.intersects(Qualif::STATIC) {
560                                 span_err!(this.tcx.sess, this.span, E0494,
561                                           "cannot refer to the interior of another \
562                                            static, use a constant instead");
563                             }
564                             let ty = place.ty(this.mir, this.tcx).to_ty(this.tcx);
565                             this.qualif.restrict(ty, this.tcx, this.param_env);
566                         }
567
568                         ProjectionElem::ConstantIndex {..} |
569                         ProjectionElem::Subslice {..} |
570                         ProjectionElem::Downcast(..) => {
571                             this.not_const()
572                         }
573                     }
574                 });
575             }
576         }
577     }
578
579     fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
580         match *operand {
581             Operand::Copy(_) |
582             Operand::Move(_) => {
583                 self.nest(|this| {
584                     this.super_operand(operand, location);
585                     this.try_consume();
586                 });
587
588                 // Mark the consumed locals to indicate later drops are noops.
589                 if let Operand::Move(Place::Local(local)) = *operand {
590                     self.temp_qualif[local] = self.temp_qualif[local].map(|q|
591                         q - Qualif::NEEDS_DROP
592                     );
593                 }
594             }
595             Operand::Constant(ref constant) => {
596                 if let Literal::Value {
597                     value: &ty::Const { val: ConstVal::Unevaluated(def_id, _), ty }
598                 } = constant.literal {
599                     // Don't peek inside trait associated constants.
600                     if self.tcx.trait_of_item(def_id).is_some() {
601                         self.add_type(ty);
602                     } else {
603                         let (bits, _) = self.tcx.at(constant.span).mir_const_qualif(def_id);
604
605                         let qualif = Qualif::from_bits(bits).expect("invalid mir_const_qualif");
606                         self.add(qualif);
607
608                         // Just in case the type is more specific than
609                         // the definition, e.g. impl associated const
610                         // with type parameters, take it into account.
611                         self.qualif.restrict(ty, self.tcx, self.param_env);
612                     }
613                 }
614             }
615         }
616     }
617
618     fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
619         // Recurse through operands and places.
620         self.super_rvalue(rvalue, location);
621
622         match *rvalue {
623             Rvalue::Use(_) |
624             Rvalue::Repeat(..) |
625             Rvalue::UnaryOp(UnOp::Neg, _) |
626             Rvalue::UnaryOp(UnOp::Not, _) |
627             Rvalue::NullaryOp(NullOp::SizeOf, _) |
628             Rvalue::CheckedBinaryOp(..) |
629             Rvalue::Cast(CastKind::ReifyFnPointer, ..) |
630             Rvalue::Cast(CastKind::UnsafeFnPointer, ..) |
631             Rvalue::Cast(CastKind::ClosureFnPointer, ..) |
632             Rvalue::Cast(CastKind::Unsize, ..) |
633             Rvalue::Discriminant(..) => {}
634
635             Rvalue::Len(_) => {
636                 // Static places in consts would have errored already,
637                 // don't treat length checks as reads from statics.
638                 self.qualif = self.qualif - Qualif::STATIC;
639             }
640
641             Rvalue::Ref(_, kind, ref place) => {
642                 // Static places in consts would have errored already,
643                 // only keep track of references to them here.
644                 if self.qualif.intersects(Qualif::STATIC) {
645                     self.qualif = self.qualif - Qualif::STATIC;
646                     self.add(Qualif::STATIC_REF);
647                 }
648
649                 let ty = place.ty(self.mir, self.tcx).to_ty(self.tcx);
650                 if let BorrowKind::Mut { .. } = kind {
651                     // In theory, any zero-sized value could be borrowed
652                     // mutably without consequences. However, only &mut []
653                     // is allowed right now, and only in functions.
654                     let allow = if self.mode == Mode::StaticMut {
655                         // Inside a `static mut`, &mut [...] is also allowed.
656                         match ty.sty {
657                             ty::TyArray(..) | ty::TySlice(_) => true,
658                             _ => false
659                         }
660                     } else if let ty::TyArray(_, len) = ty.sty {
661                         len.val.to_const_int().unwrap().to_u64().unwrap() == 0 &&
662                             self.mode == Mode::Fn
663                     } else {
664                         false
665                     };
666
667                     if !allow {
668                         self.add(Qualif::NOT_CONST);
669                         if self.mode != Mode::Fn {
670                             let mut err = struct_span_err!(self.tcx.sess,  self.span, E0017,
671                                                            "references in {}s may only refer \
672                                                             to immutable values", self.mode);
673                             err.span_label(self.span, format!("{}s require immutable values",
674                                                                 self.mode));
675                             if self.tcx.sess.teach(&err.get_code().unwrap()) {
676                                 err.note("References in statics and constants may only refer to \
677                                           immutable values.\n\n\
678                                           Statics are shared everywhere, and if they refer to \
679                                           mutable data one might violate memory safety since \
680                                           holding multiple mutable references to shared data is \
681                                           not allowed.\n\n\
682                                           If you really want global mutable state, try using \
683                                           static mut or a global UnsafeCell.");
684                             }
685                             err.emit();
686                         }
687                     }
688                 } else {
689                     // Constants cannot be borrowed if they contain interior mutability as
690                     // it means that our "silent insertion of statics" could change
691                     // initializer values (very bad).
692                     if self.qualif.intersects(Qualif::MUTABLE_INTERIOR) {
693                         // Replace MUTABLE_INTERIOR with NOT_CONST to avoid
694                         // duplicate errors (from reborrowing, for example).
695                         self.qualif = self.qualif - Qualif::MUTABLE_INTERIOR;
696                         self.add(Qualif::NOT_CONST);
697                         if self.mode != Mode::Fn {
698                             span_err!(self.tcx.sess, self.span, E0492,
699                                       "cannot borrow a constant which may contain \
700                                        interior mutability, create a static instead");
701                         }
702                     }
703                 }
704
705                 // We might have a candidate for promotion.
706                 let candidate = Candidate::Ref(location);
707                 if self.can_promote() {
708                     // We can only promote direct borrows of temps.
709                     if let Place::Local(local) = *place {
710                         if self.mir.local_kind(local) == LocalKind::Temp {
711                             self.promotion_candidates.push(candidate);
712                         }
713                     }
714                 }
715             }
716
717             Rvalue::Cast(CastKind::Misc, ref operand, cast_ty) => {
718                 let operand_ty = operand.ty(self.mir, self.tcx);
719                 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
720                 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
721                 match (cast_in, cast_out) {
722                     (CastTy::Ptr(_), CastTy::Int(_)) |
723                     (CastTy::FnPtr, CastTy::Int(_)) => {
724                         self.add(Qualif::NOT_CONST);
725                         if self.mode != Mode::Fn {
726                             let mut err = struct_span_err!(
727                                 self.tcx.sess,
728                                 self.span,
729                                 E0018,
730                                 "raw pointers cannot be cast to integers in {}s",
731                                 self.mode
732                             );
733                             if self.tcx.sess.teach(&err.get_code().unwrap()) {
734                                 err.note("\
735 The value of static and constant integers must be known at compile time. You can't cast a pointer \
736 to an integer because the address of a pointer can vary.
737
738 For example, if you write:
739
740 ```
741 static MY_STATIC: u32 = 42;
742 static MY_STATIC_ADDR: usize = &MY_STATIC as *const _ as usize;
743 static WHAT: usize = (MY_STATIC_ADDR^17) + MY_STATIC_ADDR;
744 ```
745
746 Then `MY_STATIC_ADDR` would contain the address of `MY_STATIC`. However, the address can change \
747 when the program is linked, as well as change between different executions due to ASLR, and many \
748 linkers would not be able to calculate the value of `WHAT`.
749
750 On the other hand, static and constant pointers can point either to a known numeric address or to \
751 the address of a symbol.
752
753 ```
754 static MY_STATIC: u32 = 42;
755 static MY_STATIC_ADDR: &'static u32 = &MY_STATIC;
756 const CONST_ADDR: *const u8 = 0x5f3759df as *const u8;
757 ```
758
759 This does not pose a problem by itself because they can't be accessed directly.");
760                             }
761                             err.emit();
762                         }
763                     }
764                     _ => {}
765                 }
766             }
767
768             Rvalue::BinaryOp(op, ref lhs, _) => {
769                 if let ty::TyRawPtr(_) = lhs.ty(self.mir, self.tcx).sty {
770                     assert!(op == BinOp::Eq || op == BinOp::Ne ||
771                             op == BinOp::Le || op == BinOp::Lt ||
772                             op == BinOp::Ge || op == BinOp::Gt ||
773                             op == BinOp::Offset);
774
775                     self.add(Qualif::NOT_CONST);
776                     if self.mode != Mode::Fn {
777                         struct_span_err!(
778                             self.tcx.sess, self.span, E0395,
779                             "raw pointers cannot be compared in {}s",
780                             self.mode)
781                         .span_label(
782                             self.span,
783                             "comparing raw pointers in static")
784                         .emit();
785                     }
786                 }
787             }
788
789             Rvalue::NullaryOp(NullOp::Box, _) => {
790                 self.add(Qualif::NOT_CONST);
791                 if self.mode != Mode::Fn {
792                     let mut err = struct_span_err!(self.tcx.sess, self.span, E0010,
793                                                    "allocations are not allowed in {}s", self.mode);
794                     err.span_label(self.span, format!("allocation not allowed in {}s", self.mode));
795                     if self.tcx.sess.teach(&err.get_code().unwrap()) {
796                         err.note(
797                             "The value of statics and constants must be known at compile time, \
798                              and they live for the entire lifetime of a program. Creating a boxed \
799                              value allocates memory on the heap at runtime, and therefore cannot \
800                              be done at compile time."
801                         );
802                     }
803                     err.emit();
804                 }
805             }
806
807             Rvalue::Aggregate(ref kind, _) => {
808                 if let AggregateKind::Adt(def, ..) = **kind {
809                     if def.has_dtor(self.tcx) {
810                         self.add(Qualif::NEEDS_DROP);
811                     }
812
813                     if Some(def.did) == self.tcx.lang_items().unsafe_cell_type() {
814                         let ty = rvalue.ty(self.mir, self.tcx);
815                         self.add_type(ty);
816                         assert!(self.qualif.intersects(Qualif::MUTABLE_INTERIOR));
817                     }
818                 }
819             }
820         }
821     }
822
823     fn visit_terminator_kind(&mut self,
824                              bb: BasicBlock,
825                              kind: &TerminatorKind<'tcx>,
826                              location: Location) {
827         if let TerminatorKind::Call { ref func, ref args, ref destination, .. } = *kind {
828             self.visit_operand(func, location);
829
830             let fn_ty = func.ty(self.mir, self.tcx);
831             let mut callee_def_id = None;
832             let (mut is_shuffle, mut is_const_fn) = (false, None);
833             if let ty::TyFnDef(def_id, _) = fn_ty.sty {
834                 callee_def_id = Some(def_id);
835                 match self.tcx.fn_sig(def_id).abi() {
836                     Abi::RustIntrinsic |
837                     Abi::PlatformIntrinsic => {
838                         assert!(!self.tcx.is_const_fn(def_id));
839                         match &self.tcx.item_name(def_id)[..] {
840                             "size_of" | "min_align_of" | "type_id" => is_const_fn = Some(def_id),
841
842                             name if name.starts_with("simd_shuffle") => {
843                                 is_shuffle = true;
844                             }
845
846                             _ => {}
847                         }
848                     }
849                     _ => {
850                         if self.tcx.is_const_fn(def_id) {
851                             is_const_fn = Some(def_id);
852                         }
853                     }
854                 }
855             }
856
857             let constant_arguments = callee_def_id.and_then(|id| {
858                 args_required_const(self.tcx, id)
859             });
860             for (i, arg) in args.iter().enumerate() {
861                 self.nest(|this| {
862                     this.visit_operand(arg, location);
863                     if this.mode != Mode::Fn {
864                         return
865                     }
866                     let candidate = Candidate::Argument { bb, index: i };
867                     if is_shuffle && i == 2 {
868                         if this.can_promote() {
869                             this.promotion_candidates.push(candidate);
870                         } else {
871                             span_err!(this.tcx.sess, this.span, E0526,
872                                       "shuffle indices are not constant");
873                         }
874                         return
875                     }
876
877                     let constant_arguments = match constant_arguments.as_ref() {
878                         Some(s) => s,
879                         None => return,
880                     };
881                     if !constant_arguments.contains(&i) {
882                         return
883                     }
884                     if this.can_promote() {
885                         this.promotion_candidates.push(candidate);
886                     } else {
887                         this.tcx.sess.span_err(this.span,
888                             &format!("argument {} is required to be a constant",
889                                      i + 1));
890                     }
891                 });
892             }
893
894             // Const fn calls.
895             if let Some(def_id) = is_const_fn {
896                 // find corresponding rustc_const_unstable feature
897                 if let Some(&attr::Stability {
898                     rustc_const_unstable: Some(attr::RustcConstUnstable {
899                         feature: ref feature_name
900                     }),
901                 .. }) = self.tcx.lookup_stability(def_id) {
902
903                     // We are in a const or static initializer,
904                     if self.mode != Mode::Fn &&
905
906                         // feature-gate is not enabled,
907                         !self.tcx.sess.features.borrow()
908                             .declared_lib_features
909                             .iter()
910                             .any(|&(ref sym, _)| sym == feature_name) &&
911
912                         // this doesn't come from a crate with the feature-gate enabled,
913                         self.def_id.is_local() &&
914
915                         // this doesn't come from a macro that has #[allow_internal_unstable]
916                         !self.span.allows_unstable()
917                     {
918                         let mut err = self.tcx.sess.struct_span_err(self.span,
919                             &format!("`{}` is not yet stable as a const fn",
920                                      self.tcx.item_path_str(def_id)));
921                         help!(&mut err,
922                               "in Nightly builds, add `#![feature({})]` \
923                                to the crate attributes to enable",
924                               feature_name);
925                         err.emit();
926                     }
927                 }
928             } else {
929                 self.qualif = Qualif::NOT_CONST;
930                 if self.mode != Mode::Fn {
931                     // FIXME(#24111) Remove this check when const fn stabilizes
932                     let (msg, note) = if let UnstableFeatures::Disallow =
933                             self.tcx.sess.opts.unstable_features {
934                         (format!("calls in {}s are limited to \
935                                   struct and enum constructors",
936                                  self.mode),
937                          Some("a limited form of compile-time function \
938                                evaluation is available on a nightly \
939                                compiler via `const fn`"))
940                     } else {
941                         (format!("calls in {}s are limited \
942                                   to constant functions, \
943                                   struct and enum constructors",
944                                  self.mode),
945                          None)
946                     };
947                     let mut err = struct_span_err!(self.tcx.sess, self.span, E0015, "{}", msg);
948                     if let Some(note) = note {
949                         err.span_note(self.span, note);
950                     }
951                     err.emit();
952                 }
953             }
954
955             if let Some((ref dest, _)) = *destination {
956                 // Avoid propagating irrelevant callee/argument qualifications.
957                 if self.qualif.intersects(Qualif::CONST_ERROR) {
958                     self.qualif = Qualif::NOT_CONST;
959                 } else {
960                     // Be conservative about the returned value of a const fn.
961                     let tcx = self.tcx;
962                     let ty = dest.ty(self.mir, tcx).to_ty(tcx);
963                     self.qualif = Qualif::empty();
964                     self.add_type(ty);
965                 }
966                 self.assign(dest, location);
967             }
968         } else if let TerminatorKind::Drop { location: ref place, .. } = *kind {
969             self.super_terminator_kind(bb, kind, location);
970
971             // Deny *any* live drops anywhere other than functions.
972             if self.mode != Mode::Fn {
973                 // HACK(eddyb) Emulate a bit of dataflow analysis,
974                 // conservatively, that drop elaboration will do.
975                 let needs_drop = if let Place::Local(local) = *place {
976                     if self.temp_qualif[local].map_or(true, |q| q.intersects(Qualif::NEEDS_DROP)) {
977                         Some(self.mir.local_decls[local].source_info.span)
978                     } else {
979                         None
980                     }
981                 } else {
982                     Some(self.span)
983                 };
984
985                 if let Some(span) = needs_drop {
986                     // Double-check the type being dropped, to minimize false positives.
987                     let ty = place.ty(self.mir, self.tcx).to_ty(self.tcx);
988                     if ty.needs_drop(self.tcx, self.param_env) {
989                         struct_span_err!(self.tcx.sess, span, E0493,
990                                          "destructors cannot be evaluated at compile-time")
991                             .span_label(span, format!("{}s cannot evaluate destructors",
992                                                       self.mode))
993                             .emit();
994                     }
995                 }
996             }
997         } else {
998             // Qualify any operands inside other terminators.
999             self.super_terminator_kind(bb, kind, location);
1000         }
1001     }
1002
1003     fn visit_assign(&mut self,
1004                     _: BasicBlock,
1005                     dest: &Place<'tcx>,
1006                     rvalue: &Rvalue<'tcx>,
1007                     location: Location) {
1008         self.visit_rvalue(rvalue, location);
1009
1010         // Check the allowed const fn argument forms.
1011         if let (Mode::ConstFn, &Place::Local(index)) = (self.mode, dest) {
1012             if self.mir.local_kind(index) == LocalKind::Var &&
1013                self.const_fn_arg_vars.insert(index.index()) {
1014
1015                 // Direct use of an argument is permitted.
1016                 match *rvalue {
1017                     Rvalue::Use(Operand::Copy(Place::Local(local))) |
1018                     Rvalue::Use(Operand::Move(Place::Local(local))) => {
1019                         if self.mir.local_kind(local) == LocalKind::Arg {
1020                             return;
1021                         }
1022                     }
1023                     _ => {}
1024                 }
1025
1026                 // Avoid a generic error for other uses of arguments.
1027                 if self.qualif.intersects(Qualif::FN_ARGUMENT) {
1028                     let decl = &self.mir.local_decls[index];
1029                     let mut err = struct_span_err!(
1030                         self.tcx.sess,
1031                         decl.source_info.span,
1032                         E0022,
1033                         "arguments of constant functions can only be immutable by-value bindings"
1034                     );
1035                     if self.tcx.sess.teach(&err.get_code().unwrap()) {
1036                         err.note("Constant functions are not allowed to mutate anything. Thus, \
1037                                   binding to an argument with a mutable pattern is not allowed.");
1038                         err.note("Remove any mutable bindings from the argument list to fix this \
1039                                   error. In case you need to mutate the argument, try lazily \
1040                                   initializing a global variable instead of using a const fn, or \
1041                                   refactoring the code to a functional style to avoid mutation if \
1042                                   possible.");
1043                     }
1044                     err.emit();
1045                     return;
1046                 }
1047             }
1048         }
1049
1050         self.assign(dest, location);
1051     }
1052
1053     fn visit_source_info(&mut self, source_info: &SourceInfo) {
1054         self.span = source_info.span;
1055     }
1056
1057     fn visit_statement(&mut self, bb: BasicBlock, statement: &Statement<'tcx>, location: Location) {
1058         self.nest(|this| {
1059             this.visit_source_info(&statement.source_info);
1060             match statement.kind {
1061                 StatementKind::Assign(ref place, ref rvalue) => {
1062                     this.visit_assign(bb, place, rvalue, location);
1063                 }
1064                 StatementKind::SetDiscriminant { .. } |
1065                 StatementKind::StorageLive(_) |
1066                 StatementKind::StorageDead(_) |
1067                 StatementKind::InlineAsm {..} |
1068                 StatementKind::EndRegion(_) |
1069                 StatementKind::Validate(..) |
1070                 StatementKind::Nop => {}
1071             }
1072         });
1073     }
1074
1075     fn visit_terminator(&mut self,
1076                         bb: BasicBlock,
1077                         terminator: &Terminator<'tcx>,
1078                         location: Location) {
1079         self.nest(|this| this.super_terminator(bb, terminator, location));
1080     }
1081 }
1082
1083 pub fn provide(providers: &mut Providers) {
1084     *providers = Providers {
1085         mir_const_qualif,
1086         ..*providers
1087     };
1088 }
1089
1090 fn mir_const_qualif<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1091                               def_id: DefId)
1092                               -> (u8, Rc<IdxSetBuf<Local>>) {
1093     // NB: This `borrow()` is guaranteed to be valid (i.e., the value
1094     // cannot yet be stolen), because `mir_validated()`, which steals
1095     // from `mir_const(), forces this query to execute before
1096     // performing the steal.
1097     let mir = &tcx.mir_const(def_id).borrow();
1098
1099     if mir.return_ty().references_error() {
1100         tcx.sess.delay_span_bug(mir.span, "mir_const_qualif: Mir had errors");
1101         return (Qualif::NOT_CONST.bits(), Rc::new(IdxSetBuf::new_empty(0)));
1102     }
1103
1104     let mut qualifier = Qualifier::new(tcx, def_id, mir, Mode::Const);
1105     let (qualif, promoted_temps) = qualifier.qualify_const();
1106     (qualif.bits(), promoted_temps)
1107 }
1108
1109 pub struct QualifyAndPromoteConstants;
1110
1111 impl MirPass for QualifyAndPromoteConstants {
1112     fn run_pass<'a, 'tcx>(&self,
1113                           tcx: TyCtxt<'a, 'tcx, 'tcx>,
1114                           src: MirSource,
1115                           mir: &mut Mir<'tcx>) {
1116         // There's not really any point in promoting errorful MIR.
1117         if mir.return_ty().references_error() {
1118             tcx.sess.delay_span_bug(mir.span, "QualifyAndPromoteConstants: Mir had errors");
1119             return;
1120         }
1121
1122         if src.promoted.is_some() {
1123             return;
1124         }
1125
1126         let def_id = src.def_id;
1127         let id = tcx.hir.as_local_node_id(def_id).unwrap();
1128         let mut const_promoted_temps = None;
1129         let mode = match tcx.hir.body_owner_kind(id) {
1130             hir::BodyOwnerKind::Fn => {
1131                 if tcx.is_const_fn(def_id) {
1132                     Mode::ConstFn
1133                 } else {
1134                     Mode::Fn
1135                 }
1136             }
1137             hir::BodyOwnerKind::Const => {
1138                 const_promoted_temps = Some(tcx.mir_const_qualif(def_id).1);
1139                 Mode::Const
1140             }
1141             hir::BodyOwnerKind::Static(hir::MutImmutable) => Mode::Static,
1142             hir::BodyOwnerKind::Static(hir::MutMutable) => Mode::StaticMut,
1143         };
1144
1145         if mode == Mode::Fn || mode == Mode::ConstFn {
1146             // This is ugly because Qualifier holds onto mir,
1147             // which can't be mutated until its scope ends.
1148             let (temps, candidates) = {
1149                 let mut qualifier = Qualifier::new(tcx, def_id, mir, mode);
1150                 if mode == Mode::ConstFn {
1151                     // Enforce a constant-like CFG for `const fn`.
1152                     qualifier.qualify_const();
1153                 } else {
1154                     while let Some((bb, data)) = qualifier.rpo.next() {
1155                         qualifier.visit_basic_block_data(bb, data);
1156                     }
1157                 }
1158
1159                 (qualifier.temp_promotion_state, qualifier.promotion_candidates)
1160             };
1161
1162             // Do the actual promotion, now that we know what's viable.
1163             promote_consts::promote_candidates(mir, tcx, temps, candidates);
1164         } else {
1165             let promoted_temps = if mode == Mode::Const {
1166                 // Already computed by `mir_const_qualif`.
1167                 const_promoted_temps.unwrap()
1168             } else {
1169                 Qualifier::new(tcx, def_id, mir, mode).qualify_const().1
1170             };
1171
1172             // In `const` and `static` everything without `StorageDead`
1173             // is `'static`, we don't have to create promoted MIR fragments,
1174             // just remove `Drop` and `StorageDead` on "promoted" locals.
1175             for block in mir.basic_blocks_mut() {
1176                 block.statements.retain(|statement| {
1177                     match statement.kind {
1178                         StatementKind::StorageDead(index) => {
1179                             !promoted_temps.contains(&index)
1180                         }
1181                         _ => true
1182                     }
1183                 });
1184                 let terminator = block.terminator_mut();
1185                 match terminator.kind {
1186                     TerminatorKind::Drop { location: Place::Local(index), target, .. } => {
1187                         if promoted_temps.contains(&index) {
1188                             terminator.kind = TerminatorKind::Goto {
1189                                 target,
1190                             };
1191                         }
1192                     }
1193                     _ => {}
1194                 }
1195             }
1196         }
1197
1198         // Statics must be Sync.
1199         if mode == Mode::Static {
1200             // `#[thread_local]` statics don't have to be `Sync`.
1201             for attr in &tcx.get_attrs(def_id)[..] {
1202                 if attr.check_name("thread_local") {
1203                     return;
1204                 }
1205             }
1206             let ty = mir.return_ty();
1207             tcx.infer_ctxt().enter(|infcx| {
1208                 let param_env = ty::ParamEnv::empty(Reveal::UserFacing);
1209                 let cause = traits::ObligationCause::new(mir.span, id, traits::SharedStatic);
1210                 let mut fulfillment_cx = traits::FulfillmentContext::new();
1211                 fulfillment_cx.register_bound(&infcx,
1212                                               param_env,
1213                                               ty,
1214                                               tcx.require_lang_item(lang_items::SyncTraitLangItem),
1215                                               cause);
1216                 if let Err(err) = fulfillment_cx.select_all_or_error(&infcx) {
1217                     infcx.report_fulfillment_errors(&err, None);
1218                 }
1219             });
1220         }
1221     }
1222 }
1223
1224 fn args_required_const(tcx: TyCtxt, def_id: DefId) -> Option<FxHashSet<usize>> {
1225     let attrs = tcx.get_attrs(def_id);
1226     let attr = attrs.iter().find(|a| a.check_name("rustc_args_required_const"))?;
1227     let mut ret = FxHashSet();
1228     for meta in attr.meta_item_list()? {
1229         match meta.literal()?.node {
1230             LitKind::Int(a, _) => { ret.insert(a as usize); }
1231             _ => return None,
1232         }
1233     }
1234     Some(ret)
1235 }