2 use rustc_hir::def_id::DefId;
3 use rustc_middle::mir::*;
4 use rustc_middle::ty::subst::GenericArgKind;
5 use rustc_middle::ty::{self, adjustment::PointerCast, Ty, TyCtxt};
6 use rustc_span::symbol::{sym};
8 use rustc_target::spec::abi::Abi::RustIntrinsic;
11 type McfResult = Result<(), (Span, Cow<'static, str>)>;
13 pub fn is_min_const_fn(tcx: TyCtxt<'tcx>, def_id: DefId, body: &'a Body<'tcx>) -> McfResult {
14 let mut current = def_id;
16 let predicates = tcx.predicates_of(current);
17 for (predicate, _) in predicates.predicates {
18 match predicate.skip_binders() {
19 ty::PredicateAtom::RegionOutlives(_)
20 | ty::PredicateAtom::TypeOutlives(_)
21 | ty::PredicateAtom::WellFormed(_)
22 | ty::PredicateAtom::Projection(_)
23 | ty::PredicateAtom::ConstEvaluatable(..)
24 | ty::PredicateAtom::ConstEquate(..)
25 | ty::PredicateAtom::TypeWellFormedFromEnv(..) => continue,
26 ty::PredicateAtom::ObjectSafe(_) => {
27 panic!("object safe predicate on function: {:#?}", predicate)
29 ty::PredicateAtom::ClosureKind(..) => {
30 panic!("closure kind predicate on function: {:#?}", predicate)
32 ty::PredicateAtom::Subtype(_) => {
33 panic!("subtype predicate on function: {:#?}", predicate)
35 ty::PredicateAtom::Trait(pred, _) => {
36 if Some(pred.def_id()) == tcx.lang_items().sized_trait() {
39 match pred.self_ty().kind() {
41 let generics = tcx.generics_of(current);
42 let def = generics.type_param(p, tcx);
43 let span = tcx.def_span(def.def_id);
46 "trait bounds other than `Sized` \
47 on const fn parameters are unstable"
51 // other kinds of bounds are either tautologies
52 // or cause errors in other passes
58 match predicates.parent {
59 Some(parent) => current = parent,
64 for local in &body.local_decls {
65 check_ty(tcx, local.ty, local.source_info.span)?;
67 // impl trait is gone in MIR, so check the return type manually
70 tcx.fn_sig(def_id).output().skip_binder(),
71 body.local_decls.iter().next().unwrap().source_info.span,
74 for bb in body.basic_blocks() {
75 check_terminator(tcx, body, bb.terminator())?;
76 for stmt in &bb.statements {
77 check_statement(tcx, body, def_id, stmt)?;
83 fn check_ty(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, span: Span) -> McfResult {
84 for arg in ty.walk() {
85 let ty = match arg.unpack() {
86 GenericArgKind::Type(ty) => ty,
88 // No constraints on lifetimes or constants, except potentially
89 // constants' types, but `walk` will get to them as well.
90 GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => continue,
94 ty::Ref(_, _, hir::Mutability::Mut) => {
95 return Err((span, "mutable references in const fn are unstable".into()));
97 ty::Opaque(..) => return Err((span, "`impl Trait` in const fn is unstable".into())),
99 return Err((span, "function pointers in const fn are unstable".into()));
101 ty::Dynamic(preds, _) => {
102 for pred in preds.iter() {
103 match pred.skip_binder() {
104 ty::ExistentialPredicate::AutoTrait(_)
105 | ty::ExistentialPredicate::Projection(_) => {
108 "trait bounds other than `Sized` \
109 on const fn parameters are unstable"
113 ty::ExistentialPredicate::Trait(trait_ref) => {
114 if Some(trait_ref.def_id) != tcx.lang_items().sized_trait() {
117 "trait bounds other than `Sized` \
118 on const fn parameters are unstable"
136 rvalue: &Rvalue<'tcx>,
140 Rvalue::ThreadLocalRef(_) => {
141 Err((span, "cannot access thread local storage in const fn".into()))
143 Rvalue::Repeat(operand, _) | Rvalue::Use(operand) => {
144 check_operand(tcx, operand, span, body)
147 | Rvalue::Discriminant(place)
148 | Rvalue::Ref(_, _, place)
149 | Rvalue::AddressOf(_, place) => check_place(tcx, *place, span, body),
150 Rvalue::Cast(CastKind::Misc, operand, cast_ty) => {
151 use rustc_middle::ty::cast::CastTy;
152 let cast_in = CastTy::from_ty(operand.ty(body, tcx)).expect("bad input type for cast");
153 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
154 match (cast_in, cast_out) {
155 (CastTy::Ptr(_) | CastTy::FnPtr, CastTy::Int(_)) => {
156 Err((span, "casting pointers to ints is unstable in const fn".into()))
158 _ => check_operand(tcx, operand, span, body),
162 CastKind::Pointer(PointerCast::MutToConstPointer | PointerCast::ArrayToPointer),
165 ) => check_operand(tcx, operand, span, body),
168 PointerCast::UnsafeFnPointer
169 | PointerCast::ClosureFnPointer(_)
170 | PointerCast::ReifyFnPointer,
174 ) => Err((span, "function pointer casts are not allowed in const fn".into())),
175 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), op, cast_ty) => {
176 let pointee_ty = if let Some(deref_ty) = cast_ty.builtin_deref(true) {
179 // We cannot allow this for now.
182 "unsizing casts are only allowed for references right now".into(),
185 let unsized_ty = tcx.struct_tail_erasing_lifetimes(pointee_ty, tcx.param_env(def_id));
186 if let ty::Slice(_) | ty::Str = unsized_ty.kind() {
187 check_operand(tcx, op, span, body)?;
188 // Casting/coercing things to slices is fine.
191 // We just can't allow trait objects until we have figured out trait method calls.
192 Err((span, "unsizing casts are not allowed in const fn".into()))
195 // binops are fine on integers
196 Rvalue::BinaryOp(_, lhs, rhs) | Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
197 check_operand(tcx, lhs, span, body)?;
198 check_operand(tcx, rhs, span, body)?;
199 let ty = lhs.ty(body, tcx);
200 if ty.is_integral() || ty.is_bool() || ty.is_char() {
203 Err((span, "only int, `bool` and `char` operations are stable in const fn".into()))
206 Rvalue::NullaryOp(NullOp::SizeOf, _) => Ok(()),
207 Rvalue::NullaryOp(NullOp::Box, _) => {
208 Err((span, "heap allocations are not allowed in const fn".into()))
210 Rvalue::UnaryOp(_, operand) => {
211 let ty = operand.ty(body, tcx);
212 if ty.is_integral() || ty.is_bool() {
213 check_operand(tcx, operand, span, body)
215 Err((span, "only int and `bool` operations are stable in const fn".into()))
218 Rvalue::Aggregate(_, operands) => {
219 for operand in operands {
220 check_operand(tcx, operand, span, body)?;
231 statement: &Statement<'tcx>,
233 let span = statement.source_info.span;
234 match &statement.kind {
235 StatementKind::Assign(box (place, rval)) => {
236 check_place(tcx, *place, span, body)?;
237 check_rvalue(tcx, body, def_id, rval, span)
240 StatementKind::FakeRead(_, place) => check_place(tcx, **place, span, body),
242 // just an assignment
243 StatementKind::SetDiscriminant { place, .. } => {
244 check_place(tcx, **place, span, body)
247 StatementKind::LlvmInlineAsm { .. } => {
248 Err((span, "cannot use inline assembly in const fn".into()))
251 // These are all NOPs
252 StatementKind::StorageLive(_)
253 | StatementKind::StorageDead(_)
254 | StatementKind::Retag { .. }
255 | StatementKind::AscribeUserType(..)
256 | StatementKind::Coverage(..)
257 | StatementKind::Nop => Ok(()),
263 operand: &Operand<'tcx>,
268 Operand::Move(place) | Operand::Copy(place) => check_place(tcx, *place, span, body),
269 Operand::Constant(c) => match c.check_static_ptr(tcx) {
270 Some(_) => Err((span, "cannot access `static` items in const fn".into())),
282 let mut cursor = place.projection.as_ref();
283 while let &[ref proj_base @ .., elem] = cursor {
286 ProjectionElem::Field(..) => {
287 let base_ty = Place::ty_from(place.local, &proj_base, body, tcx).ty;
288 if let Some(def) = base_ty.ty_adt_def() {
289 // No union field accesses in `const fn`
291 return Err((span, "accessing union fields is unstable".into()));
295 ProjectionElem::ConstantIndex { .. }
296 | ProjectionElem::Downcast(..)
297 | ProjectionElem::Subslice { .. }
298 | ProjectionElem::Deref
299 | ProjectionElem::Index(_) => {}
308 body: &'a Body<'tcx>,
309 terminator: &Terminator<'tcx>,
311 let span = terminator.source_info.span;
312 match &terminator.kind {
313 TerminatorKind::FalseEdge { .. }
314 | TerminatorKind::FalseUnwind { .. }
315 | TerminatorKind::Goto { .. }
316 | TerminatorKind::Return
317 | TerminatorKind::Resume
318 | TerminatorKind::Unreachable => Ok(()),
320 TerminatorKind::Drop { place, .. } => check_place(tcx, *place, span, body),
321 TerminatorKind::DropAndReplace { place, value, .. } => {
322 check_place(tcx, *place, span, body)?;
323 check_operand(tcx, value, span, body)
326 TerminatorKind::SwitchInt { discr, switch_ty: _, values: _, targets: _ } => {
327 check_operand(tcx, discr, span, body)
330 TerminatorKind::Abort => Err((span, "abort is not stable in const fn".into())),
331 TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => {
332 Err((span, "const fn generators are unstable".into()))
335 TerminatorKind::Call {
343 let fn_ty = func.ty(body, tcx);
344 if let ty::FnDef(fn_def_id, _) = *fn_ty.kind() {
345 if !rustc_mir::const_eval::is_min_const_fn(tcx, fn_def_id)
350 "can only call other `const fn` within a `const fn`, \
351 but `{:?}` is not stable as `const fn`",
358 // HACK: This is to "unstabilize" the `transmute` intrinsic
359 // within const fns. `transmute` is allowed in all other const contexts.
360 // This won't really scale to more intrinsics or functions. Let's allow const
361 // transmutes in const fn before we add more hacks to this.
362 if tcx.fn_sig(fn_def_id).abi() == RustIntrinsic
363 && tcx.item_name(fn_def_id) == sym::transmute
367 "can only call `transmute` from const items, not `const fn`".into(),
371 check_operand(tcx, func, span, body)?;
374 check_operand(tcx, arg, span, body)?;
378 Err((span, "can only call other const fns within const fn".into()))
382 TerminatorKind::Assert { cond, expected: _, msg: _, target: _, cleanup: _ } => {
383 check_operand(tcx, cond, span, body)
386 TerminatorKind::InlineAsm { .. } => {
387 Err((span, "cannot use inline assembly in const fn".into()))