]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/qualify_min_const_fn.rs
ce35a06f86a037a4e009d69052212e7c02d97229
[rust.git] / src / librustc_mir / transform / qualify_min_const_fn.rs
1 use rustc::hir::def_id::DefId;
2 use rustc::hir;
3 use rustc::mir::*;
4 use rustc::ty::{self, Predicate, Ty, TyCtxt, adjustment::{PointerCast}};
5 use rustc_target::spec::abi;
6 use std::borrow::Cow;
7 use syntax_pos::Span;
8
9 type McfResult = Result<(), (Span, Cow<'static, str>)>;
10
11 pub fn is_min_const_fn(
12     tcx: TyCtxt<'a, 'tcx, 'tcx>,
13     def_id: DefId,
14     mir: &'a Mir<'tcx>,
15 ) -> McfResult {
16     let mut current = def_id;
17     loop {
18         let predicates = tcx.predicates_of(current);
19         for (predicate, _) in &predicates.predicates {
20             match predicate {
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)
28                 }
29                 Predicate::ClosureKind(..) => {
30                     bug!("closure kind predicate on function: {:#?}", predicate)
31                 }
32                 Predicate::Subtype(_) => bug!("subtype predicate on function: {:#?}", predicate),
33                 Predicate::Trait(pred) => {
34                     if Some(pred.def_id()) == tcx.lang_items().sized_trait() {
35                         continue;
36                     }
37                     match pred.skip_binder().self_ty().sty {
38                         ty::Param(ref p) => {
39                             let generics = tcx.generics_of(current);
40                             let def = generics.type_param(p, tcx);
41                             let span = tcx.def_span(def.def_id);
42                             return Err((
43                                 span,
44                                 "trait bounds other than `Sized` \
45                                  on const fn parameters are unstable"
46                                     .into(),
47                             ));
48                         }
49                         // other kinds of bounds are either tautologies
50                         // or cause errors in other passes
51                         _ => continue,
52                     }
53                 }
54             }
55         }
56         match predicates.parent {
57             Some(parent) => current = parent,
58             None => break,
59         }
60     }
61
62     for local in &mir.local_decls {
63         check_ty(tcx, local.ty, local.source_info.span, def_id)?;
64     }
65     // impl trait is gone in MIR, so check the return type manually
66     check_ty(
67         tcx,
68         tcx.fn_sig(def_id).output().skip_binder(),
69         mir.local_decls.iter().next().unwrap().source_info.span,
70         def_id,
71     )?;
72
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)?;
77         }
78     }
79     Ok(())
80 }
81
82 fn check_ty(
83     tcx: TyCtxt<'a, 'tcx, 'tcx>,
84     ty: Ty<'tcx>,
85     span: Span,
86     fn_def_id: DefId,
87 ) -> McfResult {
88     for ty in ty.walk() {
89         match ty.sty {
90             ty::Ref(_, _, hir::Mutability::MutMutable) => return Err((
91                 span,
92                 "mutable references in const fn are unstable".into(),
93             )),
94             ty::Opaque(..) => return Err((span, "`impl Trait` in const fn is unstable".into())),
95             ty::FnPtr(..) => {
96                 if !tcx.const_fn_is_allowed_fn_ptr(fn_def_id) {
97                     return Err((span, "function pointers in const fn are unstable".into()))
98                 }
99             }
100             ty::Dynamic(preds, _) => {
101                 for pred in preds.iter() {
102                     match pred.skip_binder() {
103                         | ty::ExistentialPredicate::AutoTrait(_)
104                         | ty::ExistentialPredicate::Projection(_) => {
105                             return Err((
106                                 span,
107                                 "trait bounds other than `Sized` \
108                                  on const fn parameters are unstable"
109                                     .into(),
110                             ))
111                         }
112                         ty::ExistentialPredicate::Trait(trait_ref) => {
113                             if Some(trait_ref.def_id) != tcx.lang_items().sized_trait() {
114                                 return Err((
115                                     span,
116                                     "trait bounds other than `Sized` \
117                                      on const fn parameters are unstable"
118                                         .into(),
119                                 ));
120                             }
121                         }
122                     }
123                 }
124             }
125             _ => {}
126         }
127     }
128     Ok(())
129 }
130
131 fn check_rvalue(
132     tcx: TyCtxt<'a, 'tcx, 'tcx>,
133     mir: &'a Mir<'tcx>,
134     rvalue: &Rvalue<'tcx>,
135     span: Span,
136 ) -> McfResult {
137     match rvalue {
138         Rvalue::Repeat(operand, _) | Rvalue::Use(operand) => {
139             check_operand(operand, span)
140         }
141         Rvalue::Len(place) | Rvalue::Discriminant(place) | Rvalue::Ref(_, _, place) => {
142             check_place(place, span)
143         }
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((
150                     span,
151                     "casting pointers to ints is unstable in const fn".into(),
152                 )),
153                 (CastTy::RPtr(_), CastTy::Float) => bug!(),
154                 (CastTy::RPtr(_), CastTy::Int(_)) => bug!(),
155                 (CastTy::Ptr(_), CastTy::RPtr(_)) => bug!(),
156                 _ => check_operand(operand, span),
157             }
158         }
159         Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, _) => {
160             check_operand(operand, span)
161         }
162         Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), _, _) |
163         Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), _, _) |
164         Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), _, _) => Err((
165             span,
166             "function pointer casts are not allowed in const fn".into(),
167         )),
168         Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), _, _) => Err((
169             span,
170             "unsizing casts are not allowed in const fn".into(),
171         )),
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() {
178                 Ok(())
179             } else {
180                 Err((
181                     span,
182                     "only int, `bool` and `char` operations are stable in const fn".into(),
183                 ))
184             }
185         }
186         Rvalue::NullaryOp(NullOp::SizeOf, _) => Ok(()),
187         Rvalue::NullaryOp(NullOp::Box, _) => Err((
188             span,
189             "heap allocations are not allowed in const fn".into(),
190         )),
191         Rvalue::UnaryOp(_, operand) => {
192             let ty = operand.ty(mir, tcx);
193             if ty.is_integral() || ty.is_bool() {
194                 check_operand(operand, span)
195             } else {
196                 Err((
197                     span,
198                     "only int and `bool` operations are stable in const fn".into(),
199                 ))
200             }
201         }
202         Rvalue::Aggregate(_, operands) => {
203             for operand in operands {
204                 check_operand(operand, span)?;
205             }
206             Ok(())
207         }
208     }
209 }
210
211 fn check_statement(
212     tcx: TyCtxt<'a, 'tcx, 'tcx>,
213     mir: &'a Mir<'tcx>,
214     statement: &Statement<'tcx>,
215 ) -> McfResult {
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)
221         }
222
223         StatementKind::FakeRead(_, place) => check_place(place, span),
224
225         // just an assignment
226         StatementKind::SetDiscriminant { .. } => Ok(()),
227
228         | StatementKind::InlineAsm { .. } => {
229             Err((span, "cannot use inline assembly in const fn".into()))
230         }
231
232         // These are all NOPs
233         | StatementKind::StorageLive(_)
234         | StatementKind::StorageDead(_)
235         | StatementKind::Retag { .. }
236         | StatementKind::AscribeUserType(..)
237         | StatementKind::Nop => Ok(()),
238     }
239 }
240
241 fn check_operand(
242     operand: &Operand<'tcx>,
243     span: Span,
244 ) -> McfResult {
245     match operand {
246         Operand::Move(place) | Operand::Copy(place) => {
247             check_place(place, span)
248         }
249         Operand::Constant(_) => Ok(()),
250     }
251 }
252
253 fn check_place(
254     place: &Place<'tcx>,
255     span: Span,
256 ) -> McfResult {
257     match place {
258         Place::Base(PlaceBase::Local(_)) => Ok(()),
259         // promoteds are always fine, they are essentially constants
260         Place::Base(PlaceBase::Static(box Static { kind: StaticKind::Promoted(_), .. })) => Ok(()),
261         Place::Base(PlaceBase::Static(box Static { kind: StaticKind::Static(_), .. })) =>
262             Err((span, "cannot access `static` items in const fn".into())),
263         Place::Projection(proj) => {
264             match proj.elem {
265                 | ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. }
266                 | ProjectionElem::Deref | ProjectionElem::Field(..) | ProjectionElem::Index(_) => {
267                     check_place(&proj.base, span)
268                 }
269                 | ProjectionElem::Downcast(..) => {
270                     Err((span, "`match` or `if let` in `const fn` is unstable".into()))
271                 }
272             }
273         }
274     }
275 }
276
277 fn check_terminator(
278     tcx: TyCtxt<'a, 'tcx, 'tcx>,
279     mir: &'a Mir<'tcx>,
280     terminator: &Terminator<'tcx>,
281 ) -> McfResult {
282     let span = terminator.source_info.span;
283     match &terminator.kind {
284         | TerminatorKind::Goto { .. }
285         | TerminatorKind::Return
286         | TerminatorKind::Resume => Ok(()),
287
288         TerminatorKind::Drop { location, .. } => {
289             check_place(location, span)
290         }
291         TerminatorKind::DropAndReplace { location, value, .. } => {
292             check_place(location, span)?;
293             check_operand(value, span)
294         },
295
296         TerminatorKind::FalseEdges { .. } | TerminatorKind::SwitchInt { .. } => Err((
297             span,
298             "`if`, `match`, `&&` and `||` are not stable in const fn".into(),
299         )),
300         | TerminatorKind::Abort | TerminatorKind::Unreachable => {
301             Err((span, "const fn with unreachable code is not stable".into()))
302         }
303         | TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => {
304             Err((span, "const fn generators are unstable".into()))
305         }
306
307         TerminatorKind::Call {
308             func,
309             args,
310             from_hir_call: _,
311             destination: _,
312             cleanup: _,
313         } => {
314             let fn_ty = func.ty(mir, tcx);
315             if let ty::FnDef(def_id, _) = fn_ty.sty {
316
317                 // some intrinsics are waved through if called inside the
318                 // standard library. Users never need to call them directly
319                 match tcx.fn_sig(def_id).abi() {
320                     abi::Abi::RustIntrinsic => if !is_intrinsic_whitelisted(tcx, def_id) {
321                         return Err((
322                             span,
323                             "can only call a curated list of intrinsics in `min_const_fn`".into(),
324                         ))
325                     },
326                     abi::Abi::Rust if tcx.is_min_const_fn(def_id) => {},
327                     abi::Abi::Rust => return Err((
328                         span,
329                         format!(
330                             "can only call other `const fn` within a `const fn`, \
331                              but `{:?}` is not stable as `const fn`",
332                             func,
333                         )
334                         .into(),
335                     )),
336                     abi => return Err((
337                         span,
338                         format!(
339                             "cannot call functions with `{}` abi in `min_const_fn`",
340                             abi,
341                         ).into(),
342                     )),
343                 }
344
345                 check_operand(func, span)?;
346
347                 for arg in args {
348                     check_operand(arg, span)?;
349                 }
350                 Ok(())
351             } else {
352                 Err((span, "can only call other const fns within const fn".into()))
353             }
354         }
355
356         TerminatorKind::Assert {
357             cond,
358             expected: _,
359             msg: _,
360             target: _,
361             cleanup: _,
362         } => check_operand(cond, span),
363
364         TerminatorKind::FalseUnwind { .. } => {
365             Err((span, "loops are not allowed in const fn".into()))
366         },
367     }
368 }
369
370 /// Returns `true` if the `def_id` refers to an intrisic which we've whitelisted
371 /// for being called from stable `const fn`s (`min_const_fn`).
372 ///
373 /// Adding more intrinsics requires sign-off from @rust-lang/lang.
374 fn is_intrinsic_whitelisted(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> bool {
375     match &tcx.item_name(def_id).as_str()[..] {
376         | "size_of"
377         | "min_align_of"
378         | "needs_drop"
379         // Arithmetic:
380         | "add_with_overflow" // ~> .overflowing_add
381         | "sub_with_overflow" // ~> .overflowing_sub
382         | "mul_with_overflow" // ~> .overflowing_mul
383         | "overflowing_add" // ~> .wrapping_add
384         | "overflowing_sub" // ~> .wrapping_sub
385         | "overflowing_mul" // ~> .wrapping_mul
386         | "saturating_add" // ~> .saturating_add
387         | "saturating_sub" // ~> .saturating_sub
388         | "unchecked_shl" // ~> .wrapping_shl
389         | "unchecked_shr" // ~> .wrapping_shr
390         | "rotate_left" // ~> .rotate_left
391         | "rotate_right" // ~> .rotate_right
392         | "ctpop" // ~> .count_ones
393         | "ctlz" // ~> .leading_zeros
394         | "cttz" // ~> .trailing_zeros
395         | "bswap" // ~> .swap_bytes
396         | "bitreverse" // ~> .reverse_bits
397         => true,
398         _ => false,
399     }
400 }