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(tcx: TyCtxt<'tcx, 'tcx>, def_id: DefId, body: &'a Body<'tcx>) -> McfResult {
12 let mut current = def_id;
14 let predicates = tcx.predicates_of(current);
15 for (predicate, _) in &predicates.predicates {
17 | Predicate::RegionOutlives(_)
18 | Predicate::TypeOutlives(_)
19 | Predicate::WellFormed(_)
20 | Predicate::Projection(_)
21 | Predicate::ConstEvaluatable(..) => continue,
22 | Predicate::ObjectSafe(_) => {
23 bug!("object safe predicate on function: {:#?}", predicate)
25 Predicate::ClosureKind(..) => {
26 bug!("closure kind predicate on function: {:#?}", predicate)
28 Predicate::Subtype(_) => bug!("subtype predicate on function: {:#?}", predicate),
29 Predicate::Trait(pred) => {
30 if Some(pred.def_id()) == tcx.lang_items().sized_trait() {
33 match pred.skip_binder().self_ty().sty {
35 let generics = tcx.generics_of(current);
36 let def = generics.type_param(p, tcx);
37 let span = tcx.def_span(def.def_id);
40 "trait bounds other than `Sized` \
41 on const fn parameters are unstable"
45 // other kinds of bounds are either tautologies
46 // or cause errors in other passes
52 match predicates.parent {
53 Some(parent) => current = parent,
58 for local in &body.local_decls {
59 check_ty(tcx, local.ty, local.source_info.span, def_id)?;
61 // impl trait is gone in MIR, so check the return type manually
64 tcx.fn_sig(def_id).output().skip_binder(),
65 body.local_decls.iter().next().unwrap().source_info.span,
69 for bb in body.basic_blocks() {
70 check_terminator(tcx, body, bb.terminator())?;
71 for stmt in &bb.statements {
72 check_statement(tcx, body, stmt)?;
78 fn check_ty(tcx: TyCtxt<'tcx, 'tcx>, ty: Ty<'tcx>, span: Span, fn_def_id: DefId) -> McfResult {
81 ty::Ref(_, _, hir::Mutability::MutMutable) => return Err((
83 "mutable references in const fn are unstable".into(),
85 ty::Opaque(..) => return Err((span, "`impl Trait` in const fn is unstable".into())),
87 if !tcx.const_fn_is_allowed_fn_ptr(fn_def_id) {
88 return Err((span, "function pointers in const fn are unstable".into()))
91 ty::Dynamic(preds, _) => {
92 for pred in preds.iter() {
93 match pred.skip_binder() {
94 | ty::ExistentialPredicate::AutoTrait(_)
95 | ty::ExistentialPredicate::Projection(_) => {
98 "trait bounds other than `Sized` \
99 on const fn parameters are unstable"
103 ty::ExistentialPredicate::Trait(trait_ref) => {
104 if Some(trait_ref.def_id) != tcx.lang_items().sized_trait() {
107 "trait bounds other than `Sized` \
108 on const fn parameters are unstable"
123 tcx: TyCtxt<'tcx, 'tcx>,
124 body: &'a Body<'tcx>,
125 rvalue: &Rvalue<'tcx>,
129 Rvalue::Repeat(operand, _) | Rvalue::Use(operand) => {
130 check_operand(operand, span)
132 Rvalue::Len(place) | Rvalue::Discriminant(place) | Rvalue::Ref(_, _, place) => {
133 check_place(place, span)
135 Rvalue::Cast(CastKind::Misc, operand, cast_ty) => {
136 use rustc::ty::cast::CastTy;
137 let cast_in = CastTy::from_ty(operand.ty(body, tcx)).expect("bad input type for cast");
138 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
139 match (cast_in, cast_out) {
140 (CastTy::Ptr(_), CastTy::Int(_)) | (CastTy::FnPtr, CastTy::Int(_)) => Err((
142 "casting pointers to ints is unstable in const fn".into(),
144 (CastTy::RPtr(_), CastTy::Float) => bug!(),
145 (CastTy::RPtr(_), CastTy::Int(_)) => bug!(),
146 (CastTy::Ptr(_), CastTy::RPtr(_)) => bug!(),
147 _ => check_operand(operand, span),
150 Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, _) => {
151 check_operand(operand, span)
153 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), _, _) |
154 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), _, _) |
155 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), _, _) => Err((
157 "function pointer casts are not allowed in const fn".into(),
159 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), _, _) => Err((
161 "unsizing casts are not allowed in const fn".into(),
163 // binops are fine on integers
164 Rvalue::BinaryOp(_, lhs, rhs) | Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
165 check_operand(lhs, span)?;
166 check_operand(rhs, span)?;
167 let ty = lhs.ty(body, tcx);
168 if ty.is_integral() || ty.is_bool() || ty.is_char() {
173 "only int, `bool` and `char` operations are stable in const fn".into(),
177 Rvalue::NullaryOp(NullOp::SizeOf, _) => Ok(()),
178 Rvalue::NullaryOp(NullOp::Box, _) => Err((
180 "heap allocations are not allowed in const fn".into(),
182 Rvalue::UnaryOp(_, operand) => {
183 let ty = operand.ty(body, tcx);
184 if ty.is_integral() || ty.is_bool() {
185 check_operand(operand, span)
189 "only int and `bool` operations are stable in const fn".into(),
193 Rvalue::Aggregate(_, operands) => {
194 for operand in operands {
195 check_operand(operand, span)?;
203 tcx: TyCtxt<'tcx, 'tcx>,
204 body: &'a Body<'tcx>,
205 statement: &Statement<'tcx>,
207 let span = statement.source_info.span;
208 match &statement.kind {
209 StatementKind::Assign(place, rval) => {
210 check_place(place, span)?;
211 check_rvalue(tcx, body, rval, span)
214 StatementKind::FakeRead(FakeReadCause::ForMatchedPlace, _) => {
215 Err((span, "loops and conditional expressions are not stable in const fn".into()))
218 StatementKind::FakeRead(_, place) => check_place(place, span),
220 // just an assignment
221 StatementKind::SetDiscriminant { .. } => Ok(()),
223 | StatementKind::InlineAsm { .. } => {
224 Err((span, "cannot use inline assembly in const fn".into()))
227 // These are all NOPs
228 | StatementKind::StorageLive(_)
229 | StatementKind::StorageDead(_)
230 | StatementKind::Retag { .. }
231 | StatementKind::AscribeUserType(..)
232 | StatementKind::Nop => Ok(()),
237 operand: &Operand<'tcx>,
241 Operand::Move(place) | Operand::Copy(place) => {
242 check_place(place, span)
244 Operand::Constant(_) => Ok(()),
252 place.iterate(|place_base, place_projection| {
253 for proj in place_projection {
255 ProjectionElem::Downcast(..) => {
256 return Err((span, "`match` or `if let` in `const fn` is unstable".into()));
258 ProjectionElem::ConstantIndex { .. }
259 | ProjectionElem::Subslice { .. }
260 | ProjectionElem::Deref
261 | ProjectionElem::Field(..)
262 | ProjectionElem::Index(_) => {}
267 PlaceBase::Static(box Static { kind: StaticKind::Static(_), .. }) => {
268 Err((span, "cannot access `static` items in const fn".into()))
271 | PlaceBase::Static(box Static { kind: StaticKind::Promoted(_), .. }) => Ok(()),
277 tcx: TyCtxt<'tcx, 'tcx>,
278 body: &'a Body<'tcx>,
279 terminator: &Terminator<'tcx>,
281 let span = terminator.source_info.span;
282 match &terminator.kind {
283 | TerminatorKind::Goto { .. }
284 | TerminatorKind::Return
285 | TerminatorKind::Resume => Ok(()),
287 TerminatorKind::Drop { location, .. } => {
288 check_place(location, span)
290 TerminatorKind::DropAndReplace { location, value, .. } => {
291 check_place(location, span)?;
292 check_operand(value, span)
295 TerminatorKind::FalseEdges { .. } | TerminatorKind::SwitchInt { .. } => Err((
297 "loops and conditional expressions are not stable in const fn".into(),
299 | TerminatorKind::Abort | TerminatorKind::Unreachable => {
300 Err((span, "const fn with unreachable code is not stable".into()))
302 | TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => {
303 Err((span, "const fn generators are unstable".into()))
306 TerminatorKind::Call {
313 let fn_ty = func.ty(body, tcx);
314 if let ty::FnDef(def_id, _) = fn_ty.sty {
316 // some intrinsics are waved through if called inside the
317 // standard library. Users never need to call them directly
318 match tcx.fn_sig(def_id).abi() {
319 abi::Abi::RustIntrinsic => if !is_intrinsic_whitelisted(tcx, def_id) {
322 "can only call a curated list of intrinsics in `min_const_fn`".into(),
325 abi::Abi::Rust if tcx.is_min_const_fn(def_id) => {},
326 abi::Abi::Rust => return Err((
329 "can only call other `const fn` within a `const fn`, \
330 but `{:?}` is not stable as `const fn`",
338 "cannot call functions with `{}` abi in `min_const_fn`",
344 check_operand(func, span)?;
347 check_operand(arg, span)?;
351 Err((span, "can only call other const fns within const fn".into()))
355 TerminatorKind::Assert {
361 } => check_operand(cond, span),
363 TerminatorKind::FalseUnwind { .. } => {
364 Err((span, "loops are not allowed in const fn".into()))
369 /// Returns `true` if the `def_id` refers to an intrisic which we've whitelisted
370 /// for being called from stable `const fn`s (`min_const_fn`).
372 /// Adding more intrinsics requires sign-off from @rust-lang/lang.
373 fn is_intrinsic_whitelisted(tcx: TyCtxt<'tcx, 'tcx>, def_id: DefId) -> bool {
374 match &tcx.item_name(def_id).as_str()[..] {
379 | "add_with_overflow" // ~> .overflowing_add
380 | "sub_with_overflow" // ~> .overflowing_sub
381 | "mul_with_overflow" // ~> .overflowing_mul
382 | "overflowing_add" // ~> .wrapping_add
383 | "overflowing_sub" // ~> .wrapping_sub
384 | "overflowing_mul" // ~> .wrapping_mul
385 | "saturating_add" // ~> .saturating_add
386 | "saturating_sub" // ~> .saturating_sub
387 | "unchecked_shl" // ~> .wrapping_shl
388 | "unchecked_shr" // ~> .wrapping_shr
389 | "rotate_left" // ~> .rotate_left
390 | "rotate_right" // ~> .rotate_right
391 | "ctpop" // ~> .count_ones
392 | "ctlz" // ~> .leading_zeros
393 | "cttz" // ~> .trailing_zeros
394 | "bswap" // ~> .swap_bytes
395 | "bitreverse" // ~> .reverse_bits