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.
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.
11 //! A pass that qualifies constness of temporaries in constants,
12 //! static initializers and functions and also drives promotion.
14 //! The Qualif flags below can be used to also provide better
15 //! diagnostics as to why a constant rvalue wasn't promoted.
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;
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;
29 use rustc::mir::traversal::ReversePostorder;
30 use rustc::mir::visit::{PlaceContext, Visitor};
31 use rustc::middle::lang_items;
34 use syntax::ast::LitKind;
35 use syntax::feature_gate::UnstableFeatures;
36 use syntax_pos::{Span, DUMMY_SP};
42 use transform::{MirPass, MirSource};
43 use super::promote_consts::{self, Candidate, TempState};
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).
50 // Constant containing interior mutability (UnsafeCell).
51 const MUTABLE_INTERIOR = 1 << 0;
53 // Constant containing an ADT that implements Drop.
54 const NEEDS_DROP = 1 << 1;
57 const FN_ARGUMENT = 1 << 2;
59 // Static place or move from a static.
60 const STATIC = 1 << 3;
62 // Reference to a static.
63 const STATIC_REF = 1 << 4;
65 // Not constant at all - non-`const fn` calls, asm!,
66 // pointer comparisons, ptr-to-int casts, etc.
67 const NOT_CONST = 1 << 5;
69 // Refers to temporaries which cannot be promoted as
70 // promote_consts decided they weren't simple enough.
71 const NOT_PROMOTABLE = 1 << 6;
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;
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;
88 if !ty.needs_drop(tcx, param_env) {
89 *self = *self - Qualif::NEEDS_DROP;
94 /// What kind of item we are in.
95 #[derive(Copy, Clone, PartialEq, Eq)]
104 impl fmt::Display for Mode {
105 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
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")
115 struct Qualifier<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
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>,
126 const_fn_arg_vars: BitVector,
127 temp_promotion_state: IndexVec<Local, TempState>,
128 promotion_candidates: Vec<Candidate>
131 impl<'a, 'tcx> Qualifier<'a, 'tcx, 'tcx> {
132 fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
136 -> Qualifier<'a, 'tcx, 'tcx> {
137 let mut rpo = traversal::reverse_postorder(mir);
138 let temps = promote_consts::collect_temps(mir, &mut rpo);
141 let param_env = tcx.param_env(def_id);
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);
160 qualif: Qualif::empty(),
161 const_fn_arg_vars: BitVector::new(mir.local_decls.len()),
162 temp_promotion_state: temps,
163 promotion_candidates: vec![]
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!(
177 "{} contains unimplemented expression type",
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.");
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!(
198 "blocks in {}s are limited to items and tail expressions",
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.");
210 /// Add the given qualification to self.qualif.
211 fn add(&mut self, qualif: Qualif) {
212 self.qualif = self.qualif | qualif;
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);
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();
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()
237 self.qualif.is_empty()
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"
250 "cannot refer to statics by value, use a constant instead"
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")
257 // Replace STATIC with NOT_CONST to avoid further errors.
258 self.qualif = self.qualif - Qualif::STATIC;
259 self.add(Qualif::NOT_CONST);
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>| {
273 span_bug!(span, "multiple assignments to {:?}", dest);
275 *slot = Some(qualif);
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]);
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])
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)
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)
308 // Part of `box expr`, we should've errored
309 // already for the Box allocation Rvalue.
312 // This must be an explicit assignment.
314 // Catch more errors in the destination.
315 self.visit_place(dest, PlaceContext::Store, location);
316 self.statement_like();
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);
327 let mut seen_blocks = BitVector::new(mir.basic_blocks().len());
328 let mut bb = START_BLOCK;
330 seen_blocks.insert(bb.index());
332 self.visit_basic_block_data(bb, &mir[bb]);
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)), .. } => {
342 // Non-terminating calls cannot produce any value.
343 TerminatorKind::Call { destination: None, .. } => {
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,
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() {
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;
370 // Get the span for the initialization.
371 let source_info = if stmt_idx < data.statements.len() {
372 data.statements[stmt_idx].source_info
374 data.terminator().source_info
376 self.span = source_info.span;
378 // Treat this as a statement in the AST.
379 self.statement_like();
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 {
390 statement_index: usize::MAX,
401 Some(target) if !seen_blocks.contains(target.index()) => {
411 self.qualif = self.return_qualif.unwrap_or(Qualif::NOT_CONST);
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);
422 // Collect all the temps we need to promote.
423 let mut promoted_temps = IdxSetBuf::new_empty(self.temp_promotion_state.len());
425 for candidate in &self.promotion_candidates {
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);
435 Candidate::Argument { .. } => {}
439 (self.qualif, Rc::new(promoted_temps))
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,
449 _: PlaceContext<'tcx>,
451 let kind = self.mir.local_kind(local);
453 LocalKind::ReturnPointer => {
457 self.add(Qualif::NOT_CONST);
461 if let LocalKind::Arg = kind {
462 self.add(Qualif::FN_ARGUMENT);
465 if !self.temp_promotion_state[local].is_promotable() {
466 self.add(Qualif::NOT_PROMOTABLE);
469 if let Some(qualif) = self.temp_qualif[local] {
478 fn visit_place(&mut self,
480 context: PlaceContext<'tcx>,
481 location: Location) {
483 Place::Local(ref local) => self.visit_local(local, context, location),
484 Place::Static(ref global) => {
485 self.add(Qualif::STATIC);
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);
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()) {
505 "Static and const variables can refer to other const variables. But a \
506 const variable cannot refer to a static variable."
509 "To fix this, the value can be extracted as a const and then used."
515 Place::Projection(ref proj) => {
517 this.super_place(place, context, location);
519 ProjectionElem::Deref => {
520 if !this.try_consume() {
524 if this.qualif.intersects(Qualif::STATIC_REF) {
525 this.qualif = this.qualif - Qualif::STATIC_REF;
526 this.add(Qualif::STATIC);
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!(
537 "raw pointers cannot be dereferenced in {}s",
540 err.span_label(this.span,
541 "dereference of raw pointer in constant");
542 if this.tcx.sess.teach(&err.get_code().unwrap()) {
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."
548 err.help("A possible fix is to dereference your pointer \
549 at some point in run-time.");
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");
564 let ty = place.ty(this.mir, this.tcx).to_ty(this.tcx);
565 this.qualif.restrict(ty, this.tcx, this.param_env);
568 ProjectionElem::ConstantIndex {..} |
569 ProjectionElem::Subslice {..} |
570 ProjectionElem::Downcast(..) => {
579 fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
582 Operand::Move(_) => {
584 this.super_operand(operand, location);
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
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() {
603 let (bits, _) = self.tcx.at(constant.span).mir_const_qualif(def_id);
605 let qualif = Qualif::from_bits(bits).expect("invalid mir_const_qualif");
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);
618 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
619 // Recurse through operands and places.
620 self.super_rvalue(rvalue, location);
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(..) => {}
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;
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);
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.
657 ty::TyArray(..) | ty::TySlice(_) => true,
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
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",
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 \
682 If you really want global mutable state, try using \
683 static mut or a global UnsafeCell.");
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");
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);
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!(
730 "raw pointers cannot be cast to integers in {}s",
733 if self.tcx.sess.teach(&err.get_code().unwrap()) {
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.
738 For example, if you write:
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;
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`.
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.
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;
759 This does not pose a problem by itself because they can't be accessed directly.");
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);
775 self.add(Qualif::NOT_CONST);
776 if self.mode != Mode::Fn {
778 self.tcx.sess, self.span, E0395,
779 "raw pointers cannot be compared in {}s",
783 "comparing raw pointers in static")
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()) {
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."
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);
813 if Some(def.did) == self.tcx.lang_items().unsafe_cell_type() {
814 let ty = rvalue.ty(self.mir, self.tcx);
816 assert!(self.qualif.intersects(Qualif::MUTABLE_INTERIOR));
823 fn visit_terminator_kind(&mut self,
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);
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() {
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),
842 name if name.starts_with("simd_shuffle") => {
850 if self.tcx.is_const_fn(def_id) {
851 is_const_fn = Some(def_id);
857 let constant_arguments = callee_def_id.and_then(|id| {
858 args_required_const(self.tcx, id)
860 for (i, arg) in args.iter().enumerate() {
862 this.visit_operand(arg, location);
863 if this.mode != Mode::Fn {
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);
871 span_err!(this.tcx.sess, this.span, E0526,
872 "shuffle indices are not constant");
877 let constant_arguments = match constant_arguments.as_ref() {
881 if !constant_arguments.contains(&i) {
884 if this.can_promote() {
885 this.promotion_candidates.push(candidate);
887 this.tcx.sess.span_err(this.span,
888 &format!("argument {} is required to be a constant",
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
901 .. }) = self.tcx.lookup_stability(def_id) {
903 // We are in a const or static initializer,
904 if self.mode != Mode::Fn &&
906 // feature-gate is not enabled,
907 !self.tcx.sess.features.borrow()
908 .declared_lib_features
910 .any(|&(ref sym, _)| sym == feature_name) &&
912 // this doesn't come from a crate with the feature-gate enabled,
913 self.def_id.is_local() &&
915 // this doesn't come from a macro that has #[allow_internal_unstable]
916 !self.span.allows_unstable()
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)));
922 "in Nightly builds, add `#![feature({})]` \
923 to the crate attributes to enable",
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",
937 Some("a limited form of compile-time function \
938 evaluation is available on a nightly \
939 compiler via `const fn`"))
941 (format!("calls in {}s are limited \
942 to constant functions, \
943 struct and enum constructors",
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);
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;
960 // Be conservative about the returned value of a const fn.
962 let ty = dest.ty(self.mir, tcx).to_ty(tcx);
963 self.qualif = Qualif::empty();
966 self.assign(dest, location);
968 } else if let TerminatorKind::Drop { location: ref place, .. } = *kind {
969 self.super_terminator_kind(bb, kind, location);
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)
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",
998 // Qualify any operands inside other terminators.
999 self.super_terminator_kind(bb, kind, location);
1003 fn visit_assign(&mut self,
1006 rvalue: &Rvalue<'tcx>,
1007 location: Location) {
1008 self.visit_rvalue(rvalue, location);
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()) {
1015 // Direct use of an argument is permitted.
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 {
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!(
1031 decl.source_info.span,
1033 "arguments of constant functions can only be immutable by-value bindings"
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 \
1050 self.assign(dest, location);
1053 fn visit_source_info(&mut self, source_info: &SourceInfo) {
1054 self.span = source_info.span;
1057 fn visit_statement(&mut self, bb: BasicBlock, statement: &Statement<'tcx>, location: Location) {
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);
1064 StatementKind::SetDiscriminant { .. } |
1065 StatementKind::StorageLive(_) |
1066 StatementKind::StorageDead(_) |
1067 StatementKind::InlineAsm {..} |
1068 StatementKind::EndRegion(_) |
1069 StatementKind::Validate(..) |
1070 StatementKind::Nop => {}
1075 fn visit_terminator(&mut self,
1077 terminator: &Terminator<'tcx>,
1078 location: Location) {
1079 self.nest(|this| this.super_terminator(bb, terminator, location));
1083 pub fn provide(providers: &mut Providers) {
1084 *providers = Providers {
1090 fn mir_const_qualif<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
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();
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)));
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)
1109 pub struct QualifyAndPromoteConstants;
1111 impl MirPass for QualifyAndPromoteConstants {
1112 fn run_pass<'a, 'tcx>(&self,
1113 tcx: TyCtxt<'a, 'tcx, 'tcx>,
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");
1122 if src.promoted.is_some() {
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) {
1137 hir::BodyOwnerKind::Const => {
1138 const_promoted_temps = Some(tcx.mir_const_qualif(def_id).1);
1141 hir::BodyOwnerKind::Static(hir::MutImmutable) => Mode::Static,
1142 hir::BodyOwnerKind::Static(hir::MutMutable) => Mode::StaticMut,
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();
1154 while let Some((bb, data)) = qualifier.rpo.next() {
1155 qualifier.visit_basic_block_data(bb, data);
1159 (qualifier.temp_promotion_state, qualifier.promotion_candidates)
1162 // Do the actual promotion, now that we know what's viable.
1163 promote_consts::promote_candidates(mir, tcx, temps, candidates);
1165 let promoted_temps = if mode == Mode::Const {
1166 // Already computed by `mir_const_qualif`.
1167 const_promoted_temps.unwrap()
1169 Qualifier::new(tcx, def_id, mir, mode).qualify_const().1
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)
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 {
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") {
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,
1214 tcx.require_lang_item(lang_items::SyncTraitLangItem),
1216 if let Err(err) = fulfillment_cx.select_all_or_error(&infcx) {
1217 infcx.report_fulfillment_errors(&err, None);
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); }