"""
hls.py -- a toy high-level-synthesis (HLS) engine: trace a kernel, schedule it, bind it, pipeline it, cost it
===========================================================================================================

[Why we need it]
    An HLS tool turns a C++ function into hardware (register-transfer level, RTL). Between the C++ and the RTL it
    makes four decisions, and the quality of the hardware depends on all four:
        ALLOCATION  how many functional units (adders, multipliers, memory ports) to build;
        SCHEDULING  in which clock cycle each operation runs;
        BINDING     on which unit instance each operation runs, and in which register each value lives;
        PIPELINING  how often a loop can start a new iteration (the initiation interval, II).
    Real tools (Vitis HLS, Catapult, Stratus, ...) hide these decisions behind reports. This module makes each of
    them visible on kernels small enough to read in full:
    1. TRACING   a kernel is written as ordinary Python: `acc = acc + a[i] * b[i]`. Operator overloading records
                 every +, *, load and store into a dataflow graph (DFG) instead of computing a number -- the same
                 graph an HLS front end builds from C++.
    2. SCHEDULING  asap(), alap(), mobility; resource-constrained list scheduling (list_schedule()).
    3. BINDING   the list scheduler assigns unit instances; area_report() counts the registers (from value
                 lifetimes) and the multiplexers that sharing a unit requires.
    4. PIPELINING  modulo_schedule(): the lower bounds ResMII (resources) and RecMII (loop-carried recurrences),
                 then a modulo-reservation-table scheduler that finds an II.
    5. COST      area of functional units, registers, multiplexers and memory banks (45 nm, µm^2), energy per run.
    Every kernel can also be EVALUATED on numbers (evaluate(), run_loop()), so a restructured kernel (a reduction
    tree, interleaved accumulators, a look-ahead recurrence) can be checked against the original.

[Usage]
    import hls
    k = hls.Kernel("dot8", dtype="fp32")
    a, b = k.array("a", 8), k.array("b", 8)
    k.output("y", hls.reduce_sum([a[i] * b[i] for i in range(8)], style="tree"))
    s = hls.list_schedule(k, {"mul": 1, "add": 1})
    print(s.latency, hls.area_report(s)["total"])

    body = hls.dot_product_body(unroll=1, partition=1, accumulators=1)      # one iteration of a loop
    m = hls.modulo_schedule(body)                                           # m.ii, m.depth
    hls.loop_cycles(m, trips=256)                                           # (trips - 1) * II + depth

[The hardware model, in brief]
    - Each operation has a LATENCY in cycles (LIBRARY below; e.g. an fp32 add takes 4 cycles at the assumed clock)
      and either is PIPELINED (the unit accepts a new operation every cycle) or occupies its unit for its whole
      latency (the divider).
    - No chaining: every operation starts at a clock edge and its result is available `latency` cycles later.
    - An on-chip array is one or more SRAM BANKS; each bank serves `ports` accesses per cycle. A cyclic partition
      by P puts element i into bank i mod P. A partition with P >= size turns the array into registers (any number
      of reads per cycle).
    - Area = units + registers + multiplexers + memory. Unit areas are Horowitz's 45 nm numbers; registers,
      multiplexers and SRAM cells are assumptions of these notes (constants below, each with its reason).

[Edge cases and simplifications]
    - Dependences through memory are tracked only WITHIN one execution of the kernel (one loop iteration) and only
      between accesses with the same constant offset. Real tools also analyze dependences between iterations;
      the example kernels never create one that matters (the line buffer's distance is a whole image row).
    - The modulo scheduler does not backtrack (Rau's iterative modulo scheduling does): if an operation does not
      fit, it tries the next II. On the kernels of this lecture it reaches MII except where the notes say so.
    - Loop control (the counter and exit test) is not modeled; tools typically add ~1 cycle of latency per loop.
"""

import math
from dataclasses import dataclass, field

import course_path

course_path.use("lecture01")

from energy_model import op_area_um2, op_energy_pj, sram_pj_per_byte  # noqa: E402  (after course_path)

# =====================================================================================================================
# The component library: latency, pipelining, area and energy of every operation
# =====================================================================================================================

# [Hardware link] An HLS tool characterizes its library for the target technology and clock: an fp32 adder that
#     fits in 4 pipeline stages at 1 GHz may need 7-11 stages on an FPGA at 300 MHz. The latencies below are
#     ASSUMPTIONS of these notes, typical of an ASIC library at ~1 GHz; areas and energies are Horowitz's 45 nm
#     numbers (Lecture 1, energy_model.py) except where marked "assumed".


@dataclass(frozen=True)
class OpSpec:
    """
    How one kind of operation is implemented in hardware.

    [Fields]
        fu        : the functional-unit class it runs on ("add", "mul", "div"); sub shares the adder
        latency   : cycles from the start of the operation to its result
        pipelined : True = the unit can start a new operation every cycle (initiation interval 1);
                    False = the unit is busy for `latency` cycles (an iterative divider)
        area_um2  : area of one unit instance
        energy_pj : energy of one operation
        bits      : width of the result (decides register and multiplexer widths)
    """
    fu: str
    latency: int
    pipelined: bool
    area_um2: float
    energy_pj: float
    bits: int


LIBRARY = {
    # fp32: Horowitz's fp32 adder (4184 µm², 0.9 pJ) and multiplier (7700 µm², 3.7 pJ).
    "fp32": {
        "add": OpSpec("add", 4, True, op_area_um2("fp", "add", 32), op_energy_pj("fp", "add", 32), 32),
        "sub": OpSpec("add", 4, True, op_area_um2("fp", "add", 32), op_energy_pj("fp", "add", 32), 32),
        "mul": OpSpec("mul", 3, True, op_area_um2("fp", "mult", 32), op_energy_pj("fp", "mult", 32), 32),
        # assumed: an iterative (radix-2-like) divider: 12 cycles, NOT pipelined, a multiplier-sized datapath,
        # energy = 12 cycles of that datapath's multiplier energy.
        "div": OpSpec("div", 12, False, op_area_um2("fp", "mult", 32), 12 * op_energy_pj("fp", "mult", 32), 32),
    },
    # int8 inputs, int32 accumulation (the usual ML integer datapath): an 8-bit multiplier (282 µm², 0.2 pJ) whose
    # 16-bit product feeds a 32-bit adder (137 µm², 0.1 pJ). Both fit in one cycle at the assumed clock.
    "int8": {
        "add": OpSpec("add", 1, True, op_area_um2("int", "add", 32), op_energy_pj("int", "add", 32), 32),
        "sub": OpSpec("add", 1, True, op_area_um2("int", "add", 32), op_energy_pj("int", "add", 32), 32),
        "mul": OpSpec("mul", 1, True, op_area_um2("int", "mult", 8), op_energy_pj("int", "mult", 8), 16),
    },
}
INPUT_BITS = {"fp32": 32, "int8": 8}       # width of loaded/input elements

MEM_LATENCY = 1               # an SRAM read returns its data one cycle after the address is presented
REG_UM2_PER_BIT = 4.5         # assumed: one flip-flop ~ a 45 nm D flip-flop cell (NanGate FreePDK45 DFF_X1 ~4.5 µm²)
MUX2_UM2_PER_BIT = 1.9        # assumed: one 2:1 multiplexer bit ~ a 45 nm MUX2 cell (~1.9 µm²)
SRAM_UM2_PER_BIT = 0.7        # assumed, as in Lecture 1: 6T cell + amortized periphery of a large array
BANK_OVERHEAD_UM2 = 2500.0    # assumed: fixed periphery (decoders, sense amplifiers, IO) that EVERY extra bank pays
EXTRA_PORT_FACTOR = 0.5       # assumed: each port beyond the first adds 50% to a bank's area (bigger cell, 2nd periphery)

UNLIMITED = None              # a resource limit of None means "as many units as the schedule wants"


# =====================================================================================================================
# Tracing: kernels written in Python become dataflow graphs
# =====================================================================================================================

@dataclass
class Node:
    """
    One node of the dataflow graph.

    [Fields]
        id     : position in the kernel (nodes are created in program order, which is a valid topological order)
        kind   : "input", "const", "carried", "load", "store", "output", or an operation ("add", "sub", "mul", "div")
        args   : ids of the operand nodes (data dependences)
        label  : short name shown in schedules ("*3", "+1", "a[3]")
        bits   : width of the value it produces
        array  : the Array of a load or store; offset: its element offset
        value  : the constant of a "const" node; name: the name of an input/output/carried node
        deps   : extra ordering constraints through memory: list of (node id, minimum distance in cycles)
        source : for a "carried" node, the node that produces its value in the previous iteration
    """
    id: int
    kind: str
    args: list
    label: str
    bits: int
    array: object = None
    offset: int = 0
    value: object = None
    name: str = ""
    deps: list = field(default_factory=list)
    source: int = None


class Value:
    """
    A traced value: a handle on the node that produces it.

    [Idea] Arithmetic on Values does not compute anything; it adds a node to the kernel's graph and returns a
        Value for the new node. Plain Python numbers mixed into the arithmetic become constant nodes.
    [Python tip] Python calls a.__add__(b) for `a + b` and b.__radd__(a) for `3 + b` (when the left operand is a
        plain number that does not know how to add a Value). Defining these "dunder" methods is called operator
        overloading; it is how numpy arrays, PyTorch tensors and this tracer make `+` mean something new.
    """

    def __init__(self, kernel, node_id):
        self.k = kernel
        self.id = node_id

    def __add__(self, other):
        return self.k._binop("add", self, other)

    def __radd__(self, other):
        return self.k._binop("add", other, self)

    def __sub__(self, other):
        return self.k._binop("sub", self, other)

    def __rsub__(self, other):
        return self.k._binop("sub", other, self)

    def __mul__(self, other):
        return self.k._binop("mul", self, other)

    def __rmul__(self, other):
        return self.k._binop("mul", other, self)

    def __truediv__(self, other):
        return self.k._binop("div", self, other)


class Array:
    """
    An on-chip array (C++: `float a[256];`), stored in one or more SRAM banks.

    [Args]
        size      : number of elements
        partition : number of banks (cyclic: element i lives in bank i mod partition); partition >= size turns the
                    array into registers (HLS "complete partition")
        ports     : accesses each bank serves per cycle (1 = single-port SRAM, 2 = dual-port)
        bits      : element width
    [Indexing] Inside an ordinary kernel, a[i] is element i. Inside a LOOP BODY (Kernel(loop_stride=S)), a[off]
        means element (S * iteration + off) mod size: the body describes iteration `iteration` of a loop whose
        index advances by S elements per iteration (S = the unroll factor). The "mod size" lets a small array act
        as a circular buffer (the line buffer of a convolution).
    [Banks in a pipelined loop] Access `off` of iteration i reads element S*i + off, i.e. bank (S*i + off) mod P.
        If P divides S, that is off mod P in every iteration: each access has a FIXED bank. Otherwise the bank
        ROTATES from iteration to iteration and the hardware needs a crossbar (multiplexers) between the access
        ports and the banks, which mux_bits() charges for. Two accesses that run in the same cycle hit the same bank
        iff their "bank keys" (off - S * stage) mod P are equal, where stage = start // II says which iteration
        is executing that operation (see port_class); this is exact for affine accesses, so the scheduler can
        avoid every conflict.
    [Edge cases] partition is capped at size. A register array has no port limit and reads take 0 cycles (the
        value is already in a register).
    """

    def __init__(self, kernel, name, size, partition=1, ports=1, bits=32):
        if size < 1 or partition < 1 or ports < 1:
            raise ValueError("size, partition and ports must be >= 1")
        self.k, self.name, self.size, self.ports, self.bits = kernel, name, size, ports, bits
        self.partition = min(partition, size)
        self.is_registers = partition >= size

    @property
    def rotates(self):
        """True if, in a loop body, the bank of an access changes from iteration to iteration (P does not divide S)."""
        return (not self.is_registers and self.k.loop_stride is not None
                and self.k.loop_stride % self.partition != 0)

    def bank_key(self, offset, stage=0):
        """
        Bank key of an access (0 .. partition-1): two accesses in the same cycle conflict iff their keys are equal.

        [Args] offset: the access's offset; stage: start cycle // II of the access in a modulo schedule (0 for
            straight-line code or a non-pipelined loop)
        [Returns] int, or None for a register array (no port limit)
        """
        if self.is_registers:
            return None
        stride = self.k.loop_stride or 0
        return (offset - stride * stage) % self.partition

    def port_class(self, offset, stage=0):
        """Name of the resource an access uses, e.g. "a.b2" (bank key 2 of array a); None = unconstrained."""
        key = self.bank_key(offset, stage)
        return None if key is None else f"{self.name}.b{key}"

    def bank_bytes(self):
        """Capacity of one bank in bytes."""
        return math.ceil(self.size / self.partition) * self.bits / 8

    def area_um2(self):
        """
        Area of the storage: register bits for a register array; otherwise every bank pays its cells and a fixed
        periphery (BANK_OVERHEAD_UM2), which is why splitting an array into many banks is not free, and every
        port beyond the first adds EXTRA_PORT_FACTOR of the area (a multi-port SRAM cell is larger).
        """
        if self.is_registers:
            return self.size * self.bits * REG_UM2_PER_BIT
        base = self.partition * BANK_OVERHEAD_UM2 + self.size * self.bits * SRAM_UM2_PER_BIT
        return base * (1 + EXTRA_PORT_FACTOR * (self.ports - 1))

    def __getitem__(self, offset):
        return self.k._load(self, offset)

    def __setitem__(self, offset, value):
        self.k._store(self, offset, value)


class Kernel:
    """
    A kernel being traced: the dataflow graph of one function (or of one iteration of a loop).

    [Args]
        name        : label for reports
        dtype       : "fp32" or "int8" (selects the LIBRARY entry and the evaluation arithmetic)
        loop_stride : None for a straight-line kernel; for a loop body, the number of elements the loop index
                      advances per iteration (the unroll factor). See Array for how offsets are interpreted.
    [Methods for building] input(), const(), array(), carried(), carry(), output(); arithmetic on Values;
        a[i] (load) and a[i] = v (store).
    [Edge cases] Nodes are appended in program order, so every node's operands have smaller ids; the schedulers
        rely on this (it is a topological order for free).
    """

    def __init__(self, name, dtype="fp32", loop_stride=None):
        if dtype not in LIBRARY:
            raise ValueError(f"unknown dtype {dtype!r}; choose one of {sorted(LIBRARY)}")
        self.name, self.dtype, self.loop_stride = name, dtype, loop_stride
        self.lib = LIBRARY[dtype]
        self.nodes = []
        self.arrays = {}
        self._counts = {}
        self._last_store = {}      # (array name, offset) -> id of the last store (for read-after-write)
        self._loads_since = {}     # (array name, offset) -> loads since that store (for write-after-read)

    # ---- building blocks ----------------------------------------------------------------------------------------

    def _new(self, kind, args, label, bits, **kw):
        node = Node(len(self.nodes), kind, list(args), label, bits, **kw)
        self.nodes.append(node)
        return Value(self, node.id)

    def _auto_label(self, prefix):
        n = self._counts.get(prefix, 0)
        self._counts[prefix] = n + 1
        return f"{prefix}{n}"

    def _as_value(self, x):
        """Turn a Python number into a constant node; pass Values through."""
        if isinstance(x, Value):
            if x.k is not self:
                raise ValueError("a Value from another kernel was used")
            return x
        return self.const(x)

    def _binop(self, kind, a, b):
        if kind not in self.lib:
            raise KeyError(f"operation {kind!r} is not in the {self.dtype} library")
        a, b = self._as_value(a), self._as_value(b)
        symbol = {"add": "+", "sub": "-", "mul": "*", "div": "/"}[kind]
        return self._new(kind, [a.id, b.id], self._auto_label(symbol), self.lib[kind].bits)

    def input(self, name):
        """A scalar argument of the kernel (held in a register; available at cycle 0)."""
        return self._new("input", [], name, INPUT_BITS[self.dtype], name=name)

    def const(self, value):
        """A constant (wired into the datapath; no unit, no latency, no area)."""
        return self._new("const", [], f"{value:g}", INPUT_BITS[self.dtype], value=value)

    def array(self, name, size, partition=1, ports=1, bits=None):
        """Declare an on-chip array; see Array. Returns the Array (index it to load or store)."""
        if name in self.arrays:
            raise ValueError(f"array {name!r} declared twice")
        arr = Array(self, name, size, partition, ports, bits or INPUT_BITS[self.dtype])
        self.arrays[name] = arr
        return arr

    def carried(self, name, init=0):
        """
        A loop-carried value: inside one iteration it holds what carry() assigned in the PREVIOUS iteration
        (C++: a variable declared outside the loop, like `acc`). init is its value in iteration 0.
        """
        bits = self.lib["add"].bits
        return self._new("carried", [], name, bits, name=name, value=init)

    def carry(self, carried_value, new_value):
        """Declare that `new_value` (computed in this iteration) becomes `carried_value` in the next one."""
        node = self.nodes[carried_value.id]
        if node.kind != "carried":
            raise ValueError("carry() needs a value created by carried()")
        if node.source is not None:
            raise ValueError(f"carried value {node.name!r} already has a source")
        node.source = self._as_value(new_value).id

    def output(self, name, value):
        """Mark a value as a result of the kernel (a write to an output port/register)."""
        v = self._as_value(value)
        return self._new("output", [v.id], f"out:{name}", self.nodes[v.id].bits, name=name)

    def _load(self, arr, offset):
        key = (arr.name, offset)
        deps = [(self._last_store[key], 1)] if key in self._last_store else []   # read after write
        v = self._new("load", [], f"{arr.name}[{offset}]", arr.bits, array=arr, offset=offset, deps=deps)
        self._loads_since.setdefault(key, []).append(v.id)
        return v

    def _store(self, arr, offset, value):
        key = (arr.name, offset)
        v = self._as_value(value)
        deps = [(i, 0) for i in self._loads_since.get(key, [])]                    # write after read
        if key in self._last_store:
            deps.append((self._last_store[key], 1))                                # write after write
        s = self._new("store", [v.id], f"{arr.name}[{offset}]=", arr.bits, array=arr, offset=offset, deps=deps)
        self._last_store[key] = s.id
        self._loads_since[key] = []
        return s

    # ---- properties used by the schedulers ------------------------------------------------------------------------

    def latency_of(self, node):
        """Cycles from the start of a node to its result (0 for inputs, constants, carried values, outputs)."""
        if node.kind in self.lib:
            return self.lib[node.kind].latency
        if node.kind == "load" and node.array.is_registers:
            return 0                                     # reading a register is just a wire
        if node.kind in ("load", "store"):
            return MEM_LATENCY
        return 0

    def resource_of(self, node, t=0, ii=None):
        """
        The resource class a node occupies ("add", "mul", "a.b0", ...) or None if it needs none.
        [Args] t, ii: the start cycle and the II of a modulo schedule (memory bank keys depend on the stage t // ii)
        """
        if node.kind in self.lib:
            return self.lib[node.kind].fu
        if node.kind in ("load", "store"):
            return node.array.port_class(node.offset, t // ii if ii else 0)
        return None

    def occupancy_of(self, node):
        """Cycles a node keeps its unit busy: 1 for pipelined units and memory ports, `latency` otherwise."""
        if node.kind in self.lib and not self.lib[node.kind].pipelined:
            return self.lib[node.kind].latency
        return 1

    def capacity(self, cls, resources):
        """How many instances of class `cls` exist: memory ports from the arrays, units from `resources`."""
        if "." in cls:                                      # a memory bank, e.g. "a.b0"
            return self.arrays[cls.split(".")[0]].ports
        if resources is None:
            return UNLIMITED
        return resources.get(cls, UNLIMITED)

    def preds(self, node):
        """Intra-iteration predecessors as (node id, minimum distance in cycles)."""
        out = [(a, self.latency_of(self.nodes[a])) for a in node.args]
        return out + list(node.deps)

    def carried_edges(self):
        """
        Loop-carried dependences as (producer id, consumer id, latency, distance in iterations).

        [Idea] A consumer of carried value c depends on c's source from `distance` iterations earlier. Chains of
            carried values (c1 <- c2 <- x, a shift register) add up their distances: the consumer of c1 waits for
            x computed two iterations ago.
        """
        edges = []
        for node in self.nodes:
            for a in node.args:
                src = self.nodes[a]
                if src.kind != "carried":
                    continue
                dist = 0
                while src.kind == "carried":
                    if src.source is None:
                        raise ValueError(f"carried value {src.name!r} was never given a source with carry()")
                    dist += 1
                    src = self.nodes[src.source]
                edges.append((src.id, node.id, self.latency_of(src), dist))
        return edges

    def count(self, kind):
        """Number of nodes of one kind."""
        return sum(n.kind == kind for n in self.nodes)


def reduce_sum(values, style="tree"):
    """
    Sum a list of traced Values.

    [Idea] A sum can be written as a CHAIN ((((v0 + v1) + v2) + v3) ...: depth n-1 adders, what a `for` loop with
        `acc += ...` produces) or as a balanced TREE ((v0 + v1) + (v2 + v3)): depth log2(n). Both use n-1 adders;
        the tree's critical path is much shorter.
    [Args] values: non-empty list of Values (or numbers); style: "chain" or "tree"
    [Returns] a Value
    [Edge cases] One value is returned unchanged. For floating point the two orders round differently: an HLS
        tool must NOT turn a chain into a tree on its own, because that would change the result (integer sums are
        associative, so tools may rebalance them).
    """
    vals = list(values)
    if not vals:
        raise ValueError("reduce_sum needs at least one value")
    if style == "chain":
        acc = vals[0]
        for v in vals[1:]:
            acc = acc + v
        return acc
    if style != "tree":
        raise ValueError("style must be 'chain' or 'tree'")
    while len(vals) > 1:
        nxt = [vals[i] + vals[i + 1] for i in range(0, len(vals) - 1, 2)]
        if len(vals) % 2:
            nxt.append(vals[-1])
        vals = nxt
    return vals[0]


# =====================================================================================================================
# Scheduling without resource limits: ASAP, ALAP, mobility
# =====================================================================================================================

def asap(k):
    """
    As-soon-as-possible schedule: every node starts as soon as all its operands are ready.

    [Returns] dict node id -> start cycle. Its length (max start + latency) is the CRITICAL PATH: no amount of
        hardware can make the kernel faster than that.
    [Edge cases] Ignores resource limits and loop-carried edges (one iteration on its own).
    """
    start = {}
    for node in k.nodes:
        start[node.id] = max((start[p] + d for p, d in k.preds(node)), default=0)
    return start


def schedule_length(k, start):
    """Cycle in which the last node finishes (max over nodes of start + latency)."""
    return max((start[n.id] + k.latency_of(n) for n in k.nodes), default=0)


def alap(k, bound=None):
    """
    As-late-as-possible schedule: every node starts as late as it can while the kernel still finishes by `bound`.

    [Args] bound: total latency to meet; default = the ASAP length (the critical path)
    [Returns] dict node id -> start cycle
    [Edge cases] With a bound shorter than the critical path some start times become negative (the bound is
        infeasible); the function does not complain because list scheduling only uses ALAP times as priorities.
    """
    if bound is None:
        bound = schedule_length(k, asap(k))
    succs = {n.id: [] for n in k.nodes}
    for n in k.nodes:
        for p, d in k.preds(n):
            succs[p].append((n.id, d))
    start = {}
    for node in reversed(k.nodes):
        latest = bound - k.latency_of(node)
        for s, d in succs[node.id]:
            latest = min(latest, start[s] - d)
        start[node.id] = latest
    return start


def mobility(k):
    """ALAP - ASAP start of every node: how many cycles it can slide without lengthening the critical path."""
    a, b = asap(k), alap(k)
    return {i: b[i] - a[i] for i in a}


# =====================================================================================================================
# Schedules, resource-constrained list scheduling, binding
# =====================================================================================================================

@dataclass
class Schedule:
    """
    The result of scheduling a kernel.

    [Fields]
        kernel    : the Kernel
        start     : node id -> start cycle
        binding   : node id -> (resource class, instance index) for nodes that occupy a unit or a memory port
        resources : the limits it was scheduled under (None = unlimited)
        ii        : initiation interval for a pipelined loop body (None for a straight-line schedule)
        mii       : (ResMII, RecMII) lower bounds, for modulo schedules
    [Properties] latency (= depth for a loop body): cycles until the last node finishes; units: instances used.
    """
    kernel: Kernel
    start: dict
    binding: dict
    resources: dict = None
    ii: int = None
    mii: tuple = None

    @property
    def latency(self):
        return schedule_length(self.kernel, self.start)

    depth = latency      # for a loop body, the latency of one iteration is called the pipeline DEPTH

    def units(self):
        """dict resource class -> number of instances actually used."""
        used = {}
        for cls, inst in self.binding.values():
            used[cls] = max(used.get(cls, 0), inst + 1)
        return used


def _free_instance(busy, cls, t, occ, cap, modulo=None):
    """
    Find an instance of class `cls` free during cycles t .. t+occ-1 (taken modulo `modulo` for a modulo schedule).

    [Args] busy: dict cls -> list of sets of occupied cycles (one set per instance); cap: max instances (None = any)
    [Returns] the instance index, or None if every allowed instance is busy
    [Edge cases] With cap = None a new instance is created when all existing ones are busy.
    """
    cycles = [(t + j) % modulo if modulo else t + j for j in range(occ)]
    if modulo and len(set(cycles)) < occ:       # an operation longer than II collides with itself
        return None
    insts = busy.setdefault(cls, [])
    for i, occupied in enumerate(insts):
        if not any(c in occupied for c in cycles):
            return i
    if cap is None or len(insts) < cap:
        insts.append(set())
        return len(insts) - 1
    return None


def list_schedule(k, resources=None):
    """
    Resource-constrained LIST SCHEDULING (the classic heuristic of HLS tools for straight-line code).

    [Idea] Walk through the cycles 0, 1, 2, ... In each cycle, collect the READY operations (all operands
        available), sort them by priority -- the operation with the earliest ALAP time has the least slack and goes
        first -- and start as many as there are free units. Operations that do not get a unit wait for the next
        cycle. Optimal scheduling under resource limits is NP-hard; list scheduling is fast and usually close.
    [Args]
        k         : a Kernel
        resources : dict unit class -> number of instances, e.g. {"mul": 1, "add": 2}; classes not listed (and
                    resources=None) are unlimited. Memory ports always come from the arrays (Array.ports per bank).
    [Returns] a Schedule (binding = the first free instance at the time of scheduling)
    [Edge cases] Nodes that need no unit (inputs, constants, outputs) are placed as soon as they are ready.
        Raises RuntimeError if an operation can never be placed (a resource class with 0 instances).
    """
    prio = alap(k)
    start, binding, busy = {}, {}, {}
    remaining = [n for n in k.nodes]
    t = 0
    limit = sum(k.latency_of(n) + k.occupancy_of(n) for n in k.nodes) + 10      # a safe upper bound on cycles
    while remaining:
        if t > limit:
            raise RuntimeError("list_schedule could not place every operation (a resource limit of 0?)")
        placed_free = True
        while placed_free:          # repeat within the cycle: a 0-latency node (input, register read) placed now
            placed_free = False     # makes its consumers ready in this same cycle
            ready = [n for n in remaining if n.id not in start
                     and all(p in start and start[p] + d <= t for p, d in k.preds(n))]
            ready.sort(key=lambda n: (prio[n.id], n.id))
            for n in ready:
                cls = k.resource_of(n)
                if cls is None:
                    start[n.id] = t
                    placed_free = placed_free or k.latency_of(n) == 0
                    continue
                inst = _free_instance(busy, cls, t, k.occupancy_of(n), k.capacity(cls, resources))
                if inst is None:
                    continue
                busy[cls][inst].update(range(t, t + k.occupancy_of(n)))
                start[n.id], binding[n.id] = t, (cls, inst)
        remaining = [n for n in remaining if n.id not in start]
        t += 1
    return Schedule(k, start, binding, resources)


def check_schedule(s):
    """
    Verify a schedule: every dependence respected; no unit instance used twice in the same cycle (or the same
    modulo slot); no class uses more instances than allowed. Raises AssertionError with a message if violated.
    [Returns] True
    """
    k = s.kernel
    for n in k.nodes:
        for p, d in k.preds(n):
            assert s.start[n.id] >= s.start[p] + d, f"{n.label} starts before its operand {k.nodes[p].label}"
    if s.ii:
        for u, v, lat, dist in k.carried_edges():
            assert s.start[v] >= s.start[u] + lat - s.ii * dist, \
                f"recurrence {k.nodes[u].label} -> {k.nodes[v].label} violated at II={s.ii}"
    seen = set()
    for nid, (cls, inst) in s.binding.items():
        n = k.nodes[nid]
        for j in range(k.occupancy_of(n)):
            c = s.start[nid] + j
            key = (cls, inst, c % s.ii if s.ii else c)
            assert key not in seen, f"{cls}#{inst} used twice in cycle/slot {key[2]}"
            seen.add(key)
    for cls, used in s.units().items():
        cap = k.capacity(cls, s.resources)
        assert cap is None or used <= cap, f"{cls}: {used} instances used, {cap} allowed"
    return True


# =====================================================================================================================
# Pipelining: ResMII, RecMII and modulo scheduling
# =====================================================================================================================

def res_mii(k, resources=None):
    """
    Resource-constrained minimum initiation interval.

    [Idea] If every iteration needs u slots of a resource class with c instances, iterations can start at most
        every ceil(u / c) cycles. Example: 3 loads per iteration from a single-port memory -> II >= 3.
    [Returns] (ResMII, the class that sets it); (1, None) when no resource limits anything
    [Edge cases] A non-pipelined unit counts its full latency per operation (a 12-cycle divider used once per
        iteration, with one divider, forces II >= 12). And because an operation is bound to the SAME instance in
        every iteration, a non-pipelined operation forces II >= its occupancy however many instances exist: a
        second divider helps only if the loop is unrolled so that two divisions per iteration can use one each.
    """
    use = {}
    best, which = 1, None
    for n in k.nodes:
        if n.kind in ("load", "store") and n.array.rotates:
            cls = n.array.name                           # rotating banks: count accesses per ARRAY (see below)
        else:
            cls = k.resource_of(n)
        if cls is not None:
            use[cls] = use.get(cls, 0) + k.occupancy_of(n)
            if k.occupancy_of(n) > best:
                best, which = k.occupancy_of(n), cls
    for cls, u in sorted(use.items()):
        if cls in k.arrays:                              # u accesses spread over partition x ports slots per cycle
            arr = k.arrays[cls]
            cap = arr.partition * arr.ports
        else:
            cap = k.capacity(cls, resources)
        if cap is not None and math.ceil(u / cap) > best:
            best, which = math.ceil(u / cap), cls
    return best, which


def _has_positive_cycle(k, ii):
    """Bellman-Ford on the constraint graph with weights latency - II * distance; True if some cycle is positive."""
    edges = [(p, n.id, d) for n in k.nodes for p, d in k.preds(n)]
    edges += [(u, v, lat - ii * dist) for u, v, lat, dist in k.carried_edges()]
    dist = {n.id: 0 for n in k.nodes}
    for _ in range(len(k.nodes)):
        changed = False
        for u, v, w in edges:
            if dist[u] + w > dist[v]:
                dist[v] = dist[u] + w
                changed = True
        if not changed:
            return False
    return True


def rec_mii(k):
    """
    Recurrence-constrained minimum initiation interval.

    [Idea] A loop-carried dependence cycle with total latency L spanning D iterations forces
        II >= ceil(L / D): iteration i+D cannot start its part of the cycle before iteration i has finished it.
        Example: acc = acc + x with a 4-cycle adder: L = 4, D = 1, so II >= 4.
        We find the smallest II for which the constraint graph (edge weight = latency - II * distance) has no
        positive cycle -- the standard test, which handles any number of interlocking cycles.
    [Returns] int RecMII, 0 if the kernel has no recurrence
    """
    if not k.carried_edges():
        return 0
    upper = sum(k.latency_of(n) for n in k.nodes) + 1
    for ii in range(1, upper + 1):
        if not _has_positive_cycle(k, ii):
            return ii
    return upper


def _try_modulo(k, ii, resources, graph):
    """
    One attempt of modulo scheduling at a fixed II (forward pass, backward pass, recurrence check).
    [Returns] (start, binding) or None if the operations do not fit at this II under these resources
    """
    carried_into, carried_out, succs = graph
    start, binding, busy = {}, {}, {}
    for n in k.nodes:                                     # forward pass: earliest free slot
        est = max((start[p] + d for p, d in k.preds(n)), default=0)
        for u, lat, dist in carried_into.get(n.id, []):
            if u in start:
                est = max(est, start[u] + lat - ii * dist)
        if k.resource_of(n) is None:
            start[n.id] = est
            continue
        occ = k.occupancy_of(n)
        for t in range(est, est + ii):
            cls = k.resource_of(n, t, ii)                 # a rotating memory bank depends on the stage t // ii
            inst = _free_instance(busy, cls, t, occ, k.capacity(cls, resources), modulo=ii)
            if inst is not None:
                busy[cls][inst].update((t + j) % ii for j in range(occ))
                start[n.id], binding[n.id] = t, (cls, inst)
                break
        else:
            return None
    for n in reversed(k.nodes):                           # backward pass: slide operations toward their consumers
        if n.id not in binding or not succs[n.id]:
            continue
        latest = min(start[c] - d for c, d in succs[n.id])
        for v, lat, dist in carried_out.get(n.id, []):
            latest = min(latest, start[v] + ii * dist - lat)
        if latest <= start[n.id]:
            continue
        occ, (cls0, inst0), t0 = k.occupancy_of(n), binding[n.id], start[n.id]
        busy[cls0][inst0].difference_update((t0 + j) % ii for j in range(occ))
        for t in range(latest, t0, -1):
            cls = k.resource_of(n, t, ii)
            cap = k.capacity(cls, resources)
            cap = len(busy.get(cls, [])) if cap is None else cap      # never add a unit just to move later
            inst = _free_instance(busy, cls, t, occ, cap, modulo=ii)
            if inst is not None:
                break
        else:                                             # no later slot is free: stay where it was
            t, cls, inst = t0, cls0, inst0
        busy[cls][inst].update((t + j) % ii for j in range(occ))
        start[n.id], binding[n.id] = t, (cls, inst)
    if all(start[v] >= start[u] + lat - ii * dist for u, v, lat, dist in k.carried_edges()):
        return start, binding
    return None


def modulo_schedule(k, resources=None, max_ii=None):
    """
    Schedule a loop body for PIPELINED execution: a new iteration starts every II cycles.

    [Idea] With iterations overlapping, an operation placed at cycle t uses its unit at t, t + II, t + 2 II, ...
        (one iteration each). A MODULO RESERVATION TABLE with II rows per resource records which slots t mod II
        are taken. We start from MII = max(ResMII, RecMII, 1) and, for each candidate II:
          0. ALLOCATION: a unit class not limited by `resources` gets the fewest units that can possibly work,
             ceil(uses per iteration / II) -- at II = 4, four multiplies per iteration need only one multiplier;
          1. FORWARD pass: place the operations in program order at the earliest cycle that respects their operands
             and has a free slot;
          2. BACKWARD pass: in reverse order, slide every operation as LATE as its consumers allow (if a slot is
             free there). An operation placed too early stretches a recurrence: in y = a*y_prev + x, starting the
             multiplication long before the add needs it makes the cycle from one iteration's add to the next
             iteration's add longer than necessary;
          3. check every loop-carried constraint start(v) >= start(u) + latency(u) - II * distance.
        If the minimal allocation does not fit, the same II is retried with the unlisted classes unlimited; if that
        fails too, II + 1.
    [Args] k: a loop-body Kernel; resources: as in list_schedule (classes listed there are hard limits);
        max_ii: give up beyond this (default: sum of all latencies + occupancies, where no overlap is left)
    [Returns] a Schedule with .ii, .mii = (ResMII, RecMII), .resources = the allocation used; .depth = latency of
        one iteration
    [Edge cases] No backtracking (see the module docstring): the II found can exceed MII when operations compete
        for a slot along a recurrence. The loop's total cycles are given by loop_cycles().
    [Python tip] `for ... else`: the else block of a for loop runs only if the loop finished WITHOUT `break`.
    """
    rmii, _ = res_mii(k, resources)
    cmii = rec_mii(k)
    mii = max(1, rmii, cmii)
    if max_ii is None:
        max_ii = sum(k.latency_of(n) + k.occupancy_of(n) for n in k.nodes) + 1
    carried_into, carried_out, succs = {}, {}, {n.id: [] for n in k.nodes}
    for u, v, lat, dist in k.carried_edges():
        carried_into.setdefault(v, []).append((u, lat, dist))
        carried_out.setdefault(u, []).append((v, lat, dist))
    for n in k.nodes:
        for p, d in k.preds(n):
            succs[p].append((n.id, d))
    graph = (carried_into, carried_out, succs)
    uses = {}
    for n in k.nodes:
        if n.kind in k.lib:
            uses[k.lib[n.kind].fu] = uses.get(k.lib[n.kind].fu, 0) + k.occupancy_of(n)
    given = dict(resources or {})
    for ii in range(mii, max_ii + 1):
        minimal = {cls: given.get(cls, math.ceil(u / ii)) for cls, u in uses.items()}
        for res in (minimal, given or None):
            found = _try_modulo(k, ii, res, graph)
            if found:
                return Schedule(k, found[0], found[1], res, ii=ii, mii=(rmii, cmii))
    raise RuntimeError(f"no modulo schedule found up to II={max_ii}")


def loop_cycles(s, trips):
    """
    Total cycles of a loop with `trips` iterations.

    [Idea] Pipelined (s.ii set): the first iteration finishes after `depth` cycles, and every further iteration
        finishes II cycles after the previous one: (trips - 1) * II + depth. Not pipelined (a list schedule of the
        body): trips * depth.
    [Edge cases] trips = 0 gives 0.
    """
    if trips <= 0:
        return 0
    if s.ii is None:
        return trips * s.depth
    return (trips - 1) * s.ii + s.depth


# =====================================================================================================================
# Binding costs: registers, multiplexers, memory; area and energy reports
# =====================================================================================================================

def _consumers(k):
    """node id -> list of (consumer id, iteration distance); outputs and stores consume their operand."""
    cons = {n.id: [] for n in k.nodes}
    for n in k.nodes:
        for a in n.args:
            if k.nodes[a].kind != "carried":
                cons[a].append((n.id, 0))
    for u, v, _, dist in k.carried_edges():
        cons[u].append((v, dist))
    return cons


def register_bits(s):
    """
    Bits of storage needed to hold values between the cycle they are produced and their last use.

    [Idea] A value produced at cycle p and last read at cycle L > p must sit in a register during [p, L).
        Straight-line schedule: registers can be shared by values whose lifetimes do not overlap (the left-edge
        algorithm achieves the minimum), so the count is the maximum number of bits alive in any cycle.
        Pipelined schedule: a new copy of every value is produced each II cycles, so a value living for T cycles
        needs ceil(T / II) registers (modulo variable expansion); loop-invariant inputs need one register each.
    [Returns] int bits
    [Edge cases] A value consumed in the very cycle it appears is read straight from the unit's output register
        and needs nothing extra. Values used only by a later iteration (accumulators) live until that use.
    """
    k, cons, ii = s.kernel, _consumers(s.kernel), s.ii
    intervals = []
    for n in k.nodes:
        if n.kind in ("store", "output", "const", "carried") or not cons[n.id]:
            continue
        if n.kind == "load" and n.array.is_registers:    # the value already sits in the array's registers
            continue
        p = s.start[n.id] + k.latency_of(n)
        last = max(s.start[c] + (ii or 0) * dist for c, dist in cons[n.id])
        if n.kind == "input":
            p = 0
        if last > p:
            intervals.append((p, last, n.bits, n.kind == "input"))
    if ii:
        return sum(b if is_in else math.ceil((last - p) / ii) * b for p, last, b, is_in in intervals)
    if not intervals:
        return 0
    horizon = max(last for _, last, _, _ in intervals)
    return max(sum(b for p, last, b, _ in intervals if p <= c < last) for c in range(horizon + 1))


def mux_bits(s):
    """
    Bits of 2:1 multiplexers needed in front of shared units.

    [Idea] When several operations share one unit instance, each input port of the unit must select between
        the different sources: k sources need a k:1 multiplexer = (k - 1) 2:1 multiplexers per bit. Sharing saves
        units but costs multiplexers (and wiring), which is why "fewest units" is not "smallest area".
    [Returns] int (number of 2:1 multiplexer bits)
        A loop that accesses a cyclically partitioned array whose banks ROTATE (Array.rotates) also needs a
        crossbar: every access selects one of P banks, (P - 1) multiplexer bits per data bit.
    [Edge cases] Fixed-bank memory ports are not counted (their multiplexing is part of the bank periphery).
    """
    k = s.kernel
    crossbar = sum((n.array.partition - 1) * n.array.bits for n in k.nodes
                   if n.kind in ("load", "store") and n.array.rotates)
    sources = {}
    for nid, (cls, inst) in s.binding.items():
        n = k.nodes[nid]
        if n.kind not in k.lib:
            continue
        for port, a in enumerate(n.args):
            sources.setdefault((cls, inst, port), set()).add(a)
    total = crossbar
    for (cls, inst, port), srcs in sources.items():
        bits = max(k.nodes[a].bits for a in srcs)
        total += (len(srcs) - 1) * bits
    return total


def area_report(s):
    """
    Area of the synthesized design (45 nm, µm^2).

    [Returns] dict with "fu" (functional units), "registers", "mux", "logic" (= fu + registers + mux),
        "memory" (SRAM banks or register arrays), "total", and "units" (instances per class)
    [Edge cases] Memory ports are not "units"; their cost is in the memory term (more banks = more periphery).
    """
    k = s.kernel
    fu = 0.0
    units = {cls: n for cls, n in s.units().items() if "." not in cls}
    for cls, n in units.items():
        spec = next(sp for sp in k.lib.values() if sp.fu == cls)
        fu += n * spec.area_um2
    reg = register_bits(s) * REG_UM2_PER_BIT
    mux = mux_bits(s) * MUX2_UM2_PER_BIT
    mem = sum(arr.area_um2() for arr in k.arrays.values())
    return {"fu": fu, "registers": reg, "mux": mux, "logic": fu + reg + mux, "memory": mem,
            "total": fu + reg + mux + mem, "units": units}


def energy_pj(k):
    """
    Energy of one execution of the kernel (one iteration of a loop body), 45 nm.

    [Idea] Arithmetic energy (Horowitz) + one SRAM access per load/store at the energy of the bank's size.
        Note what is NOT here: the schedule. Unrolling and sharing change the area and the latency, but the work
        -- and to first order the dynamic energy -- stays the same. (Smaller banks are slightly cheaper per
        access; registers and multiplexers add a little.)
    [Returns] float pJ
    """
    e = 0.0
    for n in k.nodes:
        if n.kind in k.lib:
            e += k.lib[n.kind].energy_pj
        elif n.kind in ("load", "store") and not n.array.is_registers:
            e += sram_pj_per_byte(n.array.bank_bytes()) * n.array.bits / 8
    return e


# =====================================================================================================================
# Evaluation: run a traced kernel on numbers (to check that restructuring preserved the function)
# =====================================================================================================================

def _arith(dtype):
    """
    Return (convert, ops) for evaluating a kernel.

    [Idea] fp32 kernels are evaluated in numpy float32, so every operation rounds exactly like 32-bit hardware;
        int8 kernels in exact Python integers (int32 accumulators are wide enough for this lecture's sizes).
    """
    import numpy as np
    if dtype == "fp32":
        conv = np.float32
        ops = {"add": lambda a, b: np.float32(a + b), "sub": lambda a, b: np.float32(a - b),
               "mul": lambda a, b: np.float32(a * b), "div": lambda a, b: np.float32(a / b)}
    else:
        conv = int
        ops = {"add": lambda a, b: a + b, "sub": lambda a, b: a - b, "mul": lambda a, b: a * b,
               "div": lambda a, b: a // b}
    return conv, ops


def evaluate(k, inputs=None, arrays=None, carried=None, iteration=0):
    """
    Execute the kernel once on concrete numbers, in program order.

    [Args]
        inputs   : dict input name -> number
        arrays   : dict array name -> mutable sequence (list or numpy array); stores write into it
        carried  : dict carried name -> its value in this iteration (default: each carried value's init)
        iteration: loop iteration number (selects elements of loop-body arrays; see Array)
    [Returns] (outputs dict name -> value, values dict node id -> value)
    [Edge cases] Missing inputs or arrays raise KeyError (better than silently computing with zeros).
    """
    conv, ops = _arith(k.dtype)
    inputs, arrays, carried = inputs or {}, arrays or {}, carried or {}
    vals, outs = {}, {}
    for n in k.nodes:
        if n.kind == "input":
            vals[n.id] = conv(inputs[n.name])
        elif n.kind == "const":
            vals[n.id] = conv(n.value)
        elif n.kind == "carried":
            vals[n.id] = conv(carried.get(n.name, n.value))
        elif n.kind in ("load", "store"):
            idx = n.offset if k.loop_stride is None else (k.loop_stride * iteration + n.offset) % n.array.size
            if n.kind == "load":
                vals[n.id] = conv(arrays[n.array.name][idx])
            else:
                arrays[n.array.name][idx] = vals[n.args[0]]
        elif n.kind == "output":
            outs[n.name] = vals[n.args[0]]
        else:
            vals[n.id] = ops[n.kind](vals[n.args[0]], vals[n.args[1]])
    return outs, vals


def run_loop(k, trips, inputs=None, arrays=None):
    """
    Execute a loop body for `trips` iterations, passing carried values from one iteration to the next.

    [Returns] (list of the outputs dict of every iteration, final dict of carried values)
    [Edge cases] A carried value whose source is another carried value takes that value's OLD content (a shift
        register: the order of updates inside one iteration does not matter, as in hardware).
    """
    carried_nodes = [n for n in k.nodes if n.kind == "carried"]
    state = {n.name: n.value for n in carried_nodes}
    history = []
    for it in range(trips):
        outs, vals = evaluate(k, inputs, arrays, state, it)
        history.append(outs)
        new_state = {}
        for n in carried_nodes:
            src = k.nodes[n.source]
            new_state[n.name] = state[src.name] if src.kind == "carried" else vals[src.id]
        state = new_state
    return history, state


# =====================================================================================================================
# Reports for the terminal
# =====================================================================================================================

def schedule_rows(s, max_cycles=None):
    """
    Rows for print_table(): one row per cycle, one column per resource class, listing the operations that START
    in that cycle (for a modulo schedule: one row per slot 0..II-1, operations tagged with their stage t // II).

    [Returns] (headers, rows)
    """
    k = s.kernel
    classes = sorted({cls for cls, _ in s.binding.values()}, key=lambda c: ("." in c, c))
    if s.ii:
        headers = ["slot"] + classes
        rows = []
        for slot in range(s.ii):
            row = [str(slot)]
            for cls in classes:
                ops = [f"{k.nodes[i].label}@{s.start[i] // s.ii}" for i, (c, _) in sorted(s.binding.items())
                       if c == cls and s.start[i] % s.ii == slot]
                row.append(" ".join(ops) or ".")
            rows.append(row)
        return headers, rows
    horizon = s.latency if max_cycles is None else min(s.latency, max_cycles)
    headers = ["cycle"] + classes
    rows = []
    for t in range(horizon):
        row = [str(t)]
        for cls in classes:
            ops = [k.nodes[i].label for i, (c, _) in sorted(s.binding.items()) if c == cls and s.start[i] == t]
            row.append(" ".join(ops) or ".")
        rows.append(row)
    return headers, rows


# =====================================================================================================================
# Example kernels shared by the demos
# =====================================================================================================================

def dot_product_body(unroll=1, partition=1, accumulators=1, dtype="fp32", n=256, ports=1):
    """
    One iteration of the loop `for i in range(0, n, unroll): acc += sum(a[i+u] * b[i+u] for u in range(unroll))`.

    [Idea] The three knobs of the lecture:
        unroll       : products per iteration (HLS "UNROLL factor=unroll")
        partition    : banks per array (HLS "ARRAY_PARTITION cyclic factor=partition")
        accumulators : number L of interleaved partial sums. With one accumulator, every iteration's final add
                       needs the result of the previous iteration's add: a recurrence through the adder, so
                       II >= adder latency. With L accumulators, iteration i adds into partial sum i mod L, which
                       was last written L iterations earlier: the recurrence spans L iterations and
                       II >= ceil(adder latency / L).
        How the rotation is built: the L carried values form a shift register acc_0 <- acc_1 <- ... <- acc_{L-1}
        <- new. Each iteration reads acc_0 (the partial sum written L iterations ago), adds its products, and
        writes `new`. After the loop the L partial sums still have to be added (a small epilogue, not part of
        this body).
    [Args] dtype: "fp32" or "int8"; n: array length (sets memory size); ports: ports per bank
    [Returns] the loop-body Kernel (loop_stride = unroll)
    [Edge cases] unroll must divide n. The final value of the dot product is the sum of the L carried values
        after the loop (run_loop's final state); dot_product_result() does it.
    """
    if n % unroll:
        raise ValueError("unroll must divide n")
    k = Kernel(f"dot U={unroll} P={partition} L={accumulators}", dtype, loop_stride=unroll)
    a = k.array("a", n, partition=partition, ports=ports)
    b = k.array("b", n, partition=partition, ports=ports)
    group = reduce_sum([a[u] * b[u] for u in range(unroll)], style="tree")
    accs = [k.carried(f"acc{j}", init=0) for j in range(accumulators)]
    new = accs[0] + group
    for j in range(accumulators - 1):
        k.carry(accs[j], accs[j + 1])
    k.carry(accs[-1], new)
    return k


def dot_product_result(state):
    """Sum of the partial sums left in the carried values by run_loop() on a dot_product_body (the epilogue)."""
    return sum(state[name] for name in sorted(state))


# =====================================================================================================================
# Self-test
# =====================================================================================================================

if __name__ == "__main__":
    import numpy as np

    # 1. Tracing and ASAP: an 8-element dot product, chain vs tree.
    for style, expect in (("chain", 3 + 7 * 4), ("tree", 3 + 3 * 4)):         # register arrays: loads are free
        k = Kernel("dot8", "fp32")
        a, b = k.array("a", 8, partition=8), k.array("b", 8, partition=8)
        k.output("y", reduce_sum([a[i] * b[i] for i in range(8)], style))
        assert schedule_length(k, asap(k)) == expect, (style, schedule_length(k, asap(k)))
        s = list_schedule(k, {"mul": 1, "add": 1})
        assert check_schedule(s)
        x, w = list(np.arange(8.0)), list(np.ones(8))
        assert evaluate(k, arrays={"a": x, "b": w})[0]["y"] == 28.0
    # 2. Resource limits: 8 loads from one single-port array take >= 8 cycles.
    k = Kernel("dot8", "fp32")
    a, b = k.array("a", 8), k.array("b", 8, partition=8)
    k.output("y", reduce_sum([a[i] * b[i] for i in range(8)], "tree"))
    s = list_schedule(k)
    assert check_schedule(s) and max(s.start[n.id] for n in k.nodes if n.kind == "load" and n.array is a) == 7
    # 3. Pipelining: a single fp32 accumulator gives RecMII = 4; four rotating accumulators give II = 1 (2 ports).
    m1 = modulo_schedule(dot_product_body(1, 1, 1, ports=1))
    m4 = modulo_schedule(dot_product_body(1, 1, 4, ports=1))
    assert (m1.mii[1], m1.ii) == (4, 4) and (m4.mii[1], m4.ii) == (1, 1), (m1.mii, m1.ii, m4.mii, m4.ii)
    assert check_schedule(m1) and check_schedule(m4)
    # 4. ResMII from memory ports: unroll 4 with 1 bank -> 4 loads per array per iteration -> II = 4.
    m = modulo_schedule(dot_product_body(4, 1, 4))
    assert m.mii[0] == 4 and m.ii == 4
    m = modulo_schedule(dot_product_body(4, 4, 4))
    assert m.ii == 1
    # 5. Functional check of the rotated-accumulator loop against numpy.
    rng = np.random.default_rng(0)
    av, bv = rng.standard_normal(256).astype(np.float32), rng.standard_normal(256).astype(np.float32)
    for U, L in ((1, 1), (4, 4), (8, 2)):
        body = dot_product_body(U, U, L)
        _, st = run_loop(body, 256 // U, arrays={"a": av, "b": bv})
        assert abs(dot_product_result(st) - float(np.dot(av.astype(np.float64), bv))) < 1e-3
    # 6. Non-pipelined divider: II = 12 per division, even with 2 dividers, unless the loop is unrolled by 2.
    k = Kernel("norm", "fp32", loop_stride=1)
    x, y = k.array("x", 64), k.array("y", 64)
    y[0] = x[0] / k.input("s")
    assert modulo_schedule(k, {"div": 1}).ii == 12 and modulo_schedule(k, {"div": 2}).ii == 12
    k = Kernel("norm2", "fp32", loop_stride=2)
    x, y = k.array("x", 64, partition=2), k.array("y", 64, partition=2)
    s_in = k.input("s")
    for u in range(2):
        y[u] = x[u] / s_in
    assert modulo_schedule(k, {"div": 2}).ii == 12 and modulo_schedule(k, {"div": 1}).ii == 24
    print("hls.py self-test passed")
