2 use rustc_hir::def_id::DefId;
3 use rustc_middle::mir::{
4 Body, CastKind, NullOp, Operand, Place, ProjectionElem, Rvalue, Statement, StatementKind, Terminator,
7 use rustc_middle::ty::subst::GenericArgKind;
8 use rustc_middle::ty::{self, adjustment::PointerCast, Ty, TyCtxt};
9 use rustc_span::symbol::sym;
11 use rustc_target::spec::abi::Abi::RustIntrinsic;
14 type McfResult = Result<(), (Span, Cow<'static, str>)>;
16 pub fn is_min_const_fn(tcx: TyCtxt<'tcx>, body: &'a Body<'tcx>) -> McfResult {
17 let def_id = body.source.def_id();
18 let mut current = def_id;
20 let predicates = tcx.predicates_of(current);
21 for (predicate, _) in predicates.predicates {
22 match predicate.skip_binders() {
23 ty::PredicateAtom::RegionOutlives(_)
24 | ty::PredicateAtom::TypeOutlives(_)
25 | ty::PredicateAtom::WellFormed(_)
26 | ty::PredicateAtom::Projection(_)
27 | ty::PredicateAtom::ConstEvaluatable(..)
28 | ty::PredicateAtom::ConstEquate(..)
29 | ty::PredicateAtom::TypeWellFormedFromEnv(..) => continue,
30 ty::PredicateAtom::ObjectSafe(_) => panic!("object safe predicate on function: {:#?}", predicate),
31 ty::PredicateAtom::ClosureKind(..) => panic!("closure kind predicate on function: {:#?}", predicate),
32 ty::PredicateAtom::Subtype(_) => panic!("subtype predicate on function: {:#?}", predicate),
33 ty::PredicateAtom::Trait(pred, _) => {
34 if Some(pred.def_id()) == tcx.lang_items().sized_trait() {
37 match pred.self_ty().kind() {
39 let generics = tcx.generics_of(current);
40 let def = generics.type_param(p, tcx);
41 let span = tcx.def_span(def.def_id);
44 "trait bounds other than `Sized` \
45 on const fn parameters are unstable"
49 // other kinds of bounds are either tautologies
50 // or cause errors in other passes
56 match predicates.parent {
57 Some(parent) => current = parent,
62 for local in &body.local_decls {
63 check_ty(tcx, local.ty, local.source_info.span)?;
65 // impl trait is gone in MIR, so check the return type manually
68 tcx.fn_sig(def_id).output().skip_binder(),
69 body.local_decls.iter().next().unwrap().source_info.span,
72 for bb in body.basic_blocks() {
73 check_terminator(tcx, body, bb.terminator())?;
74 for stmt in &bb.statements {
75 check_statement(tcx, body, def_id, stmt)?;
81 fn check_ty(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, span: Span) -> McfResult {
82 for arg in ty.walk() {
83 let ty = match arg.unpack() {
84 GenericArgKind::Type(ty) => ty,
86 // No constraints on lifetimes or constants, except potentially
87 // constants' types, but `walk` will get to them as well.
88 GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => continue,
92 ty::Ref(_, _, hir::Mutability::Mut) => {
93 return Err((span, "mutable references in const fn are unstable".into()));
95 ty::Opaque(..) => return Err((span, "`impl Trait` in const fn is unstable".into())),
97 return Err((span, "function pointers in const fn are unstable".into()));
99 ty::Dynamic(preds, _) => {
100 for pred in preds.iter() {
101 match pred.skip_binder() {
102 ty::ExistentialPredicate::AutoTrait(_) | ty::ExistentialPredicate::Projection(_) => {
105 "trait bounds other than `Sized` \
106 on const fn parameters are unstable"
110 ty::ExistentialPredicate::Trait(trait_ref) => {
111 if Some(trait_ref.def_id) != tcx.lang_items().sized_trait() {
114 "trait bounds other than `Sized` \
115 on const fn parameters are unstable"
129 fn check_rvalue(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, def_id: DefId, rvalue: &Rvalue<'tcx>, span: Span) -> McfResult {
131 Rvalue::ThreadLocalRef(_) => Err((span, "cannot access thread local storage in const fn".into())),
132 Rvalue::Repeat(operand, _) | Rvalue::Use(operand) => check_operand(tcx, operand, span, body),
133 Rvalue::Len(place) | Rvalue::Discriminant(place) | Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
134 check_place(tcx, *place, span, body)
136 Rvalue::Cast(CastKind::Misc, operand, cast_ty) => {
137 use rustc_middle::ty::cast::CastTy;
138 let cast_in = CastTy::from_ty(operand.ty(body, tcx)).expect("bad input type for cast");
139 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
140 match (cast_in, cast_out) {
141 (CastTy::Ptr(_) | CastTy::FnPtr, CastTy::Int(_)) => {
142 Err((span, "casting pointers to ints is unstable in const fn".into()))
144 _ => check_operand(tcx, operand, span, body),
147 Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer | PointerCast::ArrayToPointer), operand, _) => {
148 check_operand(tcx, operand, span, body)
152 PointerCast::UnsafeFnPointer | PointerCast::ClosureFnPointer(_) | PointerCast::ReifyFnPointer,
156 ) => Err((span, "function pointer casts are not allowed in const fn".into())),
157 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), op, cast_ty) => {
158 let pointee_ty = if let Some(deref_ty) = cast_ty.builtin_deref(true) {
161 // We cannot allow this for now.
162 return Err((span, "unsizing casts are only allowed for references right now".into()));
164 let unsized_ty = tcx.struct_tail_erasing_lifetimes(pointee_ty, tcx.param_env(def_id));
165 if let ty::Slice(_) | ty::Str = unsized_ty.kind() {
166 check_operand(tcx, op, span, body)?;
167 // Casting/coercing things to slices is fine.
170 // We just can't allow trait objects until we have figured out trait method calls.
171 Err((span, "unsizing casts are not allowed in const fn".into()))
174 // binops are fine on integers
175 Rvalue::BinaryOp(_, lhs, rhs) | Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
176 check_operand(tcx, lhs, span, body)?;
177 check_operand(tcx, rhs, span, body)?;
178 let ty = lhs.ty(body, tcx);
179 if ty.is_integral() || ty.is_bool() || ty.is_char() {
184 "only int, `bool` and `char` operations are stable in const fn".into(),
188 Rvalue::NullaryOp(NullOp::SizeOf, _) => Ok(()),
189 Rvalue::NullaryOp(NullOp::Box, _) => Err((span, "heap allocations are not allowed in const fn".into())),
190 Rvalue::UnaryOp(_, operand) => {
191 let ty = operand.ty(body, tcx);
192 if ty.is_integral() || ty.is_bool() {
193 check_operand(tcx, operand, span, body)
195 Err((span, "only int and `bool` operations are stable in const fn".into()))
198 Rvalue::Aggregate(_, operands) => {
199 for operand in operands {
200 check_operand(tcx, operand, span, body)?;
207 fn check_statement(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, def_id: DefId, statement: &Statement<'tcx>) -> McfResult {
208 let span = statement.source_info.span;
209 match &statement.kind {
210 StatementKind::Assign(box (place, rval)) => {
211 check_place(tcx, *place, span, body)?;
212 check_rvalue(tcx, body, def_id, rval, span)
215 StatementKind::FakeRead(_, place) |
216 // just an assignment
217 StatementKind::SetDiscriminant { place, .. } => check_place(tcx, **place, span, body),
219 StatementKind::LlvmInlineAsm { .. } => Err((span, "cannot use inline assembly in const fn".into())),
221 // These are all NOPs
222 StatementKind::StorageLive(_)
223 | StatementKind::StorageDead(_)
224 | StatementKind::Retag { .. }
225 | StatementKind::AscribeUserType(..)
226 | StatementKind::Coverage(..)
227 | StatementKind::Nop => Ok(()),
231 fn check_operand(tcx: TyCtxt<'tcx>, operand: &Operand<'tcx>, span: Span, body: &Body<'tcx>) -> McfResult {
233 Operand::Move(place) | Operand::Copy(place) => check_place(tcx, *place, span, body),
234 Operand::Constant(c) => match c.check_static_ptr(tcx) {
235 Some(_) => Err((span, "cannot access `static` items in const fn".into())),
241 fn check_place(tcx: TyCtxt<'tcx>, place: Place<'tcx>, span: Span, body: &Body<'tcx>) -> McfResult {
242 let mut cursor = place.projection.as_ref();
243 while let [ref proj_base @ .., elem] = *cursor {
246 ProjectionElem::Field(..) => {
247 let base_ty = Place::ty_from(place.local, &proj_base, body, tcx).ty;
248 if let Some(def) = base_ty.ty_adt_def() {
249 // No union field accesses in `const fn`
251 return Err((span, "accessing union fields is unstable".into()));
255 ProjectionElem::ConstantIndex { .. }
256 | ProjectionElem::Downcast(..)
257 | ProjectionElem::Subslice { .. }
258 | ProjectionElem::Deref
259 | ProjectionElem::Index(_) => {},
266 fn check_terminator(tcx: TyCtxt<'tcx>, body: &'a Body<'tcx>, terminator: &Terminator<'tcx>) -> McfResult {
267 let span = terminator.source_info.span;
268 match &terminator.kind {
269 TerminatorKind::FalseEdge { .. }
270 | TerminatorKind::FalseUnwind { .. }
271 | TerminatorKind::Goto { .. }
272 | TerminatorKind::Return
273 | TerminatorKind::Resume
274 | TerminatorKind::Unreachable => Ok(()),
276 TerminatorKind::Drop { place, .. } => check_place(tcx, *place, span, body),
277 TerminatorKind::DropAndReplace { place, value, .. } => {
278 check_place(tcx, *place, span, body)?;
279 check_operand(tcx, value, span, body)
282 TerminatorKind::SwitchInt {
287 } => check_operand(tcx, discr, span, body),
289 TerminatorKind::Abort => Err((span, "abort is not stable in const fn".into())),
290 TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => {
291 Err((span, "const fn generators are unstable".into()))
294 TerminatorKind::Call {
302 let fn_ty = func.ty(body, tcx);
303 if let ty::FnDef(fn_def_id, _) = *fn_ty.kind() {
304 if !rustc_mir::const_eval::is_min_const_fn(tcx, fn_def_id) {
308 "can only call other `const fn` within a `const fn`, \
309 but `{:?}` is not stable as `const fn`",
316 // HACK: This is to "unstabilize" the `transmute` intrinsic
317 // within const fns. `transmute` is allowed in all other const contexts.
318 // This won't really scale to more intrinsics or functions. Let's allow const
319 // transmutes in const fn before we add more hacks to this.
320 if tcx.fn_sig(fn_def_id).abi() == RustIntrinsic && tcx.item_name(fn_def_id) == sym::transmute {
323 "can only call `transmute` from const items, not `const fn`".into(),
327 check_operand(tcx, func, span, body)?;
330 check_operand(tcx, arg, span, body)?;
334 Err((span, "can only call other const fns within const fn".into()))
338 TerminatorKind::Assert {
344 } => check_operand(tcx, cond, span, body),
346 TerminatorKind::InlineAsm { .. } => Err((span, "cannot use inline assembly in const fn".into())),