1 use rustc::hir::def_id::DefId;
4 use rustc::ty::{self, Predicate, Ty, TyCtxt, adjustment::{PointerCast}};
5 use rustc_target::spec::abi;
9 type McfResult = Result<(), (Span, Cow<'static, str>)>;
11 pub fn is_min_const_fn(
12 tcx: TyCtxt<'a, 'tcx, 'tcx>,
16 let mut current = def_id;
18 let predicates = tcx.predicates_of(current);
19 for (predicate, _) in &predicates.predicates {
21 | Predicate::RegionOutlives(_)
22 | Predicate::TypeOutlives(_)
23 | Predicate::WellFormed(_)
24 | Predicate::Projection(_)
25 | Predicate::ConstEvaluatable(..) => continue,
26 | Predicate::ObjectSafe(_) => {
27 bug!("object safe predicate on function: {:#?}", predicate)
29 Predicate::ClosureKind(..) => {
30 bug!("closure kind predicate on function: {:#?}", predicate)
32 Predicate::Subtype(_) => bug!("subtype predicate on function: {:#?}", predicate),
33 Predicate::Trait(pred) => {
34 if Some(pred.def_id()) == tcx.lang_items().sized_trait() {
37 match pred.skip_binder().self_ty().sty {
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 &mir.local_decls {
63 check_ty(tcx, local.ty, local.source_info.span, def_id)?;
65 // impl trait is gone in MIR, so check the return type manually
68 tcx.fn_sig(def_id).output().skip_binder(),
69 mir.local_decls.iter().next().unwrap().source_info.span,
73 for bb in mir.basic_blocks() {
74 check_terminator(tcx, mir, bb.terminator())?;
75 for stmt in &bb.statements {
76 check_statement(tcx, mir, stmt)?;
83 tcx: TyCtxt<'a, 'tcx, 'tcx>,
90 ty::Ref(_, _, hir::Mutability::MutMutable) => return Err((
92 "mutable references in const fn are unstable".into(),
94 ty::Opaque(..) => return Err((span, "`impl Trait` in const fn is unstable".into())),
96 if !tcx.const_fn_is_allowed_fn_ptr(fn_def_id) {
97 return Err((span, "function pointers in const fn are unstable".into()))
100 ty::Dynamic(preds, _) => {
101 for pred in preds.iter() {
102 match pred.skip_binder() {
103 | ty::ExistentialPredicate::AutoTrait(_)
104 | ty::ExistentialPredicate::Projection(_) => {
107 "trait bounds other than `Sized` \
108 on const fn parameters are unstable"
112 ty::ExistentialPredicate::Trait(trait_ref) => {
113 if Some(trait_ref.def_id) != tcx.lang_items().sized_trait() {
116 "trait bounds other than `Sized` \
117 on const fn parameters are unstable"
132 tcx: TyCtxt<'a, 'tcx, 'tcx>,
134 rvalue: &Rvalue<'tcx>,
138 Rvalue::Repeat(operand, _) | Rvalue::Use(operand) => {
139 check_operand(operand, span)
141 Rvalue::Len(place) | Rvalue::Discriminant(place) | Rvalue::Ref(_, _, place) => {
142 check_place(place, span)
144 Rvalue::Cast(CastKind::Misc, operand, cast_ty) => {
145 use rustc::ty::cast::CastTy;
146 let cast_in = CastTy::from_ty(operand.ty(mir, tcx)).expect("bad input type for cast");
147 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
148 match (cast_in, cast_out) {
149 (CastTy::Ptr(_), CastTy::Int(_)) | (CastTy::FnPtr, CastTy::Int(_)) => Err((
151 "casting pointers to ints is unstable in const fn".into(),
153 (CastTy::RPtr(_), CastTy::Float) => bug!(),
154 (CastTy::RPtr(_), CastTy::Int(_)) => bug!(),
155 (CastTy::Ptr(_), CastTy::RPtr(_)) => bug!(),
156 _ => check_operand(operand, span),
159 Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, _) => {
160 check_operand(operand, span)
162 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), _, _) |
163 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), _, _) |
164 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), _, _) => Err((
166 "function pointer casts are not allowed in const fn".into(),
168 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), _, _) => Err((
170 "unsizing casts are not allowed in const fn".into(),
172 // binops are fine on integers
173 Rvalue::BinaryOp(_, lhs, rhs) | Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
174 check_operand(lhs, span)?;
175 check_operand(rhs, span)?;
176 let ty = lhs.ty(mir, tcx);
177 if ty.is_integral() || ty.is_bool() || ty.is_char() {
182 "only int, `bool` and `char` operations are stable in const fn".into(),
186 Rvalue::NullaryOp(NullOp::SizeOf, _) => Ok(()),
187 Rvalue::NullaryOp(NullOp::Box, _) => Err((
189 "heap allocations are not allowed in const fn".into(),
191 Rvalue::UnaryOp(_, operand) => {
192 let ty = operand.ty(mir, tcx);
193 if ty.is_integral() || ty.is_bool() {
194 check_operand(operand, span)
198 "only int and `bool` operations are stable in const fn".into(),
202 Rvalue::Aggregate(_, operands) => {
203 for operand in operands {
204 check_operand(operand, span)?;
212 tcx: TyCtxt<'a, 'tcx, 'tcx>,
214 statement: &Statement<'tcx>,
216 let span = statement.source_info.span;
217 match &statement.kind {
218 StatementKind::Assign(place, rval) => {
219 check_place(place, span)?;
220 check_rvalue(tcx, mir, rval, span)
223 StatementKind::FakeRead(_, place) => check_place(place, span),
225 // just an assignment
226 StatementKind::SetDiscriminant { .. } => Ok(()),
228 | StatementKind::InlineAsm { .. } => {
229 Err((span, "cannot use inline assembly in const fn".into()))
232 // These are all NOPs
233 | StatementKind::StorageLive(_)
234 | StatementKind::StorageDead(_)
235 | StatementKind::Retag { .. }
236 | StatementKind::AscribeUserType(..)
237 | StatementKind::Nop => Ok(()),
242 operand: &Operand<'tcx>,
246 Operand::Move(place) | Operand::Copy(place) => {
247 check_place(place, span)
249 Operand::Constant(_) => Ok(()),
257 place.iterate(|place_base, place_projection| {
258 for proj in place_projection {
260 ProjectionElem::Downcast(..) => {
261 return Err((span, "`match` or `if let` in `const fn` is unstable".into()));
263 ProjectionElem::ConstantIndex { .. }
264 | ProjectionElem::Subslice { .. }
265 | ProjectionElem::Deref
266 | ProjectionElem::Field(..)
267 | ProjectionElem::Index(_) => {}
272 PlaceBase::Static(box Static { kind: StaticKind::Static(_), .. }) => {
273 Err((span, "cannot access `static` items in const fn".into()))
276 | PlaceBase::Static(box Static { kind: StaticKind::Promoted(_), .. }) => Ok(()),
282 tcx: TyCtxt<'a, 'tcx, 'tcx>,
284 terminator: &Terminator<'tcx>,
286 let span = terminator.source_info.span;
287 match &terminator.kind {
288 | TerminatorKind::Goto { .. }
289 | TerminatorKind::Return
290 | TerminatorKind::Resume => Ok(()),
292 TerminatorKind::Drop { location, .. } => {
293 check_place(location, span)
295 TerminatorKind::DropAndReplace { location, value, .. } => {
296 check_place(location, span)?;
297 check_operand(value, span)
300 TerminatorKind::FalseEdges { .. } | TerminatorKind::SwitchInt { .. } => Err((
302 "`if`, `match`, `&&` and `||` are not stable in const fn".into(),
304 | TerminatorKind::Abort | TerminatorKind::Unreachable => {
305 Err((span, "const fn with unreachable code is not stable".into()))
307 | TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => {
308 Err((span, "const fn generators are unstable".into()))
311 TerminatorKind::Call {
318 let fn_ty = func.ty(mir, tcx);
319 if let ty::FnDef(def_id, _) = fn_ty.sty {
321 // some intrinsics are waved through if called inside the
322 // standard library. Users never need to call them directly
323 match tcx.fn_sig(def_id).abi() {
324 abi::Abi::RustIntrinsic => if !is_intrinsic_whitelisted(tcx, def_id) {
327 "can only call a curated list of intrinsics in `min_const_fn`".into(),
330 abi::Abi::Rust if tcx.is_min_const_fn(def_id) => {},
331 abi::Abi::Rust => return Err((
334 "can only call other `const fn` within a `const fn`, \
335 but `{:?}` is not stable as `const fn`",
343 "cannot call functions with `{}` abi in `min_const_fn`",
349 check_operand(func, span)?;
352 check_operand(arg, span)?;
356 Err((span, "can only call other const fns within const fn".into()))
360 TerminatorKind::Assert {
366 } => check_operand(cond, span),
368 TerminatorKind::FalseUnwind { .. } => {
369 Err((span, "loops are not allowed in const fn".into()))
374 /// Returns `true` if the `def_id` refers to an intrisic which we've whitelisted
375 /// for being called from stable `const fn`s (`min_const_fn`).
377 /// Adding more intrinsics requires sign-off from @rust-lang/lang.
378 fn is_intrinsic_whitelisted(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> bool {
379 match &tcx.item_name(def_id).as_str()[..] {
384 | "add_with_overflow" // ~> .overflowing_add
385 | "sub_with_overflow" // ~> .overflowing_sub
386 | "mul_with_overflow" // ~> .overflowing_mul
387 | "overflowing_add" // ~> .wrapping_add
388 | "overflowing_sub" // ~> .wrapping_sub
389 | "overflowing_mul" // ~> .wrapping_mul
390 | "saturating_add" // ~> .saturating_add
391 | "saturating_sub" // ~> .saturating_sub
392 | "unchecked_shl" // ~> .wrapping_shl
393 | "unchecked_shr" // ~> .wrapping_shr
394 | "rotate_left" // ~> .rotate_left
395 | "rotate_right" // ~> .rotate_right
396 | "ctpop" // ~> .count_ones
397 | "ctlz" // ~> .leading_zeros
398 | "cttz" // ~> .trailing_zeros
399 | "bswap" // ~> .swap_bytes
400 | "bitreverse" // ~> .reverse_bits