Skip to main content

tvm_tirx/sym/
constraint.rs

1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements.  See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership.  The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License.  You may obtain a copy of the License at
9 *
10 *   http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied.  See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19// The generated `new` of a field-less base needs no `Default`.
20#![allow(clippy::new_without_default)]
21
22//! Constraints. A [`Constraint`] is one fact in scope, a [`BindingConstraint`],
23//! [`RangeConstraint`] or [`PredicateConstraint`]; a [`ConstraintContext`] holds the facts in
24//! scope at a point of a traversal, which an [`Analyzer`](super::Analyzer) proves under.
25
26// tvm-ffi-stubgen(file): mod(missing_docs = allow)
27// `no_new` generates no allocator for the abstract base: a value is one of its subtypes.
28// tvm-ffi-stubgen(object): sym.Constraint(no_new)
29// tvm-ffi-stubgen(object): sym.ConstraintContext(ty_map = crate::sym::constraint::ConstraintContext)
30
31use std::cell::UnsafeCell;
32use std::mem::{align_of, offset_of, size_of};
33use tvm_ffi::{AnyView, Array, Error, Result, VALUE_ERROR};
34// tvm-ffi-stubgen(import): crate::ir::expr::PrimExpr
35// tvm-ffi-stubgen(import): tvm_ffi::IntoArg
36// tvm-ffi-stubgen(import): std::borrow::Borrow
37// A binding's value and a predicate are `PrimExpr`s, as in C++.
38// tvm-ffi-stubgen(field): sym.BindingConstraint.value(type = PrimExpr)
39// tvm-ffi-stubgen(field): sym.PredicateConstraint.condition(type = PrimExpr)
40// tvm-ffi-stubgen(begin): import-section
41use crate::ir::expr::PrimExpr;
42use crate::ir::expr::Range;
43use crate::ir::expr::Var;
44use std::borrow::Borrow;
45use std::ops::Deref;
46use tvm_ffi::IntoArg;
47use tvm_ffi::Object;
48use tvm_ffi::ObjectArc;
49// tvm-ffi-stubgen(end)
50
51/// The base of every fact a [`ConstraintContext`] holds; it owns no analyzer state.
52// tvm-ffi-stubgen(begin): object/sym.Constraint
53#[allow(missing_docs)]
54#[repr(C)]
55#[derive(tvm_ffi::derive::ObjectRef, Clone)]
56pub struct Constraint {
57    data_: ObjectArc<ConstraintObj>,
58}
59
60/// The object behind [`Constraint`].
61// Complete: reflected fields fill [24, 24) exactly.
62#[allow(missing_docs)]
63#[repr(C)]
64#[derive(tvm_ffi::derive::Object)]
65#[object(type_key = "sym.Constraint", immutable, rs_parent)]
66pub struct ConstraintObj {
67    base_: Object,
68}
69
70const _: () = {
71    assert!(::core::mem::size_of::<ConstraintObj>() == 24);
72    assert!(::core::mem::align_of::<ConstraintObj>() == 8);
73};
74
75#[allow(missing_docs)]
76impl ConstraintObj {
77    pub fn new() -> Self {
78        let base_ = Object::new();
79        Self { base_ }
80    }
81}
82// tvm-ffi-stubgen(end)
83
84/// The binding of `var` to `value`. The value is the bound expression as written, memory reads
85/// included: it records what `var` was bound to, not an equality that holds afterwards.
86// tvm-ffi-stubgen(begin): object/sym.BindingConstraint
87#[allow(missing_docs)]
88#[repr(C)]
89#[derive(tvm_ffi::derive::ObjectRef, Clone)]
90pub struct BindingConstraint {
91    data_: ObjectArc<BindingConstraintObj>,
92}
93
94/// The object behind [`BindingConstraint`].
95// Complete: reflected fields fill [24, 40) exactly.
96#[allow(missing_docs)]
97#[repr(C)]
98#[derive(tvm_ffi::derive::Object)]
99#[object(type_key = "sym.BindingConstraint", final, immutable)]
100pub struct BindingConstraintObj {
101    base_: ConstraintObj,
102    pub var: Var,
103    pub value: PrimExpr,
104}
105
106const _: () = {
107    assert!(::core::mem::size_of::<BindingConstraintObj>() == 40);
108    assert!(::core::mem::align_of::<BindingConstraintObj>() == 8);
109};
110
111impl Deref for BindingConstraintObj {
112    type Target = ConstraintObj;
113    fn deref(&self) -> &ConstraintObj {
114        &self.base_
115    }
116}
117
118#[allow(missing_docs)]
119impl BindingConstraintObj {
120    pub(crate) fn new(var: Var, value: PrimExpr) -> Self {
121        let base_ = ConstraintObj::new();
122        Self { base_, var, value }
123    }
124}
125
126#[allow(missing_docs)]
127impl BindingConstraint {
128    /// Create a `BindingConstraint` from its field values.
129    pub fn new(var: impl IntoArg<Var>, value: impl IntoArg<PrimExpr>) -> Self {
130        let obj = BindingConstraintObj::new(var.into_owned(), value.into_owned());
131        Self { data_: ObjectArc::new(obj) }
132    }
133}
134
135tvm_ffi::impl_object_ref_upcast!(BindingConstraint => Constraint);
136// tvm-ffi-stubgen(end)
137
138/// The fact that the boolean `condition` holds. With `assume_always`, the caller guarantees it
139/// holds throughout the scope, even after the values it reads change.
140// tvm-ffi-stubgen(begin): object/sym.PredicateConstraint
141#[allow(missing_docs)]
142#[repr(C)]
143#[derive(tvm_ffi::derive::ObjectRef, Clone)]
144pub struct PredicateConstraint {
145    data_: ObjectArc<PredicateConstraintObj>,
146}
147
148/// The object behind [`PredicateConstraint`].
149// Complete: reflected fields fill [24, 40) exactly (alignment padding [33, 40)).
150#[allow(missing_docs)]
151#[repr(C)]
152#[derive(tvm_ffi::derive::Object)]
153#[object(type_key = "sym.PredicateConstraint", final, immutable)]
154pub struct PredicateConstraintObj {
155    base_: ConstraintObj,
156    pub condition: PrimExpr,
157    pub assume_always: bool,
158}
159
160const _: () = {
161    assert!(::core::mem::size_of::<PredicateConstraintObj>() == 40);
162    assert!(::core::mem::align_of::<PredicateConstraintObj>() == 8);
163};
164
165impl Deref for PredicateConstraintObj {
166    type Target = ConstraintObj;
167    fn deref(&self) -> &ConstraintObj {
168        &self.base_
169    }
170}
171
172#[allow(missing_docs)]
173impl PredicateConstraintObj {
174    pub(crate) fn new(condition: PrimExpr, assume_always: bool) -> Self {
175        let base_ = ConstraintObj::new();
176        Self { base_, condition, assume_always }
177    }
178}
179
180#[allow(missing_docs)]
181impl PredicateConstraint {
182    /// Create a `PredicateConstraint` from its field values.
183    pub fn new(condition: impl IntoArg<PrimExpr>, assume_always: bool) -> Self {
184        let obj = PredicateConstraintObj::new(condition.into_owned(), assume_always);
185        Self { data_: ObjectArc::new(obj) }
186    }
187}
188
189tvm_ffi::impl_object_ref_upcast!(PredicateConstraint => Constraint);
190// tvm-ffi-stubgen(end)
191
192/// The fact that `var` lies in the half-open `range`, which may be wider than the values `var`
193/// takes.
194// tvm-ffi-stubgen(begin): object/sym.RangeConstraint
195#[allow(missing_docs)]
196#[repr(C)]
197#[derive(tvm_ffi::derive::ObjectRef, Clone)]
198pub struct RangeConstraint {
199    data_: ObjectArc<RangeConstraintObj>,
200}
201
202/// The object behind [`RangeConstraint`].
203// Complete: reflected fields fill [24, 40) exactly.
204#[allow(missing_docs)]
205#[repr(C)]
206#[derive(tvm_ffi::derive::Object)]
207#[object(type_key = "sym.RangeConstraint", final, immutable)]
208pub struct RangeConstraintObj {
209    base_: ConstraintObj,
210    pub var: Var,
211    pub range: Range,
212}
213
214const _: () = {
215    assert!(::core::mem::size_of::<RangeConstraintObj>() == 40);
216    assert!(::core::mem::align_of::<RangeConstraintObj>() == 8);
217};
218
219impl Deref for RangeConstraintObj {
220    type Target = ConstraintObj;
221    fn deref(&self) -> &ConstraintObj {
222        &self.base_
223    }
224}
225
226#[allow(missing_docs)]
227impl RangeConstraintObj {
228    pub(crate) fn new(var: Var, range: Range) -> Self {
229        let base_ = ConstraintObj::new();
230        Self { base_, var, range }
231    }
232}
233
234#[allow(missing_docs)]
235impl RangeConstraint {
236    /// Create a `RangeConstraint` from its field values.
237    pub fn new(var: impl IntoArg<Var>, range: impl IntoArg<Range>) -> Self {
238        let obj = RangeConstraintObj::new(var.into_owned(), range.into_owned());
239        Self { data_: ObjectArc::new(obj) }
240    }
241}
242
243tvm_ffi::impl_object_ref_upcast!(RangeConstraint => Constraint);
244// tvm-ffi-stubgen(end)
245
246/// The object of a [`ConstraintContext`], with the layout of the native one and a stable identity.
247///
248/// Only the local array changes after construction. Its handle is replaced by native append, so
249/// shared context inspection must use interior mutability. Parent links and their captured local
250/// prefix are immutable and acyclic.
251#[repr(C)]
252#[derive(tvm_ffi::derive::Object)]
253#[object(type_key = "sym.ConstraintContext", final)]
254pub struct ConstraintContextObj {
255    base_: Object,
256    parent: Option<ObjectArc<ConstraintContextObj>>,
257    parent_prefix_size: i64,
258    constraints: UnsafeCell<Array<Constraint>>,
259}
260
261// These verify the Rust mirror against the matching x86_64 header layout, not
262// an arbitrary loaded binary's hidden fields. Stub generation cannot certify them.
263const _: () = {
264    assert!(size_of::<ConstraintContextObj>() == 48);
265    assert!(align_of::<ConstraintContextObj>() == 8);
266    assert!(offset_of!(ConstraintContextObj, parent) == 24);
267    assert!(offset_of!(ConstraintContextObj, parent_prefix_size) == 32);
268    assert!(offset_of!(ConstraintContextObj, constraints) == 40);
269};
270
271/// A context of constraints: the premises in effect at a point of a traversal, ancestors' first.
272///
273/// Clones share the context's identity and later appends; use
274/// [`snapshot`](ConstraintContextObj::snapshot) to capture the current prefix. A context is neither
275/// `Send` nor `Sync`: do not share one across threads, also not through an erased `ObjectRef`.
276///
277/// # Examples
278///
279/// ```
280/// use tvm_tirx::ir::prim::op::{ge, lt};
281/// use tvm_tirx::ir::{PrimType, PrimVar, Var, UNKNOWN_LOC};
282/// use tvm_tirx::sym::{Analyzer, ConstraintContext, PredicateConstraint, ProofStrength};
283///
284/// let x = PrimVar::new("x", PrimType::int(32), UNKNOWN_LOC);
285/// let outer = ConstraintContext::new();
286/// outer.append(PredicateConstraint::new(ge(&x, 0)?, false))?;
287/// let inner = outer.snapshot();
288/// inner.append(PredicateConstraint::new(lt(&x, 16)?, false))?;
289///
290/// let analyzer = Analyzer::new();
291/// analyzer.sync_constraint_context(&inner)?;
292/// assert!(analyzer.can_prove(lt(&x, 16)?, ProofStrength::Default)?);
293/// analyzer.sync_constraint_context(&outer)?;
294/// assert!(!analyzer.can_prove(lt(&x, 16)?, ProofStrength::Default)?);
295/// # Ok::<(), tvm_tirx::tvm_ffi::Error>(())
296/// ```
297#[repr(C)]
298#[derive(tvm_ffi::derive::ObjectRef, Clone)]
299pub struct ConstraintContext {
300    data_: ObjectArc<ConstraintContextObj>,
301}
302
303impl ConstraintContextObj {
304    /// Append `constraint` to the local entries (`sym.ConstraintContextAppend`).
305    ///
306    /// Do not append to the active context of a running native visitor.
307    pub fn append(&self, constraint: impl IntoArg<Constraint>) -> Result<()> {
308        tvm_ffi::cached_global_func!("sym.ConstraintContextAppend")
309            .call_packed(&[AnyView::from(self), AnyView::from(constraint.into_arg().borrow())])?;
310        Ok(())
311    }
312
313    /// Return the number of local entries, excluding captured ancestors.
314    pub fn local_size(&self) -> i64 {
315        // SAFETY: nothing can append during this short borrow.
316        unsafe { (&*self.constraints.get()).len() as i64 }
317    }
318
319    /// Capture the visible prefix in an independently extensible child.
320    pub fn snapshot(&self) -> ConstraintContext {
321        let parent = ConstraintContext::try_from(AnyView::from(self))
322            .expect("context has its registered native type");
323        ConstraintContext::allocate(Some(parent.data_), self.local_size())
324    }
325
326    fn local_array(&self) -> Array<Constraint> {
327        // SAFETY: the borrow ends with this clone, before any callback can append; an append then
328        // copies the array on write.
329        unsafe { (&*self.constraints.get()).clone() }
330    }
331
332    /// Call `callback` on each visible constraint, in inherited and then local order.
333    ///
334    /// The callback may append without entering this iteration; each borrowed constraint is valid
335    /// only during its callback.
336    pub fn for_each(&self, mut callback: impl FnMut(&Constraint)) {
337        let retained = ConstraintContext::try_from(AnyView::from(self))
338            .expect("context has its registered native type");
339        retained.for_each_prefix(retained.local_size(), &mut callback);
340    }
341
342    fn for_each_prefix(&self, prefix: i64, callback: &mut impl FnMut(&Constraint)) {
343        let local = self.local_array();
344        if let Some(parent) = &self.parent {
345            parent.for_each_prefix(self.parent_prefix_size, callback);
346        }
347        for constraint in local.iter().take(prefix as usize) {
348            callback(constraint);
349        }
350    }
351
352    /// Return the visible constraints in inherited and then local order, as an independent array.
353    ///
354    /// Later appends do not change it; constraint nodes and expressions remain shared.
355    pub fn to_array(&self) -> Array<Constraint> {
356        if self.parent.is_none() {
357            return self.local_array();
358        }
359        let mut facts = Vec::new();
360        self.for_each(|fact| facts.push(fact.clone()));
361        Array::from_vec(facts)
362    }
363}
364
365impl ConstraintContext {
366    /// Create an empty root context, with the complete native-compatible layout.
367    pub fn new() -> Self {
368        Self::allocate(None, 0)
369    }
370
371    /// Create an empty child that captures the first `parent_prefix_size` local entries of
372    /// `parent`.
373    ///
374    /// Earlier ancestor prefixes are inherited unchanged; later appends to the parent are excluded.
375    ///
376    /// # Errors
377    ///
378    /// Returns an error if `parent_prefix_size` is negative or larger than the parent's local size.
379    pub fn with_parent_prefix_size(
380        parent: impl IntoArg<ConstraintContext>,
381        parent_prefix_size: i64,
382    ) -> Result<Self> {
383        let parent = parent.into_owned();
384        if parent_prefix_size < 0 || parent_prefix_size > parent.local_size() {
385            return Err(Error::new(
386                VALUE_ERROR,
387                "Constraint context parent local prefix is out of bounds",
388            ));
389        }
390        Ok(Self::allocate(Some(parent.data_), parent_prefix_size))
391    }
392
393    fn allocate(parent: Option<ObjectArc<ConstraintContextObj>>, prefix: i64) -> Self {
394        Self {
395            data_: ObjectArc::new(ConstraintContextObj {
396                base_: Object::new(),
397                parent,
398                parent_prefix_size: prefix,
399                // Start with an empty Rust array. Native Append owns all growth;
400                // never install a nonempty Rust allocation in this mutable field.
401                constraints: UnsafeCell::new(Array::default()),
402            }),
403        }
404    }
405}