rustc_type_ir/
flags.rs

1use crate::inherent::*;
2use crate::visit::Flags;
3use crate::{self as ty, Interner};
4
5bitflags::bitflags! {
6    /// Flags that we track on types. These flags are propagated upwards
7    /// through the type during type construction, so that we can quickly check
8    /// whether the type has various kinds of types in it without recursing
9    /// over the type itself.
10    #[derive(Debug, PartialEq, Eq, Clone, Copy)]
11    pub struct TypeFlags: u32 {
12        // Does this have parameters? Used to determine whether instantiation is
13        // required.
14        /// Does this have `Param`?
15        const HAS_TY_PARAM                = 1 << 0;
16        /// Does this have `ReEarlyParam`?
17        const HAS_RE_PARAM                = 1 << 1;
18        /// Does this have `ConstKind::Param`?
19        const HAS_CT_PARAM                = 1 << 2;
20
21        const HAS_PARAM                   = TypeFlags::HAS_TY_PARAM.bits()
22                                          | TypeFlags::HAS_RE_PARAM.bits()
23                                          | TypeFlags::HAS_CT_PARAM.bits();
24
25        /// Does this have `Infer`?
26        const HAS_TY_INFER                = 1 << 3;
27        /// Does this have `ReVar`?
28        const HAS_RE_INFER                = 1 << 4;
29        /// Does this have `ConstKind::Infer`?
30        const HAS_CT_INFER                = 1 << 5;
31
32        /// Does this have inference variables? Used to determine whether
33        /// inference is required.
34        const HAS_INFER                   = TypeFlags::HAS_TY_INFER.bits()
35                                          | TypeFlags::HAS_RE_INFER.bits()
36                                          | TypeFlags::HAS_CT_INFER.bits();
37
38        /// Does this have `Placeholder`?
39        const HAS_TY_PLACEHOLDER          = 1 << 6;
40        /// Does this have `RePlaceholder`?
41        const HAS_RE_PLACEHOLDER          = 1 << 7;
42        /// Does this have `ConstKind::Placeholder`?
43        const HAS_CT_PLACEHOLDER          = 1 << 8;
44
45        /// Does this have placeholders?
46        const HAS_PLACEHOLDER             = TypeFlags::HAS_TY_PLACEHOLDER.bits()
47                                          | TypeFlags::HAS_RE_PLACEHOLDER.bits()
48                                          | TypeFlags::HAS_CT_PLACEHOLDER.bits();
49
50        /// `true` if there are "names" of regions and so forth
51        /// that are local to a particular fn/inferctxt
52        const HAS_FREE_LOCAL_REGIONS      = 1 << 9;
53
54        /// `true` if there are "names" of types and regions and so forth
55        /// that are local to a particular fn
56        const HAS_FREE_LOCAL_NAMES        = TypeFlags::HAS_TY_PARAM.bits()
57                                          | TypeFlags::HAS_CT_PARAM.bits()
58                                          | TypeFlags::HAS_TY_INFER.bits()
59                                          | TypeFlags::HAS_CT_INFER.bits()
60                                          | TypeFlags::HAS_TY_PLACEHOLDER.bits()
61                                          | TypeFlags::HAS_CT_PLACEHOLDER.bits()
62                                          // We consider 'freshened' types and constants
63                                          // to depend on a particular fn.
64                                          // The freshening process throws away information,
65                                          // which can make things unsuitable for use in a global
66                                          // cache. Note that there is no 'fresh lifetime' flag -
67                                          // freshening replaces all lifetimes with `ReErased`,
68                                          // which is different from how types/const are freshened.
69                                          | TypeFlags::HAS_TY_FRESH.bits()
70                                          | TypeFlags::HAS_CT_FRESH.bits()
71                                          | TypeFlags::HAS_FREE_LOCAL_REGIONS.bits()
72                                          | TypeFlags::HAS_RE_ERASED.bits();
73
74        /// Does this have `Projection`?
75        const HAS_TY_PROJECTION           = 1 << 10;
76        /// Does this have `Free` aliases?
77        const HAS_TY_FREE_ALIAS                 = 1 << 11;
78        /// Does this have `Opaque`?
79        const HAS_TY_OPAQUE               = 1 << 12;
80        /// Does this have `Inherent`?
81        const HAS_TY_INHERENT             = 1 << 13;
82        /// Does this have `ConstKind::Unevaluated`?
83        const HAS_CT_PROJECTION           = 1 << 14;
84
85        /// Does this have `Alias` or `ConstKind::Unevaluated`?
86        ///
87        /// Rephrased, could this term be normalized further?
88        const HAS_ALIAS                   = TypeFlags::HAS_TY_PROJECTION.bits()
89                                          | TypeFlags::HAS_TY_FREE_ALIAS.bits()
90                                          | TypeFlags::HAS_TY_OPAQUE.bits()
91                                          | TypeFlags::HAS_TY_INHERENT.bits()
92                                          | TypeFlags::HAS_CT_PROJECTION.bits();
93
94        /// Is an error type/lifetime/const reachable?
95        const HAS_ERROR                   = 1 << 15;
96
97        /// Does this have any region that "appears free" in the type?
98        /// Basically anything but `ReBound` and `ReErased`.
99        const HAS_FREE_REGIONS            = 1 << 16;
100
101        /// Does this have any `ReBound` regions?
102        const HAS_RE_BOUND                = 1 << 17;
103        /// Does this have any `Bound` types?
104        const HAS_TY_BOUND                = 1 << 18;
105        /// Does this have any `ConstKind::Bound` consts?
106        const HAS_CT_BOUND                = 1 << 19;
107        /// Does this have any bound variables?
108        /// Used to check if a global bound is safe to evaluate.
109        const HAS_BOUND_VARS              = TypeFlags::HAS_RE_BOUND.bits()
110                                          | TypeFlags::HAS_TY_BOUND.bits()
111                                          | TypeFlags::HAS_CT_BOUND.bits();
112
113        /// Does this have any `ReErased` regions?
114        const HAS_RE_ERASED               = 1 << 20;
115
116        /// Does this value have parameters/placeholders/inference variables which could be
117        /// replaced later, in a way that would change the results of `impl` specialization?
118        const STILL_FURTHER_SPECIALIZABLE = TypeFlags::HAS_TY_PARAM.bits()
119                                          | TypeFlags::HAS_TY_PLACEHOLDER.bits()
120                                          | TypeFlags::HAS_TY_INFER.bits()
121                                          | TypeFlags::HAS_CT_PARAM.bits()
122                                          | TypeFlags::HAS_CT_PLACEHOLDER.bits()
123                                          | TypeFlags::HAS_CT_INFER.bits();
124
125        /// Does this value have `InferTy::FreshTy/FreshIntTy/FreshFloatTy`?
126        const HAS_TY_FRESH                = 1 << 21;
127
128        /// Does this value have `InferConst::Fresh`?
129        const HAS_CT_FRESH                = 1 << 22;
130
131        /// Does this have any binders with bound vars (e.g. that need to be anonymized)?
132        const HAS_BINDER_VARS             = 1 << 23;
133
134        /// Does this type have any coroutines in it?
135        const HAS_TY_CORO                 = 1 << 24;
136    }
137}
138
139#[derive(Debug)]
140pub struct FlagComputation<I> {
141    pub flags: TypeFlags,
142
143    /// see `Ty::outer_exclusive_binder` for details
144    pub outer_exclusive_binder: ty::DebruijnIndex,
145
146    interner: std::marker::PhantomData<I>,
147}
148
149impl<I: Interner> FlagComputation<I> {
150    fn new() -> FlagComputation<I> {
151        FlagComputation {
152            flags: TypeFlags::empty(),
153            outer_exclusive_binder: ty::INNERMOST,
154            interner: std::marker::PhantomData,
155        }
156    }
157
158    #[allow(rustc::usage_of_ty_tykind)]
159    pub fn for_kind(kind: &ty::TyKind<I>) -> FlagComputation<I> {
160        let mut result = FlagComputation::new();
161        result.add_kind(kind);
162        result
163    }
164
165    pub fn for_predicate(binder: ty::Binder<I, ty::PredicateKind<I>>) -> FlagComputation<I> {
166        let mut result = FlagComputation::new();
167        result.add_predicate(binder);
168        result
169    }
170
171    pub fn for_const_kind(kind: &ty::ConstKind<I>) -> FlagComputation<I> {
172        let mut result = FlagComputation::new();
173        result.add_const_kind(kind);
174        result
175    }
176
177    pub fn for_clauses(clauses: &[I::Clause]) -> FlagComputation<I> {
178        let mut result = FlagComputation::new();
179        for c in clauses {
180            result.add_flags(c.as_predicate().flags());
181            result.add_exclusive_binder(c.as_predicate().outer_exclusive_binder());
182        }
183        result
184    }
185
186    fn add_flags(&mut self, flags: TypeFlags) {
187        self.flags = self.flags | flags;
188    }
189
190    /// indicates that `self` refers to something at binding level `binder`
191    fn add_bound_var(&mut self, binder: ty::DebruijnIndex) {
192        let exclusive_binder = binder.shifted_in(1);
193        self.add_exclusive_binder(exclusive_binder);
194    }
195
196    /// indicates that `self` refers to something *inside* binding
197    /// level `binder` -- not bound by `binder`, but bound by the next
198    /// binder internal to it
199    fn add_exclusive_binder(&mut self, exclusive_binder: ty::DebruijnIndex) {
200        self.outer_exclusive_binder = self.outer_exclusive_binder.max(exclusive_binder);
201    }
202
203    /// Adds the flags/depth from a set of types that appear within the current type, but within a
204    /// region binder.
205    fn bound_computation<T, F>(&mut self, value: ty::Binder<I, T>, f: F)
206    where
207        F: FnOnce(&mut Self, T),
208    {
209        let mut computation = FlagComputation::new();
210
211        if !value.bound_vars().is_empty() {
212            computation.add_flags(TypeFlags::HAS_BINDER_VARS);
213        }
214
215        f(&mut computation, value.skip_binder());
216
217        self.add_flags(computation.flags);
218
219        // The types that contributed to `computation` occurred within
220        // a region binder, so subtract one from the region depth
221        // within when adding the depth to `self`.
222        let outer_exclusive_binder = computation.outer_exclusive_binder;
223        if outer_exclusive_binder > ty::INNERMOST {
224            self.add_exclusive_binder(outer_exclusive_binder.shifted_out(1));
225        } // otherwise, this binder captures nothing
226    }
227
228    #[allow(rustc::usage_of_ty_tykind)]
229    fn add_kind(&mut self, kind: &ty::TyKind<I>) {
230        match *kind {
231            ty::Bool
232            | ty::Char
233            | ty::Int(_)
234            | ty::Float(_)
235            | ty::Uint(_)
236            | ty::Never
237            | ty::Str
238            | ty::Foreign(..) => {}
239
240            ty::Error(_) => self.add_flags(TypeFlags::HAS_ERROR),
241
242            ty::Param(_) => {
243                self.add_flags(TypeFlags::HAS_TY_PARAM);
244            }
245
246            ty::Closure(_, args)
247            | ty::CoroutineClosure(_, args)
248            | ty::CoroutineWitness(_, args) => {
249                self.add_args(args.as_slice());
250            }
251
252            ty::Coroutine(_, args) => {
253                self.add_flags(TypeFlags::HAS_TY_CORO);
254                self.add_args(args.as_slice());
255            }
256
257            ty::Bound(debruijn, _) => {
258                self.add_bound_var(debruijn);
259                self.add_flags(TypeFlags::HAS_TY_BOUND);
260            }
261
262            ty::Placeholder(..) => {
263                self.add_flags(TypeFlags::HAS_TY_PLACEHOLDER);
264            }
265
266            ty::Infer(infer) => match infer {
267                ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => {
268                    self.add_flags(TypeFlags::HAS_TY_FRESH)
269                }
270
271                ty::TyVar(_) | ty::IntVar(_) | ty::FloatVar(_) => {
272                    self.add_flags(TypeFlags::HAS_TY_INFER)
273                }
274            },
275
276            ty::Adt(_, args) => {
277                self.add_args(args.as_slice());
278            }
279
280            ty::Alias(kind, data) => {
281                self.add_flags(match kind {
282                    ty::Projection => TypeFlags::HAS_TY_PROJECTION,
283                    ty::Free => TypeFlags::HAS_TY_FREE_ALIAS,
284                    ty::Opaque => TypeFlags::HAS_TY_OPAQUE,
285                    ty::Inherent => TypeFlags::HAS_TY_INHERENT,
286                });
287
288                self.add_alias_ty(data);
289            }
290
291            ty::Dynamic(obj, r, _) => {
292                for predicate in obj.iter() {
293                    self.bound_computation(predicate, |computation, predicate| match predicate {
294                        ty::ExistentialPredicate::Trait(tr) => {
295                            computation.add_args(tr.args.as_slice())
296                        }
297                        ty::ExistentialPredicate::Projection(p) => {
298                            computation.add_existential_projection(&p);
299                        }
300                        ty::ExistentialPredicate::AutoTrait(_) => {}
301                    });
302                }
303
304                self.add_region(r);
305            }
306
307            ty::Array(tt, len) => {
308                self.add_ty(tt);
309                self.add_const(len);
310            }
311
312            ty::Pat(ty, pat) => {
313                self.add_ty(ty);
314                self.add_ty_pat(pat);
315            }
316
317            ty::Slice(tt) => self.add_ty(tt),
318
319            ty::RawPtr(ty, _) => {
320                self.add_ty(ty);
321            }
322
323            ty::Ref(r, ty, _) => {
324                self.add_region(r);
325                self.add_ty(ty);
326            }
327
328            ty::Tuple(types) => {
329                self.add_tys(types);
330            }
331
332            ty::FnDef(_, args) => {
333                self.add_args(args.as_slice());
334            }
335
336            ty::FnPtr(sig_tys, _) => self.bound_computation(sig_tys, |computation, sig_tys| {
337                computation.add_tys(sig_tys.inputs_and_output);
338            }),
339
340            ty::UnsafeBinder(bound_ty) => {
341                self.bound_computation(bound_ty.into(), |computation, ty| {
342                    computation.add_ty(ty);
343                })
344            }
345        }
346    }
347
348    fn add_ty_pat(&mut self, pat: <I as Interner>::Pat) {
349        self.add_flags(pat.flags());
350    }
351
352    fn add_predicate(&mut self, binder: ty::Binder<I, ty::PredicateKind<I>>) {
353        self.bound_computation(binder, |computation, atom| computation.add_predicate_atom(atom));
354    }
355
356    fn add_predicate_atom(&mut self, atom: ty::PredicateKind<I>) {
357        match atom {
358            ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)) => {
359                self.add_args(trait_pred.trait_ref.args.as_slice());
360            }
361            ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(ty::HostEffectPredicate {
362                trait_ref,
363                constness: _,
364            })) => {
365                self.add_args(trait_ref.args.as_slice());
366            }
367            ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(
368                a,
369                b,
370            ))) => {
371                self.add_region(a);
372                self.add_region(b);
373            }
374            ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(
375                ty,
376                region,
377            ))) => {
378                self.add_ty(ty);
379                self.add_region(region);
380            }
381            ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct, ty)) => {
382                self.add_const(ct);
383                self.add_ty(ty);
384            }
385            ty::PredicateKind::Subtype(ty::SubtypePredicate { a_is_expected: _, a, b }) => {
386                self.add_ty(a);
387                self.add_ty(b);
388            }
389            ty::PredicateKind::Coerce(ty::CoercePredicate { a, b }) => {
390                self.add_ty(a);
391                self.add_ty(b);
392            }
393            ty::PredicateKind::Clause(ty::ClauseKind::Projection(ty::ProjectionPredicate {
394                projection_term,
395                term,
396            })) => {
397                self.add_alias_term(projection_term);
398                self.add_term(term);
399            }
400            ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(term)) => {
401                self.add_term(term);
402            }
403            ty::PredicateKind::DynCompatible(_def_id) => {}
404            ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(uv)) => {
405                self.add_const(uv);
406            }
407            ty::PredicateKind::ConstEquate(expected, found) => {
408                self.add_const(expected);
409                self.add_const(found);
410            }
411            ty::PredicateKind::NormalizesTo(ty::NormalizesTo { alias, term }) => {
412                self.add_alias_term(alias);
413                self.add_term(term);
414            }
415            ty::PredicateKind::AliasRelate(t1, t2, _) => {
416                self.add_term(t1);
417                self.add_term(t2);
418            }
419            ty::PredicateKind::Clause(ty::ClauseKind::UnstableFeature(_sym)) => {}
420            ty::PredicateKind::Ambiguous => {}
421        }
422    }
423
424    fn add_ty(&mut self, ty: I::Ty) {
425        self.add_flags(ty.flags());
426        self.add_exclusive_binder(ty.outer_exclusive_binder());
427    }
428
429    fn add_tys(&mut self, tys: I::Tys) {
430        for ty in tys.iter() {
431            self.add_ty(ty);
432        }
433    }
434
435    fn add_region(&mut self, r: I::Region) {
436        self.add_flags(r.flags());
437        if let ty::ReBound(debruijn, _) = r.kind() {
438            self.add_bound_var(debruijn);
439        }
440    }
441
442    fn add_const(&mut self, c: I::Const) {
443        self.add_flags(c.flags());
444        self.add_exclusive_binder(c.outer_exclusive_binder());
445    }
446
447    fn add_const_kind(&mut self, c: &ty::ConstKind<I>) {
448        match *c {
449            ty::ConstKind::Unevaluated(uv) => {
450                self.add_args(uv.args.as_slice());
451                self.add_flags(TypeFlags::HAS_CT_PROJECTION);
452            }
453            ty::ConstKind::Infer(infer) => match infer {
454                ty::InferConst::Fresh(_) => self.add_flags(TypeFlags::HAS_CT_FRESH),
455                ty::InferConst::Var(_) => self.add_flags(TypeFlags::HAS_CT_INFER),
456            },
457            ty::ConstKind::Bound(debruijn, _) => {
458                self.add_bound_var(debruijn);
459                self.add_flags(TypeFlags::HAS_CT_BOUND);
460            }
461            ty::ConstKind::Param(_) => {
462                self.add_flags(TypeFlags::HAS_CT_PARAM);
463            }
464            ty::ConstKind::Placeholder(_) => {
465                self.add_flags(TypeFlags::HAS_CT_PLACEHOLDER);
466            }
467            ty::ConstKind::Value(cv) => self.add_ty(cv.ty()),
468            ty::ConstKind::Expr(e) => self.add_args(e.args().as_slice()),
469            ty::ConstKind::Error(_) => self.add_flags(TypeFlags::HAS_ERROR),
470        }
471    }
472
473    fn add_existential_projection(&mut self, projection: &ty::ExistentialProjection<I>) {
474        self.add_args(projection.args.as_slice());
475        match projection.term.kind() {
476            ty::TermKind::Ty(ty) => self.add_ty(ty),
477            ty::TermKind::Const(ct) => self.add_const(ct),
478        }
479    }
480
481    fn add_alias_ty(&mut self, alias_ty: ty::AliasTy<I>) {
482        self.add_args(alias_ty.args.as_slice());
483    }
484
485    fn add_alias_term(&mut self, alias_term: ty::AliasTerm<I>) {
486        self.add_args(alias_term.args.as_slice());
487    }
488
489    fn add_args(&mut self, args: &[I::GenericArg]) {
490        for arg in args {
491            match arg.kind() {
492                ty::GenericArgKind::Type(ty) => self.add_ty(ty),
493                ty::GenericArgKind::Lifetime(lt) => self.add_region(lt),
494                ty::GenericArgKind::Const(ct) => self.add_const(ct),
495            }
496        }
497    }
498
499    fn add_term(&mut self, term: I::Term) {
500        match term.kind() {
501            ty::TermKind::Ty(ty) => self.add_ty(ty),
502            ty::TermKind::Const(ct) => self.add_const(ct),
503        }
504    }
505}