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