# Copyright (c) 2026 Huawei Technologies Co., Ltd.
# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
# CANN Open Software License Agreement Version 2.0 (the "License").
# Please refer to the License for details. You may not use this file except in compliance with the License.
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
# See LICENSE in the root of the software repository for the full text of the License.
# -----------------------------------------------------------------------------------------------------------

"""Python API declarations for the PyPTO Pro DSL (``pl.xxx``).

These declarations exist so that:
- IDE "Go to Definition" works for every ``pl.xxx`` call
- Python catches typos at import time (``pl.tensr`` raises ``AttributeError``)
- Type checkers can validate argument types
- Docstrings document the user-facing calling convention

None of these functions are meant to be called at runtime.  Inside a PyPTO
kernel the AST parser intercepts every ``pl.xxx`` call before Python executes
it.  Outside a kernel, calling a declaration raises ``RuntimeError``.

When adding a new op to the parser registry, add a
matching declaration here and re-export it from the package ``__init__.py``.
"""

from __future__ import annotations

import builtins
from contextlib import contextmanager
import functools
import inspect
from typing import Any, List, Optional, Sequence, Union

from pypto.ir import (
    AccPhase,
    AccToVecMode,
    AtomicType,
    FillPadMode,
    PipeType,
    QuantMode,
    ReluPreMode,
    RoundMode,
    SaturationFlagMode,
    STPhase,
    TLoadL2Hint,
    TStoreL2Hint,
)

from .._errors import InvalidOperation
from . import Layout, MemorySpace, TilePad
from .typing import Ptr

# ---------------------------------------------------------------------------
# User-facing type aliases (NOT IR types)
# ---------------------------------------------------------------------------
Tile = Any
TileGroup = Any
Tensor = Any
Scalar = Any
DType = Any
# Block offsets name one coordinate per axis and are therefore sequences.
Offset = Sequence[int]
Shape = Sequence[int]
Struct = Any  # a variable built by pl.struct(...)
Array = Any  # a fixed-length kernel-local array built by pl.array(...)

# ---------------------------------------------------------------------------
# API declaration decorator
# ---------------------------------------------------------------------------

_API_MSG = "This function is a DSL API declaration and must be used inside a PyPTO kernel"


def _api_decl(func):
    sig = inspect.signature(func)

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        sig.bind(*args, **kwargs)
        raise InvalidOperation(_API_MSG)

    wrapper.__wrapped__ = func
    # The parser gates DSL calls against this same binding, which is why it is
    # reachable without calling the declaration.
    wrapper.bind_declared = sig.bind
    return wrapper


# ===================================================================
# Section A: Data-movement block ops
# ===================================================================


@_api_decl
def load(
    dst_tile: Tile,
    src_tensor: Tensor,
    /,
    offsets: Offset,
    *,
    order: Optional[List[int]] = None,
    l2_cache_mode: Optional[TLoadL2Hint] = None,
) -> None:
    """Load data from GM Tensor into on-chip Tile by absolute element coordinates.

    Args:
        dst_tile: Destination Tile (L1 or UB only)
        src_tensor: Source Tensor (global memory, from kernel parameter)
        offsets: Element-level offset per axis, e.g. ``[row, col]`` or ``[b, n, sq, sk]``
        order: Optional, mapping of Tile dimensions to Tensor axes.
            Each element is an absolute axis index of the Tensor.
            Ascending order (e.g. ``[0, 1]``) loads without transposition;
            descending order (e.g. ``[1, 0]``) loads with transposition (DN layout).
            Default: last N axes ascending (N = Tile ndim), i.e. no transposition.

            **Merged rows (GM -> L1 only).** Naming 3 axes for a rank-2 Tile flattens the
            first two into the Tile's row axis, ``row = i_outer * inner + i_inner``, so a
            Tensor ``[B, S, N, G, D]`` can feed a matmul that wants (S, G) as one axis::

                pl.load(l1, x, [b, s0, h, 0, k0], order=[1, 3, 4])   # NZ  [S_tile*G, D_tile]
                pl.load(l1, x, [b, s0, h, 0, k0], order=[4, 3, 1])   # ZN  [D_tile, S_tile*G]

            Multi-ND nd2nz issues either form as matrices of ``inner`` rows, where ``inner``
            is the middle axis's extent. Static and dynamic inner extents support the same
            partial-matrix transfers; the merged Tile extent need not be a multiple of it.
            The middle axis offset must be a compile-time zero. Source and destination
            dtypes must match and use 8, 16 or 32-bit elements; the destination uses a
            512-byte fractal. The source column stride must be 1.
            Requires PTO-ISA multi-ND2NZ and multi-DN2ZN TLOAD with partial-matrix support.
            TLOAD uses a 3D descriptor with a bounded matrix extent. Source stride and static
            Tile shape limits follow the selected PTO-ISA implementation.
            Runtime valid shapes limit the transfer; a partial final matrix uses a separate DMA.
            The caller must keep runtime valid extents positive and within the declared Tile
            shape, with a valid source covering the requested transfer and a positive inner extent.
            The last axis must be the Tensor's innermost -- nd2nz reads each row as
            contiguous elements and has no column stride. The reversed spelling is the same
            transfer under the other label: an NZ ``[M, K]`` tile and a ZN ``[K, M]`` tile at
            one address are the same bytes, so it costs nothing and the Mat->L0 move delivers
            the transposed operand. Any other permutation of the three axes is rejected.
            Merged orders are currently unsupported for Vec (UB), load_tile and store.
            A UB reinterpret can reshape already packed data, but cannot gather separated GM regions.
        l2_cache_mode: Optional L2 cache hint for this GM read. ``None`` uses the PTO-ISA default
            ``TLoadL2Hint.NormalFirstVictim``. GM → UB supports ``NormalFirstVictim``,
            ``NormalLastVictim``, ``NormalPersistent``, ``NotAllocKeep``, ``NotAllocClean``, and
            ``NotAllocDrop``; GM → L1 Buffer supports ``NormalFirstVictim``, ``NormalLastVictim``,
            ``NormalPersistent``, and ``NotAllocKeep``.
    """


@_api_decl
def load_tile(
    dst_tile: Tile,
    src_tensor: Tensor,
    /,
    tile_offsets: Offset,
    *,
    order: Optional[List[int]] = None,
    l2_cache_mode: Optional[TLoadL2Hint] = None,
) -> None:
    """Load data from GM Tensor into on-chip Tile by tile-block index.

    Offsets are in tile-block units, internally multiplied by tile shape.
    E.g. with tile shape ``[64, 128]``, ``tile_offsets=[2, 2]`` equals
    ``load`` with absolute offsets ``[128, 256]``.

    Args:
        dst_tile: Destination Tile (L1 or UB only)
        src_tensor: Source Tensor (global memory)
        tile_offsets: Tile-block index, e.g. ``[tile_row, tile_col]``
        order: Optional, mapping of Tile dimensions to Tensor axes.
            Each element is an absolute axis index of the Tensor.
            Ascending order (e.g. ``[0, 1]``) loads without transposition;
            descending order (e.g. ``[1, 0]``) loads with transposition (DN layout).
            Default: last N axes ascending (N = Tile ndim), i.e. no transposition.
        l2_cache_mode: Optional L2 cache hint for this GM read. ``None`` uses the PTO-ISA default
            ``TLoadL2Hint.NormalFirstVictim``. GM → UB supports ``NormalFirstVictim``,
            ``NormalLastVictim``, ``NormalPersistent``, ``NotAllocKeep``, ``NotAllocClean``, and
            ``NotAllocDrop``; GM → L1 Buffer supports ``NormalFirstVictim``, ``NormalLastVictim``,
            ``NormalPersistent``, and ``NotAllocKeep``.
    """


@_api_decl
def store(
    dst_tensor: Tensor,
    src_tile: Tile,
    /,
    offsets: Offset,
    *,
    relu_pre_mode: Optional[ReluPreMode] = None,
    scale: Optional[Union[int, float, Tile]] = None,
    order: Optional[List[int]] = None,
    atomic: AtomicType = AtomicType.AtomicNone,
    phase: Optional[STPhase] = None,
    l2_cache_mode: Optional[TStoreL2Hint] = None,
) -> None:
    """Store on-chip Tile back to GM Tensor by absolute element coordinates.

    Args:
        dst_tensor: Destination Tensor (global memory)
        src_tile: Source Tile (on-chip buffer)
        offsets: Element-level offset per axis, e.g. ``[row, col]`` or ``[b, n, sq, sk]``
        relu_pre_mode: Optional ReLU fusion — ``pl.ReluPreMode.NormalRelu``
        scale: Optional fixpipe quantization scale.
            ``float`` or runtime scalar → per-tensor quantization (deqScalar path);
            a runtime **FP32** scalar is auto-reinterpreted as its IEEE-754 bit
            pattern (codegen bitcast), so pass the raw float value; a runtime
            **INT32/INT64** scalar must carry the pre-encoded float32 bit pattern
            (``struct.pack("!f", scale)``). Other runtime scalar dtypes
            (FP16/BF16/unsigned/narrower ints) are rejected at parse time.
            ``Tile`` (INT64, MemorySpace.Scaling, shape ``[1, N]``) → per-channel quantization with a
            **user-prepared deqTensor tile**; the framework reuses it directly (no auto-allocation,
            no sync insertion) — the user owns the data flow and must ensure the tile is ready
            (load → move → sync MTE1→FIX) before the store.
            Hardware requires ``[1, N]`` (row == 1, per-column), ``N % 16 == 0`` and ``N <= 512`` —
            ``[N, 1]`` per-row scaling is NOT supported.
            ``None`` → no fixpipe quantization.
            Quantization direction (quantize vs dequantize) is determined by ``dst_tensor`` dtype:
            INT8 → quantize; FP16 → dequantize (from INT32 L0C). Unsupported scale combos —
            UINT8 output, and FP32/INT32 → BF16 output — are rejected at parse time
            (hardware fixpipe has no unsigned requantization and only dequantizes INT32→FP16).
        order: Optional, which axes of the Tensor the Tile dimensions map to.
            When the Tensor has more dimensions than the Tile, this specifies the mapping.
            E.g. ``order=[0, 2]`` means Tile dim 0 → Tensor axis 0, Tile dim 1 → Tensor axis 2.
            Default: last N axes of the Tensor (N = Tile ndim)
        atomic: Atomic write mode — ``pl.AtomicType.AtomicNone`` (overwrite) or
            ``pl.AtomicType.AtomicAdd`` (atomic accumulate). ``AtomicAdd`` requires
            the destination Tensor dtype to be ``pl.DT_FP16``, ``pl.DT_FP32``,
            ``pl.DT_BF16``, ``pl.DT_INT8``, ``pl.DT_INT16``, or ``pl.DT_INT32``
        phase: Fixpipe drain phase — ``pl.STPhase.Partial`` or ``pl.STPhase.Final``
        l2_cache_mode: Optional L2 cache hint for this GM write. ``None`` uses the PTO-ISA default
            ``TStoreL2Hint.NormalFirstVictim``. UB → GM and L0C Buffer → GM support
            ``NormalFirstVictim``, ``NormalLastVictim``, ``NormalPersistent``, and ``NotAllocClean``.
    """


@_api_decl
def store_tile(
    dst_tensor: Tensor,
    src_tile: Tile,
    /,
    tile_offsets: Offset,
    *,
    relu_pre_mode: Optional[ReluPreMode] = None,
    scale: Optional[Union[int, float, Tile]] = None,
    order: Optional[List[int]] = None,
    atomic: AtomicType = AtomicType.AtomicNone,
    phase: Optional[STPhase] = None,
    l2_cache_mode: Optional[TStoreL2Hint] = None,
) -> None:
    """Store on-chip Tile back to GM Tensor by tile-block index.

    Args:
        dst_tensor: Destination Tensor (global memory)
        src_tile: Source Tile (on-chip buffer)
        tile_offsets: Tile-block index, e.g. ``[tile_row, tile_col]``;
            internally multiplied by tile shape to get element offsets
        relu_pre_mode: Optional ReLU fusion — ``pl.ReluPreMode.NormalRelu``
        scale: Optional fixpipe quantization scale.
            ``float`` or runtime scalar → per-tensor quantization (deqScalar path);
            a runtime **FP32** scalar is auto-reinterpreted as its IEEE-754 bit
            pattern (codegen bitcast), so pass the raw float value; a runtime
            **INT32/INT64** scalar must carry the pre-encoded float32 bit pattern
            (``struct.pack("!f", scale)``). Other runtime scalar dtypes
            (FP16/BF16/unsigned/narrower ints) are rejected at parse time.
            ``Tile`` (INT64, MemorySpace.Scaling, shape ``[1, N]``) → per-channel quantization with a
            **user-prepared deqTensor tile**; the framework reuses it directly (no auto-allocation,
            no sync insertion) — the user owns the data flow and must ensure the tile is ready
            (load → move → sync MTE1→FIX) before the store.
            Hardware requires ``[1, N]`` (row == 1, per-column), ``N % 16 == 0`` and ``N <= 512`` —
            ``[N, 1]`` per-row scaling is NOT supported.
            ``None`` → no fixpipe quantization.
        order: Optional, which axes of the Tensor the Tile dimensions map to.
            When the Tensor has more dimensions than the Tile, this specifies the mapping.
            E.g. ``order=[0, 2]`` means Tile dim 0 → Tensor axis 0, Tile dim 1 → Tensor axis 2.
            Default: last N axes of the Tensor (N = Tile ndim)
        atomic: Atomic write mode — ``pl.AtomicType.AtomicNone`` (overwrite) or
            ``pl.AtomicType.AtomicAdd`` (atomic accumulate). ``AtomicAdd`` requires
            the destination Tensor dtype to be ``pl.DT_FP16``, ``pl.DT_FP32``,
            ``pl.DT_BF16``, ``pl.DT_INT8``, ``pl.DT_INT16``, or ``pl.DT_INT32``
        phase: Fixpipe drain phase — ``pl.STPhase.Partial`` or ``pl.STPhase.Final``
        l2_cache_mode: Optional L2 cache hint for this GM write. ``None`` uses the PTO-ISA default
            ``TStoreL2Hint.NormalFirstVictim``. UB → GM and L0C Buffer → GM support
            ``NormalFirstVictim``, ``NormalLastVictim``, ``NormalPersistent``, and ``NotAllocClean``.
    """


@_api_decl
def init_output(
    tensor: Tensor,
    *,
    offset: int = 0,
    size: int,
    value: Union[int, float] = 0,
) -> None:
    """Initialize a region of a GM Tensor with a scalar value.

    The framework allocates a temporary UB buffer, fills it with *value*
    via the V pipeline (Duplicate), then copies it to GM via the MTE3
    pipeline (DataCopyPad).  V→MTE3 synchronization is inserted
    automatically.  Must be called before Tile buffer allocation
    (``make_tile_group`` etc.).

    The temporary UB tile starts at address 0 and occupies 8192 bytes for
    8/16/32-bit types, or 512 bytes for 64-bit types, regardless of ``size``.
    This op does not drain MTE3 before later UB reuse; synchronize MTE3 with
    the subsequent reader/writer pipe before reusing that byte range.

    This op never emits a cross-core barrier (``pipe_barrier`` would only
    drain the calling core's pipes).  When the initialized GM data is
    consumed by other cores or the cube sub-core (e.g. a subsequent
    ``pl.matmul``), the caller must explicitly call
    ``pl.system.sync_all(core_type=pl.SyncCoreType.MIX)`` on both sides
    (or an equivalent cross-core sync primitive) after this call.

    Args:
        tensor: Destination GM Tensor to initialize.
        offset: Element-level offset from the start of *tensor* (default 0).
        size: Number of elements to initialize.
        value: Fill value — int/float literal or ``pl.const()`` scalar;
            must be type-compatible with *tensor*'s dtype (default 0).
    """


@_api_decl
def move(
    dst_tile: Tile,
    src_tile: Tile,
    /,
    offset: Optional[Offset] = None,
    *,
    acc_to_vec_mode: Optional[AccToVecMode] = None,
    relu_pre_mode: Optional[ReluPreMode] = None,
    scale: Optional[Union[int, float, Tile]] = None,
    phase: Optional[STPhase] = None,
) -> None:
    """Move data between on-chip Tiles (tile↔tile, no GM access).

    Supported memory-space paths:

    ============ ============ ========
    src          dst          pipe
    ============ ============ ========
    Acc (L0C)    Vec (UB)     fix
    Acc (L0C)    Mat (L1)     fix
    Mat (L1)     Left (L0A)   mte1
    Mat (L1)     Right (L0B)  mte1
    Vec (UB)     Mat (L1)     mte3
    others       —            v
    ============ ============ ========

    Supported fusion (side operations):

    - ``acc_to_vec_mode``: Acc→Vec conversion mode (single/dual split M/N)
    - ``relu_pre_mode``: ReLU activation before destination
    - ``scale``: fixpipe quantization scale (per-tensor or per-channel)
    - ``phase``: FixPipe unit-flag phase for Acc→Vec or Acc→Mat moves

    Args:
        dst_tile: Destination Tile
        src_tile: Source Tile
        offset: Optional ``[offset_m, offset_k]`` to extract a sub-block from a wider source Tile.
            When the source is in Mat (L1) and no offset is specified, the source and destination
            Tiles must have the same physical shape.
        acc_to_vec_mode: Acc→Vec mode — ``pl.AccToVecMode.SingleModeVec0``, ``pl.AccToVecMode.SingleModeVec1``,
            ``pl.AccToVecMode.DualModeSplitM``, ``pl.AccToVecMode.DualModeSplitN``;
            only meaningful when src is Acc and dst is Vec
        relu_pre_mode: Optional ReLU fusion — ``pl.ReluPreMode.NormalRelu``
        scale: Optional fixpipe quantization scale.
            ``float`` or runtime scalar → per-tensor quantization (deqScalar path);
            a runtime **FP32** scalar is auto-reinterpreted as its IEEE-754 bit
            pattern (codegen bitcast), so pass the raw float value; a runtime
            **INT32/INT64** scalar must carry the pre-encoded float32 bit pattern
            (``struct.pack("!f", scale)``). Other runtime scalar dtypes
            (FP16/BF16/unsigned/narrower ints) are rejected at parse time.
            ``Tile`` (INT64, MemorySpace.Scaling, shape ``[1, N]``) → per-channel quantization with a
            **user-prepared deqTensor tile**; the framework reuses it directly (no auto-allocation,
            no sync insertion) — the user owns the data flow and must ensure the tile is ready
            (load → move → sync MTE1→FIX) before the move.
            Hardware requires ``[1, N]`` (row == 1, per-column), ``N % 16 == 0`` and ``N <= 512`` —
            ``[N, 1]`` per-row scaling is NOT supported.
            ``None`` → no fixpipe quantization.
        phase: Optional FixPipe unit-flag phase for Acc→Vec or Acc→Mat —
            ``pl.STPhase.Partial`` or ``pl.STPhase.Final``. It must be paired
            correctly with the producer's ``AccPhase`` sequence. Acc→Mat
            supports TMOV, TEXTRACT, and TINSERT; Acc→Vec does not support an
            ``offset`` together with phase.
    """


@_api_decl
def img2col(
        dst_tile: Tile,
        src_tile: Tile,
        /,
        *,
        config: Img2ColConfig,
        pos_m: int,
        pos_k: int,
) -> None:
    """Expand one L1 feature-map window into the L0A matrix.

    Args:
        dst_tile: Destination Tile in ``Left`` (L0A) memory, dtype matching src (fp16/bf16)
        src_tile: Source conv-layout TileType in ``Mat`` (L1) memory — ``pl.NC1HWC0``
            shape ``[1, C1, H, W, C0]`` or ``pl.NDC1HWC0`` shape ``[1, 1, C1, H, W, C0]``
        config: ``pl.Img2ColConfig`` window geometry — kernel/stride/dilation/pad_value
            are compile-time constants; padding entries are constants or runtime
            integer scalars
        pos_m: Element offset of the first generated row in the (H, W) enumeration
        pos_k: Element offset of the first generated column in the K enumeration
    """


@_api_decl
def insert(
    dst_tile: Tile,
    src_tile: Tile,
    /,
    offset: Offset,
    *,
    relu_pre_mode: Optional[ReluPreMode] = None,
    scale: Optional[Union[int, float, Tile]] = None,
    phase: Optional[STPhase] = None,
) -> None:
    """Insert a small Tile into a larger Tile at the given 2-D offset (TINSERT).

    Args:
        dst_tile: Destination (larger) Tile
        src_tile: Source (smaller) Tile
        offset: Insertion coordinates ``[row, col]`` in the destination
        relu_pre_mode: Optional ReLU fusion for Acc→Mat
        scale: Optional scalar or Scaling Tile for Acc→Mat FixPipe quantization
        phase: Optional FixPipe unit-flag phase for Acc→Mat —
            ``pl.STPhase.Partial`` or ``pl.STPhase.Final``. It must be paired
            correctly with the producer's ``AccPhase`` sequence.
    """


@_api_decl
def ssbuf_load(struct_var: Struct, offset: int, /) -> None:
    """Load data from SuperScalar Buffer (SSBUF) into a struct variable.

    Args:
        struct_var: Struct variable (created via ``pl.struct``)
        offset: SSBUF offset
    """


@_api_decl
def ssbuf_store(struct_var: Struct, offset: int, /) -> None:
    """Write a struct variable to SuperScalar Buffer (SSBUF).

    Args:
        struct_var: Struct variable (created via ``pl.struct``)
        offset: SSBUF offset
    """


# ===================================================================
# Section B: Compute block ops
# ===================================================================

# --- B1. Binary element-wise (out, lhs, rhs) ---
#
# Constraints (apply to all ops in this section):
# - No broadcast: ``out``, ``lhs``, ``rhs`` (when Tile) must have identical shape.
# - No implicit type promotion: all operands must have the same dtype.
# - Supported dtypes: FP16, FP32, BF16 (op-dependent; FP8/FP4 are storage-only
#   — use vf.astype to convert to/from FP32/BF16/FP16 for computation).


@_api_decl
def adds(out: Tile, lhs: Tile, rhs: Scalar, /) -> None:
    """Elementwise scalar addition: ``out = lhs + rhs``."""


@_api_decl
def subs(out: Tile, lhs: Tile, rhs: Scalar, /) -> None:
    """Elementwise scalar subtraction: ``out = lhs - rhs``."""


@_api_decl
def muls(out: Tile, lhs: Tile, rhs: Scalar, /) -> None:
    """Elementwise scalar multiplication: ``out = lhs * rhs``."""


@_api_decl
def add(out: Tile, lhs: Tile, rhs: Union[Tile, int, float]) -> None:
    """Element-wise addition: ``out = lhs + rhs``

    Supports both tile-tile and tile-scalar operations:
        - ``add(out, tile_a, tile_b)`` -> tile-tile
        - ``add(out, tile_a, scalar)`` -> tile-scalar
    """


@_api_decl
def sub(out: Tile, lhs: Tile, rhs: Union[Tile, int, float]) -> None:
    """Element-wise subtraction: ``out = lhs - rhs``

    Supports both tile-tile and tile-scalar operations:
        - ``sub(out, tile_a, tile_b)`` -> tile-tile
        - ``sub(out, tile_a, scalar)`` -> tile-scalar
    """


@_api_decl
def mul(out: Tile, lhs: Tile, rhs: Union[Tile, int, float]) -> None:
    """Element-wise multiplication: ``out = lhs * rhs``

    Supports both tile-tile and tile-scalar operations:
        - ``mul(out, tile_a, tile_b)`` -> tile-tile
        - ``mul(out, tile_a, scalar)`` -> tile-scalar
    """


@_api_decl
def div(out: Tile, lhs: Tile, rhs: Union[Tile, int, float]) -> None:
    """Element-wise division: ``out = lhs / rhs``

    Supports both tile-tile and tile-scalar operations:
        - ``div(out, tile_a, tile_b)`` -> tile-tile
        - ``div(out, tile_a, scalar)`` -> tile-scalar
    """


@_api_decl
def rem(out: Tile, lhs: Tile, rhs: Union[Tile, int, float]) -> None:
    """Element-wise remainder (truncation semantics): ``out = lhs % rhs``

    Supports both tile-tile and tile-scalar operations:
        - ``rem(out, tile_a, tile_b)`` -> tile-tile
        - ``rem(out, tile_a, scalar)`` -> tile-scalar
    """


# --- B2. Bitwise element-wise (out, lhs, rhs) ---


@_api_decl
def and_(out: Tile, lhs: Tile, rhs: Union[Tile, int]) -> None:
    """Element-wise bitwise AND: ``out = lhs & rhs``

    Supports both tile-tile and tile-scalar operations:
        - ``and_(out, tile_a, tile_b)`` -> tile-tile
        - ``and_(out, tile_a, scalar)`` -> tile-scalar
    """


@_api_decl
def or_(out: Tile, lhs: Tile, rhs: Union[Tile, int]) -> None:
    """Element-wise bitwise OR: ``out = lhs | rhs``

    Supports both tile-tile and tile-scalar operations:
        - ``or_(out, tile_a, tile_b)`` -> tile-tile
        - ``or_(out, tile_a, scalar)`` -> tile-scalar
    """


@_api_decl
def shl(out: Tile, lhs: Tile, rhs: Union[Tile, int]) -> None:
    """Element-wise left shift: ``out = lhs << rhs``

    Supports both tile-tile and tile-scalar operations:
        - ``shl(out, tile_a, tile_b)`` -> tile-tile
        - ``shl(out, tile_a, scalar)`` -> tile-scalar
    """


@_api_decl
def shr(out: Tile, lhs: Tile, rhs: Union[Tile, int]) -> None:
    """Element-wise right shift: ``out = lhs >> rhs``

    Supports both tile-tile and tile-scalar operations:
        - ``shr(out, tile_a, tile_b)`` -> tile-tile
        - ``shr(out, tile_a, scalar)`` -> tile-scalar
    """


@_api_decl
def xor(out: Tile, lhs: Tile, rhs: Union[Tile, int], tmp: Tile) -> None:
    """Element-wise bitwise XOR: ``out = lhs ^ rhs``

    Args:
        out: Destination Tile
        lhs: Left-hand Tile
        rhs: Right-hand Tile or Scalar (tile-scalar path lowers to ``block.xors``)
        tmp: Workspace Tile
    """


@_api_decl
def expands(out: Tile, scalar: Union[int, float]) -> None:
    """Fill Tile with a scalar (splat): ``out[i] = scalar``"""


# --- B3. Unary element-wise (out, src) ---


@_api_decl
def neg(out: Tile, src: Tile) -> None:
    """Element-wise negate: ``out = -src``"""


@_api_decl
def not_(out: Tile, src: Tile) -> None:
    """Element-wise bitwise NOT: ``out = ~src``"""


@_api_decl
def abs(out: Tile, src: Tile) -> None:
    """Element-wise absolute value: ``out = |src|``"""


@_api_decl
def exp(out: Tile, src: Tile) -> None:
    """Element-wise exponential: ``out = exp(src)``"""


@_api_decl
def log(out: Tile, src: Tile) -> None:
    """Element-wise natural log: ``out = log(src)``"""


@_api_decl
def sqrt(out: Tile, src: Tile) -> None:
    """Element-wise square root: ``out = sqrt(src)``"""


@_api_decl
def rsqrt(out: Tile, src: Tile) -> None:
    """Element-wise reciprocal square root: ``out = 1/sqrt(src)``"""


@_api_decl
def recip(out: Tile, src: Tile) -> None:
    """Element-wise reciprocal: ``out = 1/src``"""


@_api_decl
def relu(out: Tile, src: Tile) -> None:
    """Element-wise ReLU: ``out = max(0, src)``"""


@_api_decl
def fillpad(out: Tile, src: Tile, *, mode: FillPadMode = FillPadMode.NORMAL) -> None:
    """Fill padding region of a Tile.

    Args:
        out: Destination Tile.
        src: Source Tile.
        mode: Fill mode — ``pl.FillPadMode.NORMAL`` (default, dst and src same shape),
            ``pl.FillPadMode.EXPAND`` (dst larger than src, expand fill),
            ``pl.FillPadMode.INPLACE`` (dst and src share the same address).
    """


# --- B4. Type conversion ---


@_api_decl
def cast(out: Tile, src: Tile, *, mode: Optional[RoundMode] = None) -> None:
    """Cast Tile to a different data type.

    The target dtype is inferred from ``out`` tile's dtype.

    Args:
        out: Destination Tile (determines target dtype)
        src: Source Tile
        mode: Rounding mode — ``pl.RoundMode.CAST_NONE``, ``pl.RoundMode.CAST_RINT``, ``pl.RoundMode.CAST_ROUND``,
            ``pl.RoundMode.CAST_FLOOR``, ``pl.RoundMode.CAST_CEIL``,
            ``pl.RoundMode.CAST_TRUNC``, ``pl.RoundMode.CAST_ODD``.
            Per-path support follows the cast API reference: ``DT_FP32`` to ``DT_FP8E4M3FN``/``DT_FP8E5M2``
            rounds to nearest even only, so there only ``CAST_RINT``/``CAST_NONE`` are accepted (and an
            omitted ``mode`` resolves to ``CAST_RINT`` there, while every other path defaults to
            ``CAST_ROUND``).
    """


@_api_decl
def add_relu_cast(
    out: Tile, lhs: Tile, rhs: Tile, *, target_type: DType, mode: RoundMode = RoundMode.CAST_ROUND
) -> None:
    """Fused add + ReLU + cast: ``out = cast(relu(lhs + rhs), target_type)``"""


@_api_decl
def sub_relu_cast(
    out: Tile, lhs: Tile, rhs: Tile, *, target_type: DType, mode: RoundMode = RoundMode.CAST_ROUND
) -> None:
    """Fused sub + ReLU + cast: ``out = cast(relu(lhs - rhs), target_type)``"""


@_api_decl
def mul_cast(out: Tile, lhs: Tile, rhs: Tile, *, target_type: DType, mode: RoundMode = RoundMode.CAST_ROUND) -> None:
    """Fused mul + cast: ``out = cast(lhs * rhs, target_type)``"""


# --- B5. Compare / select ---


@_api_decl
def eq(out: Tile, lhs: Tile, rhs: Union[Tile, int, float]) -> None:
    """Element-wise equal: ``out = (lhs == rhs)``

    Supports both tile-tile and tile-scalar operations:
        - ``eq(out, tile_a, tile_b)`` -> tile-tile
        - ``eq(out, tile_a, scalar)`` -> tile-scalar
    """


@_api_decl
def ne(out: Tile, lhs: Tile, rhs: Union[Tile, int, float]) -> None:
    """Element-wise not equal: ``out = (lhs != rhs)``

    Supports both tile-tile and tile-scalar operations:
        - ``ne(out, tile_a, tile_b)`` -> tile-tile
        - ``ne(out, tile_a, scalar)`` -> tile-scalar
    """


@_api_decl
def lt(out: Tile, lhs: Tile, rhs: Union[Tile, int, float]) -> None:
    """Element-wise less than: ``out = (lhs < rhs)``

    Supports both tile-tile and tile-scalar operations:
        - ``lt(out, tile_a, tile_b)`` -> tile-tile
        - ``lt(out, tile_a, scalar)`` -> tile-scalar
    """


@_api_decl
def le(out: Tile, lhs: Tile, rhs: Union[Tile, int, float]) -> None:
    """Element-wise less or equal: ``out = (lhs <= rhs)``

    Supports both tile-tile and tile-scalar operations:
        - ``le(out, tile_a, tile_b)`` -> tile-tile
        - ``le(out, tile_a, scalar)`` -> tile-scalar
    """


@_api_decl
def gt(out: Tile, lhs: Tile, rhs: Union[Tile, int, float]) -> None:
    """Element-wise greater than: ``out = (lhs > rhs)``

    Supports both tile-tile and tile-scalar operations:
        - ``gt(out, tile_a, tile_b)`` -> tile-tile
        - ``gt(out, tile_a, scalar)`` -> tile-scalar
    """


@_api_decl
def ge(out: Tile, lhs: Tile, rhs: Union[Tile, int, float]) -> None:
    """Element-wise greater or equal: ``out = (lhs >= rhs)``

    Supports both tile-tile and tile-scalar operations:
        - ``ge(out, tile_a, tile_b)`` -> tile-tile
        - ``ge(out, tile_a, scalar)`` -> tile-scalar
    """


@_api_decl
def select(out: Tile, mask: Tile, lhs: Tile, rhs: Union[Tile, int, float], tmp: Tile) -> None:
    """Select by mask: ``out[i] = lhs[i] if mask[i] else rhs[i]``

    Supports both tile-tile and tile-scalar operations:
        - ``select(out, mask, tile_a, tile_b, tmp)`` -> tile-tile
        - ``select(out, mask, tile_a, scalar, tmp)`` -> tile-scalar

    Args:
        out: Destination Tile
        mask: Mask Tile (from ``eq``/``gt``/...)
        lhs: Tile selected when mask is true
        rhs: Tile or Scalar selected when mask is false
        tmp: Workspace Tile
    """


# --- B6. Fused ops ---


@_api_decl
def add_relu(out: Tile, lhs: Tile, rhs: Tile) -> None:
    """Fused add + ReLU: ``out = relu(lhs + rhs)``"""


@_api_decl
def sub_relu(out: Tile, lhs: Tile, rhs: Tile) -> None:
    """Fused sub + ReLU: ``out = relu(lhs - rhs)``"""


@_api_decl
def mul_add_dst(out: Tile, lhs: Tile, rhs: Tile) -> None:
    """Fused multiply-add into out: ``out = lhs * rhs + out``"""


@_api_decl
def fused_mul_add(out: Tile, lhs: Tile, rhs: Tile) -> None:
    """Fused multiply-add in-place: ``out = lhs * out + rhs``"""


@_api_decl
def fused_mul_add_relu(out: Tile, a: Tile, b: Tile) -> None:
    """Fused multiply-add + ReLU in-place: ``out = relu(out * a + b)``"""


@_api_decl
def axpy(out: Tile, src: Tile, alpha: Union[int, float], /) -> None:
    """AXPY: ``out[i] = alpha * src[i] + out[i]``

    Args:
        out: Destination Tile (also accumulates)
        src: Source Tile
        alpha: Scalar multiplier
    """


@_api_decl
def partadd(out: Tile, src0: Tile, src1: Tile) -> None:
    """Partial addition: ``out = src0 + src1`` (only src1's valid region)."""


@_api_decl
def partmax(out: Tile, src0: Tile, src1: Tile) -> None:
    """Partial maximum over the valid regions of two Tiles."""


@_api_decl
def partmin(out: Tile, src0: Tile, src1: Tile) -> None:
    """Partial minimum over the valid regions of two Tiles."""


@_api_decl
def partmul(out: Tile, src0: Tile, src1: Tile) -> None:
    """Partial multiplication over the valid regions of two Tiles."""


# --- B7. Matrix ops ---


@_api_decl
def matmul(
    dst_tile: Tile, lhs_tile: Tile, rhs_tile: Tile, bias_tile: Optional[Tile] = None, /,
    *, phase: Optional[AccPhase] = None
) -> None:
    """Matrix multiply: ``dst = lhs @ rhs`` (L0A × L0B → L0C).

    When ``bias_tile`` is provided, performs fused matmul + bias:
    ``dst = lhs @ rhs + bias`` (bias row-broadcast [1,N], added in fixpipe).

    Args:
        dst_tile: Accumulator Tile (L0C, output)
        lhs_tile: Left matrix Tile (L0A)
        rhs_tile: Right matrix Tile (L0B)
        bias_tile: Optional positional Bias Tile (BiasTable buffer, shape [1, N], row-broadcast)
        phase: Optional — ``pl.AccPhase.Partial`` or ``pl.AccPhase.Final``
    """


@_api_decl
def matmul_acc(
    dst_tile: Tile, acc_tile: Tile, lhs_tile: Tile, rhs_tile: Tile, /, *, phase: Optional[AccPhase] = None
) -> None:
    """In-place accumulating matrix multiply: ``dst += lhs @ rhs``.

    ``acc_tile`` must be the same Tile as ``dst_tile``. Initialize it with
    ``matmul`` before the first accumulating operation; this operation does not zero it.

    Args:
        dst_tile: Accumulator Tile (L0C, input/output)
        acc_tile: Must be the same Tile as dst_tile
        lhs_tile: Left matrix Tile (L0A)
        rhs_tile: Right matrix Tile (L0B)
        phase: Optional — ``pl.AccPhase.Partial`` or ``pl.AccPhase.Final``
    """


@_api_decl
def matmul_mx(
    dst_tile: Tile, lhs_tile: Tile, rhs_tile: Tile, /, scale_a: Tile, scale_b: Tile,
    bias_tile: Optional[Tile] = None, *, phase: Optional[AccPhase] = None
) -> None:
    """MX matmul with per-group E8M0 scale and optional bias.

    Left/Right tiles use FP8/FP4 dtype; scale tiles use E8M0 in ScaleLeft/ScaleRight.
    Hardware mad_mx reads scale implicitly via SFractal layout.

    Args:
        dst_tile: Accumulator Tile (L0C, output, FP32)
        lhs_tile: Left matrix Tile (L0A, FP8/FP4)
        rhs_tile: Right matrix Tile (L0B, FP8/FP4)
        scale_a: Left scale Tile (ScaleLeft, E8M0)
        scale_b: Right scale Tile (ScaleRight, E8M0)
        bias_tile: Optional Bias Tile (BiasTable buffer, FP32, shape [1, N], row-broadcast)
        phase: Optional — ``pl.AccPhase.Partial`` or ``pl.AccPhase.Final``
    """


@_api_decl
def matmul_mx_acc(
    dst_tile: Tile, acc_tile: Tile, lhs_tile: Tile, rhs_tile: Tile, /, scale_a: Tile, scale_b: Tile,
    *, phase: Optional[AccPhase] = None
) -> None:
    """In-place MX matmul with accumulation: ``dst += scaled_lhs @ scaled_rhs``.

    ``acc_tile`` must be the same Tile as ``dst_tile``. Initialize it with
    ``matmul_mx`` before the first accumulating operation; this operation does not zero it.

    Args:
        dst_tile: Accumulator Tile (L0C, input/output, FP32)
        acc_tile: Must be the same Tile as dst_tile
        lhs_tile: Left matrix Tile (L0A, FP8/FP4)
        rhs_tile: Right matrix Tile (L0B, FP8/FP4)
        scale_a: Left scale Tile (ScaleLeft, E8M0)
        scale_b: Right scale Tile (ScaleRight, E8M0)
        phase: Optional — ``pl.AccPhase.Partial`` or ``pl.AccPhase.Final``
    """



@_api_decl
def gemm(
    acc: Tile, l1a: Tile, l1b: Tile, /, *,
    l0a: Union[Tile, TileGroup], l0b: Union[Tile, TileGroup],
    m: Optional[Scalar] = None, n: Optional[Scalar] = None, k: Optional[Scalar] = None,
    init: bool = True, splitn: Optional[int] = None, splitk: Optional[int] = None,
    trans_a: bool = False, trans_b: bool = False, bias: Optional[Tile] = None,
) -> None:
    """Stage L1 operands and compute acc = l1a @ l1b, or accumulate when init=False.

    The caller supplies all Tiles, addresses and mutex IDs. A staging TileGroup
    rotates once per step. Generated move/matmul statements use native auto_mutex.
    Automatic cross-core pipelines track L1 reads on MTE1; the accumulator,
    staging Tiles and bias must remain local to the stage.

    Args:
        acc: L0C accumulator, shape [M, N].
        l1a: L1 left operand, shape [M, K], or [K, M] with trans_a.
        l1b: L1 right operand, shape [K, N], or [N, K] with trans_b.
        l0a: L0A staging Tile or TileGroup.
        l0b: L0B staging Tile or TileGroup.
        m: Effective M. Narrows l0a and acc; narrowed Tiles require compact=1.
        n: Effective N. Narrows l0b and acc.
        k: Effective K. Narrows l0a and l0b. L1 descriptors are left unchanged.
        init: Compile-time bool; True initializes acc, False accumulates in place.
        splitn: Compile-time N step, a multiple of 16, equal to l0b's column
            extent. Requires a static accumulator slot. The final strip may be
            shorter; l0b then requires compact=1. With splitn, n must be static;
            m and bias are unsupported.
        splitk: Compile-time K step, equal to l0a's column and l0b's row extents.
            The first step initializes when init=True; subsequent steps accumulate.
            A short final step requires compact staging. With splitk, k must be static.
            Mutually exclusive with splitn.
        trans_a: Transpose a named static L1 operand using an NZ-to-ZN alias.
            For runtime-selected slots, reinterpret the whole group before selection.
        trans_b: Transpose l1b by the same mechanism.
        bias: Optional BiasTable Tile, shape [1, N]; requires init=True.

    Each call sets the staging and accumulator descriptors to its effective
    extents; omitted axes use the L1 operands' declared extents, even after a
    partial call on the same Tiles. Explicit full physical extents need no compact
    layout. Extents remain after the call so a subsequent store drains the same
    valid extent. Runtime extents must stay positive and within declared shapes.
    """


@_api_decl
def gemm_mx(
    acc: Tile, l1a: Tile, l1b: Tile, l1a_scale: Tile, l1b_scale: Tile, /, *,
    l0a: Union[Tile, TileGroup], l0b: Union[Tile, TileGroup],
    scale_a: Union[Tile, TileGroup], scale_b: Union[Tile, TileGroup],
    m: Optional[Scalar] = None, n: Optional[Scalar] = None, k: Optional[Scalar] = None,
    init: bool = True, trans_a: bool = False, trans_b: bool = False, bias: Optional[Tile] = None,
) -> None:
    """Stage MX data and scale pairs from L1, then compute an MX matmul.

    Each operand is staged as an adjacent data/scale move pair. Native matmul_mx
    checks the ScaleLeft/ScaleRight plane at its data slot's address >> 4.

    Args:
        acc: FP32 L0C accumulator, shape [M, N].
        l1a: FP8/FP4 L1 left operand, shape [M, K], or [K, M] with trans_a.
        l1b: FP8/FP4 L1 right operand, shape [K, N], or [N, K] with trans_b.
        l1a_scale: E8M0 L1 scale, ZZ layout, shape [M, K // 32].
        l1b_scale: E8M0 L1 scale, NN layout, shape [K // 32, N].
        l0a: L0A data staging Tile or TileGroup.
        l0b: L0B data staging Tile or TileGroup.
        scale_a: ScaleLeft plane or group, ZZ layout, shape [M, K // 32].
        scale_b: ScaleRight plane or group, NN layout, shape [K // 32, N].
        m: Effective M; narrows l0a, acc and scale_a's row axis.
        n: Effective N; narrows l0b, acc and scale_b's column axis.
        k: Effective K; narrows data staging and both planes' group axes.
            Declared K and a static k must be multiples of 64. A runtime k has
            the same caller contract. Narrowed data/acc Tiles require compact=1;
            planes require compact=1 when k narrows their group axis. M/N-only
            plane narrowing does not require it.
        init: Compile-time bool; False emits matmul_mx_acc.
        trans_a: Transpose the named static L1 data operand as in gemm.
            Its scale operand keeps the canonical scale shape and layout.
        trans_b: Transpose l1b by the same mechanism.
        bias: Optional FP32 BiasTable Tile, shape [1, N]; requires init=True.

    Each call sets data staging, accumulator and scale-plane extents, restoring
    declared L1 extents on omitted axes even when reusing narrowed Tiles. Explicit
    full physical extents need no compact layout. Effective extents remain after
    the call for a subsequent store. Source L1 descriptors are unchanged.
    splitn and splitk are unsupported.
    """


@_api_decl
def transpose(out: Tile, src: Tile) -> None:
    """Transpose Tile by swapping the last two dimensions.

    Args:
        out: Destination Tile
        src: Source Tile
    """


# --- B8. Reductions / expands ---
#
# Unified reduce / expand interfaces.  ``dim=0`` reduces along the last axis
# (row-wise), ``dim=1`` reduces along the first axis (column-wise).
#
# tmp Tile constraints (apply to all reduce ops with ``tmp`` parameter):
# - dtype: must match ``src`` Tile dtype
# - shape: must match ``src`` Tile shape (1:1 workspace, not reduced size)
# - memory: must be in UB (Vec) memory space


@_api_decl
def sum(out: Tile, src: Tile, tmp: Tile, *, dim: int = 0) -> None:
    """Sum reduction along the specified dimension.

    Args:
        out: Destination Tile
        src: Source Tile
        tmp: Workspace Tile (required by hardware)
        dim: Reduction dimension — 0=row (last axis), 1=column (first axis)

    Example::

        tmp_type = pl.TileType(shape=src.type.shape, dtype=pl.DT_FP32,
                               target_memory=pl.MemorySpace.Vec)
        tmp = pl.make_tile(tmp_type, addr=0x1000)
        pl.sum(out, src, tmp, dim=0)   # row-wise sum, out shape = [src.shape[0], 1]
    """


@_api_decl
def argmax(out: Tile, src: Tile, *, dim: int = 0) -> None:
    """Argmax reduction along the specified dimension.

    Args:
        out: Destination Tile
        src: Source Tile
        dim: Reduction dimension — 0=row (last axis), 1=column (first axis)
    """


@_api_decl
def argmin(out: Tile, src: Tile, *, dim: int = 0) -> None:
    """Argmin reduction along the specified dimension.

    Args:
        out: Destination Tile
        src: Source Tile
        dim: Reduction dimension — 0=row (last axis), 1=column (first axis)
    """


@_api_decl
def expand_max(out: Tile, src: Tile, scalar: Tile, *, dim: int = 0) -> None:
    """Max expand (broadcast reduction result back to full shape).

    Args:
        out: Destination Tile
        src: Source Tile (reduction result)
        scalar: Scalar Tile for the expand operation
        dim: Expand dimension — 0=row, 1=column
    """


@_api_decl
def expand_min(out: Tile, src: Tile, scalar: Tile, *, dim: int = 0) -> None:
    """Min expand.

    Args:
        out: Destination Tile
        src: Source Tile (reduction result)
        scalar: Scalar Tile for the expand operation
        dim: Expand dimension — 0=row, 1=column
    """


@_api_decl
def expand_mul(out: Tile, src: Tile, scalar: Tile, *, dim: int = 0) -> None:
    """Multiply expand.

    Args:
        out: Destination Tile
        src: Source Tile (reduction result)
        scalar: Scalar Tile for the expand operation
        dim: Expand dimension — 0=row, 1=column
    """


@_api_decl
def expand_sub(out: Tile, src: Tile, scalar: Tile, *, dim: int = 0) -> None:
    """Subtract expand.

    Args:
        out: Destination Tile
        src: Source Tile (reduction result)
        scalar: Scalar Tile for the expand operation
        dim: Expand dimension — 0=row, 1=column
    """


@_api_decl
def expand_div(out: Tile, src: Tile, scalar: Tile, *, dim: int = 0) -> None:
    """Divide expand.

    Args:
        out: Destination Tile
        src: Source Tile (reduction result)
        scalar: Scalar Tile for the expand operation
        dim: Expand dimension — 0=row, 1=column
    """


@_api_decl
def expand_add(out: Tile, src: Tile, scalar: Tile, *, dim: int = 0) -> None:
    """Add expand (broadcast the reduction result back to full shape).

    Args:
        out: Destination Tile
        src: Source Tile (reduction result)
        scalar: Scalar Tile for the expand operation
        dim: Expand dimension — 0=row, 1=column
    """


@_api_decl
def expand_expdif(out: Tile, src: Tile, scalar: Tile, *, dim: int = 0) -> None:
    """Fused expand-expdif (softmax-style update: exp of the broadcast difference).

    Args:
        out: Destination Tile
        src: Source Tile (reduction result)
        scalar: Scalar Tile for the expand operation
        dim: Expand dimension — 0=row, 1=column
    """


@_api_decl
def prod(out: Tile, src: Tile, tmp: Tile, *, dim: int = 0) -> None:
    """Product reduction along the specified dimension.

    Args:
        out: Destination Tile
        src: Source Tile
        tmp: Workspace Tile (required by hardware)
        dim: Reduction dimension — 0=row (last axis), 1=column (first axis)
    """


# --- B9. Gather / scatter / sort ---


@_api_decl
def gather(
    out: Tile,
    src: Tile,
    indices_or_k_value: Tile,
    tmp_or_cdst: Optional[Tile] = None,
    tmp: Optional[Tile] = None,
    *,
    cmp_mode: int = 0,
    offset: int = 0,
) -> None:
    """Gather elements by index, or by comparison against a k-value.

    Two forms share this signature; the trailing positional parameters mean
    different things in each:

    - index form ``gather(out, src, indices[, tmp])``: ``out[i] = src[indices[i]]``
    - compare form ``gather(out, src, k_value, cdst, tmp, cmp_mode=...)``: indices
      where ``src`` compares against the k-value per ``cmp_mode``

    Args:
        out: Destination Tile
        src: Source Tile
        indices_or_k_value: Index Tile (index form) or k-value Tile (compare form)
        tmp_or_cdst: Workspace Tile (index form) or cdst Tile (compare form)
        tmp: Workspace Tile, compare form only
        cmp_mode: Comparison mode (default 0)
        offset: Index offset
    """


@_api_decl
def gatherb(out: Tile, src: Tile, offsets: Tile) -> None:
    """Gather elements by 32-byte block byte offset.

    Args:
        out: Destination Tile
        src: Source Tile
        offsets: Byte offset Tile
    """


@_api_decl
def gathermask(out: Tile, src: Tile, *, pattern_mode: int) -> None:
    """Extract columns by bit-pattern mask.

    Args:
        out: Destination Tile
        src: Source Tile
        pattern_mode: Bit-pattern extraction mode
    """


@_api_decl
def scatter(out: Tile, src: Tile, idx: Tile) -> None:
    """Scatter elements by index.

    Args:
        out: Destination Tile
        src: Source Tile
        idx: Index Tile
    """


@_api_decl
def mrgsort(dst: Tile, src: Tile, *, block_len: int) -> None:
    """Merge sort.

    Args:
        dst: Sorted output Tile
        src: Source Tile
        block_len: Sort block length
    """


@_api_decl
def mrgsort2(src0: Tile, src1: Tile, dst: Tile, tmp: Tile, *args, exhausted: bool = False) -> None:
    """Two-way (or multi-way) merge sort.

    Args:
        src0: First source Tile (val-idx pairs)
        src1: Second source Tile (val-idx pairs)
        dst: Destination Tile
        tmp: Workspace Tile
        *args: Optional additional source Tiles for multi-way merge
        exhausted: Whether any source is already exhausted
    """


@_api_decl
def sort32(dst: Tile, src: Tile, idx: Tile, tmp: Optional[Tile] = None) -> None:
    """Sort 32 elements with index tracking.

    Args:
        dst: Destination Tile for sorted values
        src: Source Tile (32 elements)
        idx: Index Tile for tracking original positions
        tmp: Optional workspace Tile (for tail-block handling)
    """


@_api_decl
def histogram(dst: Tile, src: Tile, idx: Tile, *, is_msb: bool) -> None:
    """Histogram accumulation for radix sort preprocessing.

    Counts byte-value frequencies in *src* and writes per-row bin counts to *dst*.

    Args:
        dst: Destination Tile (``pl.DT_UINT32``, cols >= 256)
        src: Source Tile (``pl.DT_UINT16``)
        idx: Index Tile (``pl.DT_UINT8``, DN layout); used for filtering when ``is_msb=False``
        is_msb: ``True`` counts high byte (bits 15-8); ``False`` counts low byte (bits 7-0)
            filtered by rows where the high byte matches ``idx``
    """


# --- B10. Quantization / index / misc ---


@_api_decl
def quant(out: Tile, src: Tile, scale: Tile, *, mode: QuantMode = QuantMode.SYM, offset: Optional[Tile] = None) -> None:
    """Quantize Tile (high-precision → low-precision integer).

    Args:
        out: Destination Tile (quantized output)
        src: Source Tile (float input)
        scale: Scale Tile
        mode: ``pl.QuantMode.SYM`` (symmetric) or ``pl.QuantMode.ASYM`` (asymmetric, requires *offset*)
        offset: Offset Tile (required for ``mode=pl.QuantMode.ASYM``)
    """


@_api_decl
def dequant(out: Tile, src: Tile, scale: Tile, offset: Tile) -> None:
    """Dequantize Tile (low-precision integer → high-precision).

    Args:
        out: Destination Tile (float output)
        src: Source Tile (quantized input)
        scale: Scale Tile
        offset: Offset Tile
    """


@_api_decl
def getval(container: "Tile | Tensor", offset: int) -> Scalar:
    """Read a scalar at the given linear offset, widening integer elements except UINT64 to INT64.

    Inside SIMT vector functions and their SIMT helpers, use element indexing instead;
    those reads preserve the Tile or Tensor's element dtype.
    """


@_api_decl
def numel(tensor: Tensor) -> Scalar:
    """Element count of a GM Tensor (AICPU kernels only): the shape product.

    Mirrors the cpp ``tensor->NumElements()``. Dynamic dims stay runtime
    values; a static shape folds to a constant. Not available in AI Core
    kernels -- those query extents through the tiling contract instead.
    """

@_api_decl
def setval(container: "Tile | Tensor", offset: int, value: Union[int, float]) -> None:
    """Write a scalar value into a Tile or Tensor at the given linear offset."""


@_api_decl
def atomic_add(tensor: Tensor, offset: int, value: Union[int, float]) -> Scalar:
    """Atomically add ``value`` to one GM Tensor element and return its pre-op value.

    Supported element dtypes: INT32, UINT32, FP32, INT64, UINT64.
    """


@_api_decl
def atomic_sub(tensor: Tensor, offset: int, value: Union[int, float]) -> Scalar:
    """Atomically subtract ``value`` from one GM Tensor element and return its pre-op value.

    Supported element dtypes: INT32, UINT32, FP32, INT64, UINT64.
    """


@_api_decl
def atomic_exch(tensor: Tensor, offset: int, value: Union[int, float]) -> Scalar:
    """Atomically replace one GM Tensor element with ``value`` and return its pre-op value.

    Supported element dtypes: INT32, UINT32, FP32, INT64, UINT64.
    """


@_api_decl
def atomic_max(tensor: Tensor, offset: int, value: Union[int, float]) -> Scalar:
    """Atomically keep the maximum of one GM Tensor element and ``value``; return the pre-op value.

    Supported element dtypes: INT32, UINT32, FP32, INT64, UINT64.
    """


@_api_decl
def atomic_min(tensor: Tensor, offset: int, value: Union[int, float]) -> Scalar:
    """Atomically keep the minimum of one GM Tensor element and ``value``; return the pre-op value.

    Supported element dtypes: INT32, UINT32, FP32, INT64, UINT64.
    """


@_api_decl
def atomic_inc(tensor: Tensor, offset: int, limit: Union[int, float]) -> Scalar:
    """Atomically increment a wrapping counter element and return its pre-op value.

    The new value is ``0`` when the old value is greater than or equal to
    ``limit``, otherwise ``old + 1``. Supported element dtypes: UINT32, UINT64.
    """


@_api_decl
def atomic_dec(tensor: Tensor, offset: int, limit: Union[int, float]) -> Scalar:
    """Atomically decrement a wrapping counter element and return its pre-op value.

    The new value is ``limit`` when the old value is zero or greater than
    ``limit``, otherwise ``old - 1``. Supported element dtypes: UINT32, UINT64.
    """


@_api_decl
def atomic_and(tensor: Tensor, offset: int, value: Union[int, float]) -> Scalar:
    """Atomically apply bitwise AND to one GM Tensor element and return its pre-op value.

    Supported element dtypes: INT32, UINT32, INT64, UINT64.
    """


@_api_decl
def atomic_or(tensor: Tensor, offset: int, value: Union[int, float]) -> Scalar:
    """Atomically apply bitwise OR to one GM Tensor element and return its pre-op value.

    Supported element dtypes: INT32, UINT32, INT64, UINT64.
    """


@_api_decl
def atomic_xor(tensor: Tensor, offset: int, value: Union[int, float]) -> Scalar:
    """Atomically apply bitwise XOR to one GM Tensor element and return its pre-op value.

    Supported element dtypes: INT32, UINT32, INT64, UINT64.
    """


@_api_decl
def atomic_cas(tensor: Tensor, offset: int, compare: Union[int, float], value: Union[int, float]) -> Scalar:
    """Atomically compare and exchange one GM Tensor element; return its pre-op value.

    ``value`` is stored when the element equals ``compare``; otherwise the
    element is unchanged. Compare the returned pre-op value with ``compare`` to
    learn whether the swap happened — this is a single CAS, not a retry loop.

    Supported element dtypes: INT32, UINT32, FP32, INT64, UINT64.
    """


@_api_decl
def atomic_load(tensor: Tensor, offset: int) -> Scalar:
    """Atomically load one GM Tensor element, bypassing the scalar DCache.

    Supported element dtypes: INT32, UINT32, FP32, INT64, UINT64.
    """


@_api_decl
def atomic_store(tensor: Tensor, offset: int, value: Union[int, float]) -> None:
    """Atomically store ``value`` into one GM Tensor element, bypassing the scalar DCache.

    Supported element dtypes: INT32, UINT32, FP32, INT64, UINT64.
    """


@_api_decl
def set_validshape(tile: "Tile | TileGroup", /, shape: Shape) -> None:
    """Set the valid shape of a Tile or tile_group (for partial-tile / tail-block operations).

    When a tile_group is passed, valid_shape is set on all tiles in the group.

    A conv-layout tile takes one value per shape dimension. Its TileType
    must carry an all-dynamic valid shape (``[-1, ..., -1]`` -- the default
    when valid_shape is omitted), and every value must be within ``(0, dim]``
    per dimension -- a conv tile has no 0-width empty region.
    """

@_api_decl
def reinterpret(tile: "Tile | TileGroup", /, *, dtype: Optional[DType] = None, shape: Optional[Shape] = None,
                layout: Optional[Layout] = None) -> "Tile | TileGroup":
    """Reinterpret a Tile or tile_group's dtype/shape/layout metadata without data movement.

    Returns a new handle using the source tile's current runtime address,
    with memory space, fractal, pad, compact and mutex mapping inherited; only
    the given properties are overridden. valid_shape is NOT inherited (the new
    handle starts with a dynamic valid shape, equivalent to -1; set it with
    ``pl.set_validshape``). The original handle is unchanged.

    The view's dtype, shape and layout are compile-time properties; its address
    comes from the source handle. No load/move/store/cast instruction is generated.
    The caller must guarantee
    that the physical data actually matches the new declaration (e.g. declaring
    ``layout=pl.ZN`` on data that really is ZN-arranged).

    Constraints:
        - at least one of ``dtype`` / ``shape`` / ``layout`` must be given
        - when ``dtype`` changes, ``shape`` must be given as well (the element
          count is re-stated explicitly)
        - ``shape`` must be compile-time constants; use ``pl.set_validshape``
          for runtime windows
        - the caller must ensure enough storage from the current address for
          the new shape and dtype, and alignment to the new element size;
          reinterpret does not statically validate runtime addresses

    Example::

        t2 = pl.reinterpret(tile_a, shape=[64, 64], dtype=pl.DT_BF16)  # same buffer as BF16 (dtype change needs shape)
        g2 = pl.reinterpret(group_a, shape=[128, 32])        # whole group, mutex kept

    Reinterpreting ``group.next()`` creates a view of the tile selected by that call.
    Reinterpreting the whole group creates views of all its tiles and shares the
    group's cursor. Advance the shared cursor once per iteration and read the
    group view with ``current()``::

        g_zn = pl.reinterpret(g, shape=[K, M], layout=pl.ZN)  # transposed view of the group
        t = g.next()                                          # advances the shared cursor
        pl.load(t, ...)
        pl.move(dst, g_zn.current())                          # same buffer as t; next() would skip one
    """


@_api_decl
def set_mask_count() -> None:
    """Switch mask to counting mode."""


@_api_decl
def set_mask_norm() -> None:
    """Switch mask to per-bit normalization mode."""


@_api_decl
def set_vec_mask(mask_high: int, mask_low: int) -> None:
    """Explicitly set the 128-bit vector mask from two 64-bit integers."""


@_api_decl
def reset_mask() -> None:
    """Reset the mask to all-ones (no masking)."""


@_api_decl
def fill_index(out: Tile, start: Union[int, float]) -> None:
    """Fill target tile with sequential indices starting from *start*."""


# ===================================================================
# Section E: Debug ops
# ===================================================================


@_api_decl
def mark_stamp(pipe: PipeType, id: int) -> None:
    """Insert a PMU point on every block that reaches this statement (3510 only).

    No JIT option is needed. Kernels without this call emit no PMU instrumentation.
    ``pipe`` (pl.PipeType) and ``id`` are compile-time constants. IDs are 0..4095
    (excluding bool) and must be unique per target/call site, including across
    different pipes. Runtime IDs are not supported.
    Cube supports S, MTE2, MTE1, M, FIX and MTE3; Vector supports S, MTE2, V
    and MTE3. Choose the pipe executing the work being observed: MTE2 for
    input transfers, MTE1 for L1-to-L0 transfers, M for matrix computation,
    V for vector computation, FIX for matrix-result conversion/transfers,
    MTE3 for output transfers, and S for scalar progress. ALL is not supported.
    Call this operation outside @pl.vector_function; SIMT kernels and functions
    are not supported. It returns no value; its result cannot be used in tuples,
    lists, function arguments, calculations, comparisons or conditions. A direct
    assignment is allowed only if the result is unused.
    No block or subblock filter is inserted. Use an explicit condition on
    pl.get_block_idx() to restrict which logical blocks emit a point. The Vector
    index includes the subblock index; it is not a physical processor ID.

    Hardware profiling records contain the numeric ID, not a user-defined name.
    No extra barrier, event handshake or per-point NOP spacing is inserted.
    CANN may insert required MTE barriers inside mark_stamp; V points do not
    wait for all pipelines. These are checkpoints, not guaranteed operation
    start/completion timestamps. Prefer sparse points near existing program
    synchronization; do not add synchronization merely to align the graph.
    Dense points can be lost by the collector. Targets with stamps retain a
    final drain and 16384-iteration NOP tail on every block for collection, even
    if a runtime condition skips the points. Total kernel time therefore includes
    instrumentation overhead.
    Collect with ``msprof --instr-profiling=on``; compare performance against an
    uninstrumented kernel.
    """
    ...


@_api_decl
def pto_assert(condition: bool, /, format_str: Optional[str] = None, *args, loc: bool = False) -> None:
    """Log when the runtime condition is false; execution continues without a host exception.

    Use ``pl.trap()`` when the kernel must abort.

    Args:
        condition: Scalar boolean condition (dtype must be BOOL)
        format_str: Optional compile-time constant format string (printf-style)
        *args: Scalar values to print in the format string
        loc: Show source location in the error message
    """


@_api_decl
def printf(format_str: str, *args, loc: bool = False) -> None:
    """Print scalar values using a compile-time format string (printf-style).

    Supported conversions: ``%d``/``%i`` (signed int), ``%u`` (unsigned int),
    ``%x`` (hex), ``%f`` (float, FP32 only).

    Args:
        format_str: Compile-time constant format string
        *args: Scalar values (int, float, or ``pl.Scalar``)
        loc: Show source location
    """


@_api_decl
def dump_data(
    data: Union[Tensor, Tile],
    offsets: Optional[Offset] = None,
    shapes: Optional[Shape] = None,
    *,
    workspace: Optional[Tensor] = None,
    loc: bool = False,
    flag: Optional[str] = None,
    logical_order: bool = False,
) -> None:
    """Print Tensor or Tile contents for debugging.

    Automatically dispatches based on input type:
    - TensorType (GM Tensor): prints GM tensor data
    - TileType (on-chip Tile): prints tile data

    Args:
        data: Tensor or Tile to dump
        offsets: Optional window start offsets (per dimension); must pair with *shapes*
        shapes: Optional window shape (per dimension); must pair with *offsets*
        workspace: Reserved for future extensions; the current implementation does not require this argument
        loc: Show source location
        flag: Optional compile-time string label printed as a standalone marker line
              before the dump output, to distinguish multiple dump sites
        logical_order: False (default) prints window values in physical order;
            True prints the same values in logical coordinate order
    """


@_api_decl
def trap() -> None:
    """Insert a trap instruction to unconditionally abort execution."""


# ===================================================================
# Section F: Scalar ops
# ===================================================================


@_api_decl
def min(lhs: Union[int, float], rhs: Union[int, float], /) -> Scalar:
    """Return the minimum of two scalars.

    Scalar-only operation for loop-bound calculations etc.
    For tile element-wise minimum, use ``pl.minimum``.

    Args:
        lhs: Left operand (scalar)
        rhs: Right operand (scalar)

    Returns:
        Scalar result.
    """


@_api_decl
def max(lhs: Union[int, float], rhs: Union[int, float], /) -> Scalar:
    """Return the maximum of two scalars.

    Scalar-only operation for loop-bound calculations etc.
    For tile element-wise maximum, use ``pl.maximum``.

    Args:
        lhs: Left operand (scalar)
        rhs: Right operand (scalar)

    Returns:
        Scalar result.
    """


@_api_decl
def scalar_abs(x: Union[int, float], /) -> Scalar:
    """Return the absolute value of a scalar: ``|x|``.

    Scalar-only operation for loop-bound calculations etc.
    The supported operand dtypes are INT8, INT16, INT32, INT64, INDEX, FP16,
    BF16 and FP32. For tile element-wise absolute value, use ``pl.abs``.

    Args:
        x: Source operand (scalar)

    Returns:
        Scalar result.
    """


@_api_decl
def ceil(x: Union[int, float], /) -> Scalar:
    """Return the ceiling of a scalar: the smallest integer >= ``x``.

    Scalar-only operation for scalar value computation; a floating-point result
    cannot be used as a loop bound. Integer operands, signed or unsigned, are
    unchanged; floating-point operands (FP16/BF16/FP32) are rounded up.

    Args:
        x: Source operand (scalar)

    Returns:
        Scalar result.
    """


@_api_decl
def floor(x: Union[int, float], /) -> Scalar:
    """Return the floor of a scalar: the largest integer <= ``x``.

    Scalar-only operation for scalar value computation; a floating-point result
    cannot be used as a loop bound. Integer operands, signed or unsigned, are
    unchanged; floating-point operands (FP16/BF16/FP32) are rounded down.

    Args:
        x: Source operand (scalar)

    Returns:
        Scalar result.
    """


@_api_decl
def ceildiv(lhs: Union[int, float], rhs: Union[int, float], /) -> Scalar:
    """Return the ceiling division of two scalars: ``ceil(lhs / rhs)``.

    Scalar-only operation for loop-bound calculations etc. Integer operands
    yield an integer ceiling, floating-point operands a floating-point one;
    operand dtypes follow the floor-division (``//``) rule set, unsigned
    integers included. For tile element-wise ceiling division, use the tensor
    API ``pypto.ceil_div``.

    Args:
        lhs: Dividend operand (scalar)
        rhs: Divisor operand (scalar); a compile-time zero divisor is rejected

    Returns:
        Scalar result.
    """


# ===================================================================
# Section G: Tile min/max (element-wise + reduce overload)
#
# ``maximum`` / ``minimum`` are overloaded:
#   - Element-wise (no ``dim``): ``out = max(lhs, rhs)``
#       - ``maximum(out, tile_a, tile_b)``  -> tile-tile
#       - ``maximum(out, tile_a, scalar)``  -> tile-scalar
#   - Reduce (with ``dim``): reduction along the specified dimension
#       - ``maximum(out, src, tmp, dim=0)`` -> row-wise max (last axis)
#       - ``maximum(out, src, tmp, dim=1)`` -> column-wise max (first axis)
# ===================================================================


@_api_decl
def minimum(out: Tile, lhs: Tile, rhs: Union[Tile, int, float], *, dim: Optional[int] = None) -> None:
    """Element-wise minimum or dimension-wise min reduction.

    Without ``dim`` (element-wise): ``out = min(lhs, rhs)``
        - ``minimum(out, tile_a, tile_b)`` -> tile-tile
        - ``minimum(out, tile_a, scalar)`` -> tile-scalar

    With ``dim`` (reduce): min reduction along the specified dimension.
        - ``minimum(out, src, tmp, dim=0)`` -> row-wise min (last axis)
        - ``minimum(out, src, tmp, dim=1)`` -> column-wise min (first axis)

    Args:
        out: Destination Tile
        lhs: Source Tile (or left operand in element-wise mode)
        rhs: Right operand — Tile/Scalar in element-wise mode, or workspace
             Tile in reduce mode
        dim: Reduction dimension — None=element-wise, 0=row, 1=column
    """


@_api_decl
def maximum(out: Tile, lhs: Tile, rhs: Union[Tile, int, float], *, dim: Optional[int] = None) -> None:
    """Element-wise maximum or dimension-wise max reduction.

    Without ``dim`` (element-wise): ``out = max(lhs, rhs)``
        - ``maximum(out, tile_a, tile_b)`` -> tile-tile
        - ``maximum(out, tile_a, scalar)`` -> tile-scalar

    With ``dim`` (reduce): max reduction along the specified dimension.
        - ``maximum(out, src, tmp, dim=0)`` -> row-wise max (last axis)
        - ``maximum(out, src, tmp, dim=1)`` -> column-wise max (first axis)

    Args:
        out: Destination Tile
        lhs: Source Tile (or left operand in element-wise mode)
        rhs: Right operand — Tile/Scalar in element-wise mode, or workspace
             Tile in reduce mode
        dim: Reduction dimension — None=element-wise, 0=row, 1=column
    """


@_api_decl
def const(value: Union[int, float], dtype: DType, /) -> Scalar:
    """Create a typed compile-time constant.

    Args:
        value: Numeric literal (int or float, optionally preceded by a minus sign)
        dtype: Data type, e.g. ``pl.DT_INT32``, ``pl.DT_FP16``
    """


@_api_decl
def astype(x: Union[int, float], dtype: DType, /) -> Scalar:
    """Convert a runtime scalar expression to ``dtype``.

    Storage-only dtypes (FP8, FP4, HF8, HF4, INT4 and UINT4) are not supported
    as either the source or destination. For supported FP8/FP4 register
    conversions, use ``pl.Vf.astype``.

    Args:
        x: Source scalar expression
        dtype: Destination data type, e.g. ``pl.DT_INT32``
    """


# ===================================================================
# Section G: Control flow
# ===================================================================


def range(start: int, stop: Optional[int] = None, step: int = 1, /):
    """Loop iterator for ``for`` loops.

    Usage::

        for i in pl.range(10):          # 0..9
        for i in pl.range(0, 10, 2):    # 0, 2, 4, 6, 8
    """
    if stop is None:
        start, stop = 0, start
    return builtins.range(start, stop, step)


@contextmanager
def section_vector():
    """Context manager for a Vector-pipe section scope."""
    yield


@contextmanager
def section_cube():
    """Context manager for a Cube-pipe section scope."""
    yield


# ===================================================================
# Section H: Utility / system-level ops
# ===================================================================


@_api_decl
def get_block_idx() -> int:
    """Get the current block (AI Core) index."""


@_api_decl
def get_subblock_idx() -> int:
    """Get the current sub-block index (0 or 1)."""


@_api_decl
def dynamic_input_ptr(x: Ptr, i: int, /) -> Ptr:
    """Pointer to the i-th tensor carried by a runtime-variadic (DYNAMIC) input.

    ``x`` is the descriptor pointer the framework passes for a ``ParamType(DYNAMIC)``
    op (CANN ``folded_with_desc``); declare it as ``pl.Ptr[dtype]``.  ``i`` is the tensor
    index in ``[0, N)`` where N is the host-provided tensor count. The returned pointer's
    element type is the descriptor's element dtype; build a typed view with
    ``pl.make_tensor(dynamic_input_ptr(x, i), shape, stride, dtype=...)``, which also
    reinterprets the element type when a different ``dtype`` is given.

    Element widths: 8/16/32/64-bit elements use the matching C type. 4-bit elements are
    *packed two-per-byte*, so ``DT_FP4E2M1``/``DT_FP4E1M2`` map to ``float4_e2m1x2_t``/
    ``float4_e1m2x2_t`` (one element spans two values); ``DT_INT4``/``DT_UINT4``/``DT_FP4``/
    ``DT_HF4`` have no packed C type and are rejected when the op is lowered.
    """


@_api_decl
def dynamic_input_dim(x: Ptr, i: int, axis: int, /) -> Scalar:
    """Length of shape axis ``axis`` of the i-th tensor in a runtime-variadic (DYNAMIC) input.

    ``x`` is the descriptor pointer the framework passes for a ``ParamType(DYNAMIC)`` op;
    declare it as ``pl.Ptr[dtype]``.
    ``i`` is the tensor index; ``axis`` is an integer scalar expression (a compile-time constant
    or a runtime value) whose valid range ``[0, dim)`` is only known at run time, so an
    out-of-range axis is guarded on device. Only the ``dim != 0`` descriptor form carries
    shape; reads the layout directly (no AscendC dependency).
    """


@_api_decl
def get_block_num() -> int:
    """Get the launched worker block count after applying the stream's core limits.

    This can be smaller than the host's requested ``kernel[stream, block_dim]``.
    Use this runtime count as the work-distribution stride so limiting cores does
    not leave tiles unprocessed. Mixed Vector sections have this many blocks times
    ``get_subblock_num()`` vector workers.
    """


@_api_decl
def get_subblock_num() -> int:
    """Get the sub-block count per AI Core (task ration).

    Returns 1 on AIC binaries, get_subblockdim() on AIV binaries.
    Matches AscendC GetTaskRation().
    """


@_api_decl
def get_spr() -> int:
    """Read a special purpose register value (get_ar instruction).

    Currently only the AR register is supported. The AR register stores
    the total byte count of valid elements produced by Squeeze.

    ``get_ar()`` is an ``__aicore__`` instruction and cannot be used inside
    ``@pl.vector_function``. Call this in the ``@pl.jit`` kernel body.

    Returns:
        int64_t scalar value from the SPR
    """


@_api_decl
def get_cycle() -> int:
    """Read the device system cycle counter (get_sys_cnt instruction).

    Returns the current value of the AI Core system counter. The counter runs
    at 1000MHz on 3510, so use differences between two reads to measure
    elapsed cycles.

    ``get_sys_cnt()`` is an ``__aicore__`` instruction and cannot be used
    inside ``@pl.vector_function``. Call this in the ``@pl.jit`` kernel body.

    Returns:
        int64_t scalar value of the system cycle counter
    """


@_api_decl
def set_saturation_flag(*, mode: SaturationFlagMode, enable: bool) -> None:
    """Set the saturation flag in the CTRL special purpose register.

    Controls the global saturation mode for Cast (vcvt) and other
    vector compute instructions. Must be called outside
    ``@pl.vector_function`` (in the ``@pl.jit`` kernel body),
    before the ``pl.section_vector()`` block that uses ``vf.astype``
    with the corresponding saturation mode.

    Args:
        mode: Saturation mode category, one of:

            - ``pl.SaturationFlagMode.FLOAT`` — float compute/convert (CTRL bit 48)
            - ``pl.SaturationFlagMode.FLOAT8`` — float8 compute (CTRL bit 50)
            - ``pl.SaturationFlagMode.INT`` — int compute (CTRL bit 53)
            - ``pl.SaturationFlagMode.CAST`` — float→int / int→int convert (CTRL bit 59)

        enable: ``True`` to enable saturation (clamp to target type's
            min/max), ``False`` to disable (truncate).
    """


@_api_decl
def get_saturation_flag(*, mode: SaturationFlagMode) -> bool:
    """Read the saturation flag from the CTRL special purpose register.

    Returns the current saturation state for the given mode category.
    Must be called outside ``@pl.vector_function``.

    Args:
        mode: Saturation mode category (same as ``set_saturation_flag``).

    Returns:
        ``True`` if saturation is enabled, ``False`` otherwise.
    """


@_api_decl
def set_ctrl_spr(start_bit: int, end_bit: int, value: int, /) -> None:
    """Set a bit range in the CTRL special purpose register.

    Writes ``value`` into the CTRL register bits ``[start_bit, end_bit]``,
    preserving all other bits. This is the low-level counterpart to
    ``set_saturation_flag`` — use it when direct CTRL bit manipulation
    is needed (e.g., setting the global override bit CTRL[60]).

    Must be called outside ``@pl.vector_function``.

    Args:
        start_bit: Start bit index (0-63), compile-time constant.
        end_bit: End bit index (0-63), compile-time constant.
            Writable bits on 3510: 6-10, 45, 48, 50, 53, 59, 60.
        value: Value to write into the bit range.
    """


@_api_decl
def get_ctrl_spr(start_bit: int, end_bit: int, /) -> int:
    """Read a bit range from the CTRL special purpose register.

    Returns the value of CTRL register bits ``[start_bit, end_bit]``.
    Must be called outside ``@pl.vector_function``.

    Args:
        start_bit: Start bit index (0-63), compile-time constant.
        end_bit: End bit index (0-63), compile-time constant.

    Returns:
        int64_t value of the extracted bit range.
    """


@_api_decl
def reset_ctrl_spr(start_bit: int, end_bit: int, /) -> None:
    """Reset a bit range in the CTRL register to default values.

    Restores CTRL register bits ``[start_bit, end_bit]`` to their
    hardware default (CTRL default = 0x1000000000000008).
    Must be called outside ``@pl.vector_function``.

    Args:
        start_bit: Start bit index (0-63), compile-time constant.
        end_bit: End bit index (0-63), compile-time constant.
            Writable bits on 3510: 6-10, 45, 48, 50, 53, 59, 60.
    """


@_api_decl
def array(size: int, /, *, dtype: DType) -> Array:
    """Declare a fixed-length, mutable kernel-local array of scalars.

    The storage is uninitialized: write every element before reading it. The
    element dtype and length are part of the IR type, so they are fixed at
    compile time. Each call creates independent storage; assigning the array to
    another name aliases the same storage.

    Args:
        size: Positive compile-time element count
        dtype: Explicit supported scalar element dtype, e.g. ``pl.DT_INT32``

    Example::

        datas = pl.array(8, dtype=pl.DT_INT32)
        datas[0] = 7
        a = datas[0]          # captures the int32 value 7
        alias = datas         # same storage
        alias[0] = 9
        datas[1] = a          # datas[0] is 9, datas[1] is 7
    """


@_api_decl
def make_tile(
    tile_type: TileType,
    /,
    *,
    addr: int,
) -> Tile:
    """Place one Tile at a fixed address in the memory space its type names.

    The Tile's shape, dtype, memory space and layout all come from ``tile_type``;
    this call binds it to an address range whose byte span is derived from the
    shape and dtype. For several Tiles of one type
    rotating through a ping-pong buffer, use ``pl.make_tile_group``.

    ``tile_type`` is the only positional argument; ``addr`` is keyword-only.

    Args:
        tile_type: ``pl.TileType`` descriptor — the only accepted spelling of the
            Tile's shape/dtype/memory space/layout
        addr: Required byte offset within the memory space. Fixed at parse time,
            and aligned to that space (32B Vec/Mat, 512B Left/Right, 64B Acc/Bias,
            128B Scaling)
    Example::

        tt = pl.TileType(shape=[64, 128], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Vec)
        tile_a = pl.make_tile(tt, addr=0x0000)           # size derived: 64 * 128 * 2
    """


@_api_decl
def make_tile_group(*, type: TileType, addrs: int | list,
    mutex_ids: str | list[int | list[int] | tuple[int, ...]] | tuple | None = None,
    depth: int | None = None,
    fwd_ids: list[int] | tuple[int, ...] | None = None,
    bwd_ids: list[int] | tuple[int, ...] | None = None,
) -> Any:
    """Create a rotating Tile group with optional mutex metadata.

    The handle supports ``group.next()``, ``group.current()``,
    ``group.previous()``, and ``group[i]``. Configuring non-empty ``mutex_ids``
    requires ``@pl.jit(auto_mutex=True)`` to synchronize accesses automatically.

    Args:
        type: ``pl.TileType`` descriptor
        addrs: Base address for contiguous Tiles, or one address per Tile
        mutex_ids: ``"auto"`` for whole-group automatic allocation, a manual
            sequence, or None/empty for user-managed synchronization. Each
            manually configured Tile may use one int or a non-empty list/tuple.
            Every Tile must use the same mutex ID count, with no duplicates for
            one Tile
        depth: Number of Tiles. Required when ``mutex_ids`` is ``"auto"``, None,
            or empty; otherwise inferred from ``len(mutex_ids)``
        fwd_ids: Optional cross-core event IDs (0..15) marking this group as a
            producer->consumer channel for the automatic pipeline transform. One
            per Tile; the transform picks ``fwd_ids[i % N]`` per iteration
        bwd_ids: Optional cross-core event IDs for the consumer->producer
            direction (buffer released). Same shape as ``fwd_ids``
    """


# ===================================================================
# Section I: Type and pointer constructors
#
# These declarations describe calls the parser intercepts by name. The runtime
# objects they describe stay where they are -- ``pl.TileType`` is still the class
# from ``ir/op/block_ops.py`` and ``pl.addptr`` still the builder -- so they are
# deliberately absent from the re-exports in ``__init__.py``. What they add is a
# user-facing signature for the argument gate to bind against, with the
# framework-internal ``span`` parameter left out.
# ===================================================================


# The constructor returns the concrete descriptor; the alias avoids colliding
# with this declaration's public name.
@_api_decl
def TileType(  # noqa: N802 -- the user writes pl.TileType(...), a class constructor
    *,
    shape: Shape,
    dtype: DType,
    target_memory: MemorySpace = MemorySpace.Vec,
    valid_shape: Optional[Shape] = None,
    layout: Optional[Layout] = None,
    fractal: Optional[int] = None,
    pad: Optional[Union[TilePad, int]] = None,
    compact: Optional[int] = 1,
) -> TileType:
    """Describe a tile: its shape, dtype, memory space and layout.

    A TileType carries everything about a tile except where it lives, which
    ``pl.make_tile(tile_type, addr=...)`` supplies.

    Args:
        shape: Tile shape per axis
        dtype: Element data type, e.g. ``pl.DT_FP16``
        target_memory: On-chip memory space the tile occupies
        valid_shape: Optional smaller shape actually holding data (not supported by conv-layout tiles)
        layout: Optional tensor layout (ND/DN/NZ/ZN/NN/ZZ), or a conv layout
            (NC1HWC0/NDC1HWC0/FRACTAL_Z/FRACTAL_Z_3D) for a multi-dim L1 ConvTile
        fractal: Optional fractal size (not supported by conv-layout tiles)
        pad: Optional padding mode, a ``pl.TilePad`` or the integer 0/1/2/3 standing for one
            (not supported by conv-layout tiles)
        compact: Optional compact flag (conv-layout tiles are always normal mode)
    """


@_api_decl
def Img2ColConfig(  # noqa: N802 -- the user writes pl.Img2ColConfig(...), a class constructor
    *,
    kernel: Shape,
    stride: Shape,
    dilation: Shape,
    padding: Shape,
    pad_value: int = 0,
) -> Any:
    """Describe the img2col window geometry for ``pl.img2col``.

    kernel/stride/dilation/pad_value are compile-time constants baked into the
    img2col call. padding entries are constant ints or runtime integer scalars
    (list length stays 4); runtime entries reach the fmatrix pad registers at
    run time, so their values cannot be range-checked while building the IR.

    Args:
        kernel: Convolution window ``[kernel_h, kernel_w]``, each in [1, 255]
        stride: Window slide ``[stride_h, stride_w]``, each in [1, 63]
        dilation: Window dilation ``[dilation_h, dilation_w]``, each in [1, 63]
        padding: Feature-map border fill ``[pad_top, pad_bottom, pad_left, pad_right]``,
            each a constant in [0, 255] or a runtime integer scalar
        pad_value: Optional fill value written outside the feature map, an
            integer (default 0)
    """


@_api_decl
def addptr(ptr: Ptr, offset: int) -> Ptr:
    """Advance a raw pointer by an integer offset.

    Args:
        ptr: Raw pointer expression (``pl.Ptr[dtype]``)
        offset: Element offset, an int or an integer scalar expression
    """


@_api_decl
def make_ptr(ptr: Union[Ptr, Tensor], dtype: Optional[DType] = None) -> Ptr:
    """Extract a raw pointer from a Tensor, or reinterpret a pointer's element dtype.

    Args:
        ptr: A ``pl.Tensor`` to take the data pointer of, or a ``pl.Ptr[dtype]`` to recast
        dtype: Optional element type for the result
    """


@_api_decl
def tensor_view(
    tensor: Tensor,
    offset: Offset | int,
    shape: Shape,
) -> Tensor:
    """Create a no-copy sub-view of an existing GM tensor.

    The view shares the source tensor's storage: it starts at element
    coordinates ``offset`` and covers ``shape`` elements, keeping the source's
    dtype and strides. Nothing is copied — codegen rebases the tensor's data
    pointer and re-declares the access shape, exactly as
    ``pl.make_tensor(pl.addptr(pl.make_ptr(tensor), offset), shape, stride)``
    would.

    Args:
        tensor: Existing GM tensor — a kernel parameter or another view
        offset: Per-axis element coordinates (one per source axis), or a scalar
            linear element offset (row-major)
        shape: Extent of the sub-view per axis, same rank as the source
    """


@_api_decl
def make_tensor(
    ptr: Union[Ptr, Tensor],
    shape: Shape,
    stride: Optional[Shape] = None,
    dtype: Optional[DType] = None,
) -> Tensor:
    """Create a Tensor view over a raw pointer or an existing Tensor.

    Args:
        ptr: A ``pl.Ptr[dtype]`` or an existing ``pl.Tensor``
        shape: Shape of the view per axis
        stride: Optional stride per axis; contiguous when omitted
        dtype: Optional element type for the view
    """