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