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