]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/consts.rs
Rollup merge of #86374 - bossmc:enable-static-pie-for-gnu, r=nagisa
[rust.git] / compiler / rustc_middle / src / ty / consts.rs
1 use crate::mir::interpret::ConstValue;
2 use crate::mir::interpret::{LitToConstInput, Scalar};
3 use crate::ty::{
4     self, InlineConstSubsts, InlineConstSubstsParts, InternalSubsts, ParamEnv, ParamEnvAnd, Ty,
5     TyCtxt, TypeFoldable,
6 };
7 use rustc_errors::ErrorReported;
8 use rustc_hir as hir;
9 use rustc_hir::def_id::{DefId, LocalDefId};
10 use rustc_macros::HashStable;
11
12 mod int;
13 mod kind;
14 mod valtree;
15
16 pub use int::*;
17 pub use kind::*;
18 pub use valtree::*;
19
20 /// Typed constant value.
21 #[derive(Copy, Clone, Debug, Hash, TyEncodable, TyDecodable, Eq, PartialEq, Ord, PartialOrd)]
22 #[derive(HashStable)]
23 pub struct Const<'tcx> {
24     pub ty: Ty<'tcx>,
25
26     pub val: ConstKind<'tcx>,
27 }
28
29 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
30 static_assert_size!(Const<'_>, 48);
31
32 impl<'tcx> Const<'tcx> {
33     /// Literals and const generic parameters are eagerly converted to a constant, everything else
34     /// becomes `Unevaluated`.
35     pub fn from_anon_const(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx Self {
36         Self::from_opt_const_arg_anon_const(tcx, ty::WithOptConstParam::unknown(def_id))
37     }
38
39     #[instrument(skip(tcx), level = "debug")]
40     pub fn from_opt_const_arg_anon_const(
41         tcx: TyCtxt<'tcx>,
42         def: ty::WithOptConstParam<LocalDefId>,
43     ) -> &'tcx Self {
44         debug!("Const::from_anon_const(def={:?})", def);
45
46         let body_id = match tcx.hir().get_by_def_id(def.did) {
47             hir::Node::AnonConst(ac) => ac.body,
48             _ => span_bug!(
49                 tcx.def_span(def.did.to_def_id()),
50                 "from_anon_const can only process anonymous constants"
51             ),
52         };
53
54         let expr = &tcx.hir().body(body_id).value;
55         debug!(?expr);
56
57         let ty = tcx.type_of(def.def_id_for_type_of());
58
59         match Self::try_eval_lit_or_param(tcx, ty, expr) {
60             Some(v) => v,
61             None => tcx.mk_const(ty::Const {
62                 val: ty::ConstKind::Unevaluated(ty::Unevaluated {
63                     def: def.to_global(),
64                     substs: InternalSubsts::identity_for_item(tcx, def.did.to_def_id()),
65                     promoted: None,
66                 }),
67                 ty,
68             }),
69         }
70     }
71
72     #[instrument(skip(tcx), level = "debug")]
73     fn try_eval_lit_or_param(
74         tcx: TyCtxt<'tcx>,
75         ty: Ty<'tcx>,
76         expr: &'tcx hir::Expr<'tcx>,
77     ) -> Option<&'tcx Self> {
78         // Unwrap a block, so that e.g. `{ P }` is recognised as a parameter. Const arguments
79         // currently have to be wrapped in curly brackets, so it's necessary to special-case.
80         let expr = match &expr.kind {
81             hir::ExprKind::Block(block, _) if block.stmts.is_empty() && block.expr.is_some() => {
82                 block.expr.as_ref().unwrap()
83             }
84             _ => expr,
85         };
86
87         let lit_input = match expr.kind {
88             hir::ExprKind::Lit(ref lit) => Some(LitToConstInput { lit: &lit.node, ty, neg: false }),
89             hir::ExprKind::Unary(hir::UnOp::Neg, ref expr) => match expr.kind {
90                 hir::ExprKind::Lit(ref lit) => {
91                     Some(LitToConstInput { lit: &lit.node, ty, neg: true })
92                 }
93                 _ => None,
94             },
95             _ => None,
96         };
97
98         if let Some(lit_input) = lit_input {
99             // If an error occurred, ignore that it's a literal and leave reporting the error up to
100             // mir.
101             match tcx.at(expr.span).lit_to_const(lit_input) {
102                 Ok(c) => return Some(c),
103                 Err(e) => {
104                     tcx.sess.delay_span_bug(
105                         expr.span,
106                         &format!("Const::from_anon_const: couldn't lit_to_const {:?}", e),
107                     );
108                 }
109             }
110         }
111
112         use hir::{def::DefKind::ConstParam, def::Res, ExprKind, Path, QPath};
113         match expr.kind {
114             ExprKind::Path(QPath::Resolved(_, &Path { res: Res::Def(ConstParam, def_id), .. })) => {
115                 // Find the name and index of the const parameter by indexing the generics of
116                 // the parent item and construct a `ParamConst`.
117                 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
118                 let item_id = tcx.hir().get_parent_node(hir_id);
119                 let item_def_id = tcx.hir().local_def_id(item_id);
120                 let generics = tcx.generics_of(item_def_id.to_def_id());
121                 let index = generics.param_def_id_to_index[&def_id];
122                 let name = tcx.hir().name(hir_id);
123                 Some(tcx.mk_const(ty::Const {
124                     val: ty::ConstKind::Param(ty::ParamConst::new(index, name)),
125                     ty,
126                 }))
127             }
128             _ => None,
129         }
130     }
131
132     pub fn from_inline_const(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx Self {
133         debug!("Const::from_inline_const(def_id={:?})", def_id);
134
135         let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
136
137         let body_id = match tcx.hir().get(hir_id) {
138             hir::Node::AnonConst(ac) => ac.body,
139             _ => span_bug!(
140                 tcx.def_span(def_id.to_def_id()),
141                 "from_inline_const can only process anonymous constants"
142             ),
143         };
144
145         let expr = &tcx.hir().body(body_id).value;
146
147         let ty = tcx.typeck(def_id).node_type(hir_id);
148
149         let ret = match Self::try_eval_lit_or_param(tcx, ty, expr) {
150             Some(v) => v,
151             None => {
152                 let typeck_root_def_id = tcx.typeck_root_def_id(def_id.to_def_id());
153                 let parent_substs =
154                     tcx.erase_regions(InternalSubsts::identity_for_item(tcx, typeck_root_def_id));
155                 let substs =
156                     InlineConstSubsts::new(tcx, InlineConstSubstsParts { parent_substs, ty })
157                         .substs;
158                 tcx.mk_const(ty::Const {
159                     val: ty::ConstKind::Unevaluated(ty::Unevaluated {
160                         def: ty::WithOptConstParam::unknown(def_id).to_global(),
161                         substs,
162                         promoted: None,
163                     }),
164                     ty,
165                 })
166             }
167         };
168         debug_assert!(!ret.has_free_regions());
169         ret
170     }
171
172     /// Interns the given value as a constant.
173     #[inline]
174     pub fn from_value(tcx: TyCtxt<'tcx>, val: ConstValue<'tcx>, ty: Ty<'tcx>) -> &'tcx Self {
175         tcx.mk_const(Self { val: ConstKind::Value(val), ty })
176     }
177
178     #[inline]
179     /// Interns the given scalar as a constant.
180     pub fn from_scalar(tcx: TyCtxt<'tcx>, val: Scalar, ty: Ty<'tcx>) -> &'tcx Self {
181         Self::from_value(tcx, ConstValue::Scalar(val), ty)
182     }
183
184     #[inline]
185     /// Creates a constant with the given integer value and interns it.
186     pub fn from_bits(tcx: TyCtxt<'tcx>, bits: u128, ty: ParamEnvAnd<'tcx, Ty<'tcx>>) -> &'tcx Self {
187         let size = tcx
188             .layout_of(ty)
189             .unwrap_or_else(|e| panic!("could not compute layout for {:?}: {:?}", ty, e))
190             .size;
191         Self::from_scalar(tcx, Scalar::from_uint(bits, size), ty.value)
192     }
193
194     #[inline]
195     /// Creates an interned zst constant.
196     pub fn zero_sized(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> &'tcx Self {
197         Self::from_scalar(tcx, Scalar::ZST, ty)
198     }
199
200     #[inline]
201     /// Creates an interned bool constant.
202     pub fn from_bool(tcx: TyCtxt<'tcx>, v: bool) -> &'tcx Self {
203         Self::from_bits(tcx, v as u128, ParamEnv::empty().and(tcx.types.bool))
204     }
205
206     #[inline]
207     /// Creates an interned usize constant.
208     pub fn from_usize(tcx: TyCtxt<'tcx>, n: u64) -> &'tcx Self {
209         Self::from_bits(tcx, n as u128, ParamEnv::empty().and(tcx.types.usize))
210     }
211
212     #[inline]
213     /// Attempts to evaluate the given constant to bits. Can fail to evaluate in the presence of
214     /// generics (or erroneous code) or if the value can't be represented as bits (e.g. because it
215     /// contains const generic parameters or pointers).
216     pub fn try_eval_bits(
217         &self,
218         tcx: TyCtxt<'tcx>,
219         param_env: ParamEnv<'tcx>,
220         ty: Ty<'tcx>,
221     ) -> Option<u128> {
222         assert_eq!(self.ty, ty);
223         let size = tcx.layout_of(param_env.with_reveal_all_normalized(tcx).and(ty)).ok()?.size;
224         // if `ty` does not depend on generic parameters, use an empty param_env
225         self.val.eval(tcx, param_env).try_to_bits(size)
226     }
227
228     #[inline]
229     pub fn try_eval_bool(&self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> Option<bool> {
230         self.val.eval(tcx, param_env).try_to_bool()
231     }
232
233     #[inline]
234     pub fn try_eval_usize(&self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> Option<u64> {
235         self.val.eval(tcx, param_env).try_to_machine_usize(tcx)
236     }
237
238     #[inline]
239     /// Tries to evaluate the constant if it is `Unevaluated`. If that doesn't succeed, return the
240     /// unevaluated constant.
241     pub fn eval(&self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> &Const<'tcx> {
242         if let Some(val) = self.val.try_eval(tcx, param_env) {
243             match val {
244                 Ok(val) => Const::from_value(tcx, val, self.ty),
245                 Err(ErrorReported) => tcx.const_error(self.ty),
246             }
247         } else {
248             self
249         }
250     }
251
252     #[inline]
253     /// Panics if the value cannot be evaluated or doesn't contain a valid integer of the given type.
254     pub fn eval_bits(&self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>, ty: Ty<'tcx>) -> u128 {
255         self.try_eval_bits(tcx, param_env, ty)
256             .unwrap_or_else(|| bug!("expected bits of {:#?}, got {:#?}", ty, self))
257     }
258
259     #[inline]
260     /// Panics if the value cannot be evaluated or doesn't contain a valid `usize`.
261     pub fn eval_usize(&self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> u64 {
262         self.try_eval_usize(tcx, param_env)
263             .unwrap_or_else(|| bug!("expected usize, got {:#?}", self))
264     }
265 }
266
267 pub fn const_param_default<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx Const<'tcx> {
268     let default_def_id = match tcx.hir().get_by_def_id(def_id.expect_local()) {
269         hir::Node::GenericParam(hir::GenericParam {
270             kind: hir::GenericParamKind::Const { ty: _, default: Some(ac) },
271             ..
272         }) => tcx.hir().local_def_id(ac.hir_id),
273         _ => span_bug!(
274             tcx.def_span(def_id),
275             "`const_param_default` expected a generic parameter with a constant"
276         ),
277     };
278     Const::from_anon_const(tcx, default_def_id)
279 }