Files
Tianqi Chen 275114b327 [REFACTOR][IR] Unify PrimExpr with Expr typed view (#19910)
## Summary
- Make `PrimExpr` a typed C++ view over `Expr` values whose
`ExprNode::ty` is `PrimType`, instead of using a separate runtime node
class as the proof of primitive-ness.
- Use the shared `ir::Call` node for Relax, TIRX, and primitive-valued
calls, while keeping primitive-only APIs explicit at their semantic
boundaries.
- Keep Python on the general `Expr` surface for primitive-typed values
so `isinstance` behavior does not imply a nominal primitive-expression
subclass.

## Design Rationale
The main advantage of this change is that common expression nodes such
as `Call` can be unified without specializing each one to `PrimType`. A
single `ir::Call` can represent a Relax tensor call, a Relax scalar
call, or a primitive-valued intrinsic call; the result type stored in
`ExprNode::ty` determines whether that particular value can be viewed as
`PrimExpr`.

This keeps the IR node hierarchy focused on expression structure rather
than result-type categories. Nodes that are intrinsically primitive,
such as integer and floating-point literals or TIRX primitive operators,
still have strongly typed C++ APIs and data structures. General nodes
whose result type may vary, such as `Call`, remain general `Expr` nodes
and are narrowed to `PrimExpr` only where primitive-only semantics are
required.

The PR also keeps the compatibility surface practical: C++
primitive-only APIs continue to accept `PrimExpr`, Python exposes a
compatibility predicate for checking the primitive typed category, and
visitors/printers use one natural `Call` path rather than duplicating
Relax and primitive call handling. Missing expression types are
represented explicitly with `Type::Missing()` so constructors can leave
type inference to later analysis without relying on nullable `Type`
values.
2026-07-01 18:55:33 -04:00

161 lines
4.4 KiB
Python

# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Wrapping existing analysis utils."""
# pylint: disable=invalid-name
from tvm.ir import IRModule
from tvm.tirx.expr import Var
from tvm.tirx.stmt import Expr
from .. import Stmt
from ..function import PrimFunc
from . import _ffi_api
def expr_deep_equal(lhs: Expr, rhs: Expr) -> bool:
"""Deeply compare two nested expressions.
Parameters
----------
lhs : Expr
The left operand.
rhs : Expr
The right operand.
Returns
-------
result : bool
The comparison result
Note
----
This function does not remap variable bindings, it will not
return true for (let x = 1 in x + 1) vs (let y = 1 in y + 1), unless x.same_as(y).
Use py:func:`tvm_ffi.structural_equal` to handle structural variable remapping.
Due to the restriction of not remapping variables, this function can run
faster than StructuralEqual and can be used as a utility function during arithmetic
simplifications.
Always consider py:func:`tvm_ffi.structural_equal` first, which handles
the structural remapping.
See Also
--------
tvm_ffi.structural_equal
"""
return _ffi_api.expr_deep_equal(lhs, rhs) # type: ignore
def verify_ssa(func: PrimFunc) -> bool:
"""Verify if the func is in SSA form.
Parameters
----------
func: tvm.tirx.PrimFunc
The module to be verified.
Returns
-------
result : bool
The result of verification.
"""
return _ffi_api.verify_ssa(func) # type: ignore
def verify_memory(func: PrimFunc) -> bool:
"""Verify if func contains illegal host side direct memory access.
Parameters
----------
func: tvm.tirx.PrimFunc
The module to be verified.
Returns
-------
result : bool
The result of verification.
"""
return _ffi_api.verify_memory(func) # type: ignore
def undefined_vars(node: Stmt | Expr, defs: list[Var] | None = None) -> list[Var]:
"""Find undefined vars in a TIR statement or expression.
Parameters
----------
node: Union[Stmt, Expr]
The TIR statement or expression to be checked.
defs: Optional[List[Var]]
The vars that is defined
Returns
-------
result : List[Var]
The undefined vars.
"""
defs = defs or []
return _ffi_api.UndefinedVars(node, defs) # type: ignore # pylint: disable=no-member
def verify_well_formed(obj: PrimFunc | IRModule, assert_mode: bool = True) -> bool:
"""Verify if the given TIR is well-formed. The verification includes:
- Check if expressions not contain vars that is defined outside the block.
Parameters
----------
obj: Union[tvm.tirx.PrimFunc, tvm.ir.IRModule]
The function or module to be verified.
assert_mode: bool
The indicator if it raises an error when the function is not well-formed.
Returns
-------
result: bool
Whether it is a well-formed TIR function.
"""
return _ffi_api.VerifyWellFormed(obj, assert_mode) # type: ignore # pylint: disable=no-member
def verify_tirx_well_formed(
obj: PrimFunc | IRModule, assert_mode: bool = True, device_func: bool = False
) -> bool:
"""Verify if the given TIRX is well-formed.
Parameters
----------
obj: Union[tvm.tirx.PrimFunc, tvm.ir.IRModule]
The function or module to be verified.
assert_mode: bool
The indicator if it raises an error when the function is not well-formed.
device_func: bool
The indicator if it is a device function.
Returns
-------
result: bool
Whether it is a well-formed TIRX function.
"""
return _ffi_api.VerifyTIRxWellFormed(obj, assert_mode, device_func) # type: ignore # pylint: disable=no-member