Algorithmadvanced
DAG-aware AIG rewriting
Also called AIG rewriting.
Mishchenko, Chatterjee and Brayton's rewriting that replaces the logic of small cuts of an AIG by precomputed AIGs of the same NPN class when this saves nodes in the shared graph.
- Time
- O(N^2 C^2) worst
- Space
- O(N C) extra
- Where
- C = the largest number of cuts of at most K leaves of one node; K = the largest number of leaves of a cut; N = the number of AND nodes
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Alan Mishchenko, Satrajit Chatterjee, Robert Brayton, 2006
DAG-aware AIG rewriting is a local search for multi-level logic synthesis that makes an and-inverter graph smaller without changing its functions. For each node it looks at the small cuts of the node, computes the function of the node in terms of the leaves of the cut, and looks up a precomputed AIG for that function, up to a permutation and complement of inputs and output, its NPN class. The new AIG replaces the old logic when this saves nodes. The gain counts the nodes that the change frees and the nodes that it adds, both in the shared graph: a node that other logic still uses is not freed, and a node that the hash table already holds is not added. Mishchenko, Chatterjee and Brayton (2006) used cuts of 4 leaves and the 222 NPN classes of 4-input functions, and the rewrite command of ABC is built on their method.
In plain words
Take a gate and a few wires below it, at most three or four, from which the gate's value can be computed. Work out what the gate computes from those wires. That is a small truth table.
Long ago, someone found good small circuits for every such table and stored them. Look up the stored circuit for this table. Count what you would save if you threw out the old logic between the wires and the gate, and built the stored circuit in its place. Old gates that other parts of the circuit still need cannot be thrown out, so do not count them. Gates of the stored circuit that already exist somewhere cost nothing.
If the count says you save at least one gate, make the change. Go through all gates this way, from the inputs to the outputs.
The problem
The input is an AIG with outputs . The output is an AIG with the same output functions and fewer AND nodes. Finding the smallest AIG of a function is a hard problem, so rewriting only makes local changes that never add nodes, and it stops after one pass over the graph. See multi-level logic synthesis for the problem and its hardness.
A cut of a node is a set of nodes such that every path from an input to passes through , and the cut is -feasible when . The maximum fanout-free cone is the set of nodes that become unused if is deleted: itself, and every node between and all of whose fanouts are in the set. Two functions are NPN-equivalent if one becomes the other by a permutation of the inputs, a negation of some inputs and a negation of the output. A permutation and negations cost nothing in an AIG, so two NPN-equivalent functions have smallest AIGs of the same size.
The algorithm
REWRITE(G)- 1
for each AND node v of G in topological order, if v is still in use do - 2
best ← none - 3
for each cut C of v with 2 to K leaves do - 4
t ← the truth table of v over C; (c, π) ← the NPN class of t and the transform to it - 5
M ← the maximum fanout-free cone of v over C - 6
for each structure S of the library for c do - 7
a ← the nodes that S over C, under π, would add, with a reused node of M counted as added - 8
if |M| − a > the gain of best then best ← (S, C, π) - 9
if best has gain > 0 then - 10
r ← build S over C under π, with the AND of the AIG page - 11
replace v by r: move each fanout of v to r, and hash it again; a fanout that now equals another node or a trivial case is replaced in turn - 12
delete the nodes that no output reaches
Line L3 takes the cuts from cut enumeration, which merges the cuts of the two fanins. Line L4 computes the truth table by simulating the cone of above , and finds the class and the transform in a table of all functions. Line L7 is a dry run of the AND of the AIG page that looks up each node of in the hash table and creates nothing. A node of that the table holds and that is outside costs nothing. A node that the table holds and that is in costs one, because it would be freed otherwise. A node that the table does not hold costs one. Line L8 keeps the best gain. Line L11 can trigger more merges above , since a fanout of may now have the same fanins as another node.
The code of this page uses and stores one smallest AIG for each of the 14 NPN classes of 3-input functions, found by an exhaustive search. The paper uses . It precomputes, for the classes that occur often, a set of AIG subgraphs that have no redundant nodes, shared in one graph of about a thousand nodes, and tries all of them for each cut.
Example
Take , built as written: node 4 is , node 5 is , and node 6 is , with . So the AIG has 3 AND nodes. Node 6 has four cuts with 2 or 3 leaves.
| cut of node 6 | function of node 6 | freed nodes M | added a | gain |
|---|---|---|---|---|
| {4, 5} | {6} | 1 | 0 | |
| {a, c, 4} | {5, 6} | the structure is node 6 again | skipped | |
| {a, b, 5} | {4, 6} | the structure is node 6 again | skipped | |
| {a, b, c} | {4, 5, 6} | 2 | 1 |
The cut has the class of the function (table 00011111), whose smallest AIG has 2 nodes: the complement of . Neither node is in the table, so , and the gain is . Line L10 makes node 7 and node 8 , line L11 moves the output to node 8, and line L12 deletes nodes 4, 5 and 6. The AIG now has 2 nodes for , and its truth table is still 11100000.
Now let be a second output. Node 4 is no longer freed when node 6 goes, so the cut has , and gain 0, and the cut has and gain 0. Nothing changes, and the AIG keeps 3 nodes. A rewriter that counted the whole tree of node 6 as freed would predict a gain of 1 and make the change, but node 4 must stay, so the AIG would still have 3 nodes, nodes 4, 7 and 8. With a structure of 3 nodes such a rewriter would even make the AIG larger. This is the sense in which the method is DAG-aware.
Correctness
The full proof shows three facts. First, the functions do not change: the structure computes the class representative , the transform maps it to the table of over , and the new literal is built over the same leaves, so and have the same function, and line L11 only replaces nodes by literals with equal functions. Second, no cycle appears: a node built at line L10 depends only on the leaves of and on nodes found in the table, and a found node depends on only if it is or above it. If the dry run uses , it has rebuilt the whole cone of above , so it counts every node of and the gain is at most 0. Third, the number of nodes that the outputs reach falls by at least the gain at each change: the nodes of that the new logic does not use are deleted, each node of adds at most one node, a reused node of is counted as added, and the merges of line L11 only remove nodes.
Proof: Rewriting keeps the functions, makes no cycle and lowers the size by at least the gainfull
We use the notation of the and-inverter graph page. is the function of a literal over the primary inputs. Before each node is handled, the graph is clean: every AND node is reached from an output, no two AND nodes have the same fanin pair, every node has fanins with , the table maps each fanin pair to its node, and the fanout counts are exact. The first sweep at the start of the pass and line L12 after each change make the graph clean, and the dry runs of lines L3 to L8 do not change it.
Fix a node , a cut of and the cone of over : the nodes on paths from to , without , so . Let be the maximum fanout-free cone, the nodes whose every fanout lies in , together with . Each library structure is a list of AND gates over the inputs and the constants.
Lemma 1 (the structure has the function of v). The literal built at line L10 satisfies .
Proof. Let be the table of over the leaves of , so , since every path from an input to meets . Line L4 gives , a permutation , a negation mask and an output phase with where . The structure computes , which the test file checks on all 8 points. Line L10 feeds with the literal of , complemented if , and the constant 0 if , in which case and so do not depend on . It complements the root if . The AND of the AIG page returns literals with the right functions, so .
Lemma 2 (the replacement keeps the functions). After line L11, every output has the same function as before.
Proof. Line L11 handles pairs with , starting with by Lemma 1. It replaces each use of , in an output or as a fanin of a node , by with the same phase, which keeps the function of that output and of . Then the fanins of are hashed again. If a trivial rule applies, has the function of the literal that the rule gives, and if the table holds a node with the same fanins, . In both cases the pair or again has equal functions. A target that was itself replaced earlier is followed to its replacement, which has the same function. So every step keeps all functions, and the pass ends because each step deletes one node and only nodes that exist at the start of line L11 or are made at line L10 are ever handled.
Lemma 3 (no cycle). If the gain of the chosen structure is positive, then does not depend on , and line L11 makes no cycle.
Proof. Call a value of the dry run of line L7 real if it is a literal of the graph, and new otherwise. Real values arise from the leaves, the constants, the trivial rules and table lookups. A real value that is not a leaf or a constant equals the result of a lookup at some gate of , because a trivial rule returns one of its two inputs or a constant. We claim that if some lookup returns a node of , then the lookups of the dry run return every node of the cone of that node over . Let a lookup return at gate . The fanins of are the two values of gate , so they are real, and each is either a leaf of or a node of , since every node on a path from to is in . A fanin in is not a leaf or a constant, so it is the result of a lookup at an earlier gate, and the claim follows by induction on the gates.
A node of the graph depends on only if it is or lies above . The leaves do not depend on . Suppose the dry run returns at some lookup. Then by the claim it returns every node of the cone of , which is , so it counts every node of as added and the gain is at most 0. So when the gain is positive, no lookup returns . Then by induction on the gates, no real value depends on : a lookup with fanins that do not depend on returns a node that is not and is not above . Line L10 runs the same steps on the same table, with new nodes in place of the new values, so does not depend on . Moving the fanouts of to therefore makes no cycle. A later step of line L11 replaces by a fanin of , by a constant, or by a node with the same fanins as , and none of these depends on .
Lemma 4 (the size). Let be the number of AND nodes before the change and the number after line L12. Then .
Proof. After line L11, has no uses. Every node of other than has all its fanouts in , so after the change it is reached from an output only through the nodes of . By the argument of Lemma 3, a node of reached through is the result of a lookup at some gate of in the dry run, and the dry run counted it as added. So the reached nodes after line L12 are among the nodes outside that were there before, the nodes of counted by the dry run, and the nodes created at line L10. Line L10 makes at most one node for each gate of that the dry run counted as new, since a gate with only real values does the same lookup in both runs, and a gate counted as new adds at most one node. The merges of line L11 add no node. So .
Theorem. One pass of REWRITE returns an AIG with the same output functions and no cycle, and each change lowers the number of AND nodes by at least its gain, which is positive. So the size never grows.
Proof. Lemmas 2 and 3 for each change, and Lemma 4 with the gain test of line L9.
Complexity
With fixed, a cut has a truth table of bits and a constant number of library structures, so lines L4 to L8 cost per cut, at most . The code of this page enumerates the cuts of each node again by merging the cuts of its fanins, per node in the worst case, and an accepted change costs for line L11 and the sweep of line L12. Over nodes this gives the of the front matter. ABC computes the cuts of all nodes once, bottom up, in , keeps only a bounded number of cuts per node, and updates the graph locally, so a pass is close to linear in on circuits. The NPN table for has entries, made once.
Properties
What is proved. One pass keeps every output function, never makes a cycle, and lowers the number of AND nodes by at least the gain of each change, so the size never grows. The 14 structures of the code of this page are smallest AIGs of their classes: an exhaustive search over all AIGs of at most 5 nodes, run by the test file, finds each of their sizes, and it finds no AIG of 5 or fewer nodes for the two classes of size 6.
What is not proved. The result is not a smallest AIG. A pass only sees cuts of at most leaves, accepts a change only when it saves nodes now, and visits the nodes once, so it stops at a local optimum. The 4-input subgraphs of the paper are not all smallest AIGs of their functions. They are the subgraphs with no redundant nodes that the precomputation found, and some classes are left out. The depth can grow when a change makes a longer path.
What is measured. On 300 random AIGs with 6 inputs, 50 calls of AND and 3 outputs each (seed 3), the code of this page lowered the mean number of AND nodes that the outputs reach from 23.3 to 10.3 in one pass, and a second pass lowered it to 10.0. Random AIGs have much redundant logic, so this shows only that the code works. It is not a benchmark result. The paper reports its own results on benchmark circuits.
Variants and improvements
- Zero-gain changes. Accepting changes with gain 0 does not shrink the graph, but it changes its shape, and a later pass can then find gains. ABC offers this as an option of rewrite.
- Keeping the depth. The rewrite command of ABC can reject a change that raises the level of the node, so that rewriting for area and AIG balancing for depth work together in scripts such as resyn2.
- Refactoring and resubstitution. Refactoring takes a larger cut of a node, often 10 or more leaves, computes a factored form of its function, and keeps it when it saves nodes. Resubstitution tries to express a node with nodes that already exist, sometimes with don't-cares.
- Exact libraries. With exact synthesis by SAT, the library can hold proved smallest AIGs for every NPN class of 4 inputs, and for many classes of 5 or 6 inputs. Exact synthesis on the fly for larger cuts is slower but finds more.
- Choices. Instead of replacing the old logic, a pass can keep both versions as structural choices, and let technology mapping pick between them.
- Other graphs. The same scheme works on the majority-inverter graph with a library of majority structures, and on XOR-AND graphs.
When to use it
Use rewriting as the main area pass on AIGs, alternating with balancing, before technology mapping or before a SAT based check, where fewer nodes mean a smaller CNF. It is fast, and many passes are cheap. It finds local redundancy well. It does not find logic sharing across distant parts of a circuit, which SAT sweeping finds, and it does not use the don't-cares of the network unless a variant with don't-cares is used.
Pitfalls
- Counting the tree, not the DAG. The gain must subtract only the nodes of the fanout-free cone. A node that has other fanouts stays, and the example above shows how counting it predicts a saving that does not happen.
- Counting a reused cone node as free. If the new structure reuses a node of through the hash table, that node is no longer freed, and it must count as added. Without this rule the predicted gain is too high, and the change can even rebuild over itself and make a cycle.
- Stale fanouts after a merge. When a fanout of becomes equal to another node, its own fanouts must move too, and a node that was already replaced must be followed to its replacement. A chain of merges is common after a change.
- Wrong transform direction. The transform maps the table of the cut to the class representative. Building the representative's structure needs the inverse map on the leaves, and the output phase must be put back. A test that compares the tables before and after a change catches this at once.
- Calling the subgraphs optimal. The library of the paper holds non-redundant subgraphs, not proved smallest ones, and the rewriting is a local search, so neither the structures nor the result are optimal.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/aig-rewriting/. The authors are listed in prov/CJJRNE.jsonl.
"""DAG-aware AIG rewriting with 3-input cuts and a library of smallest AIGs.
The AIG uses the literal code of the and-inverter-graph page: a literal
is 2 * id + c, node 0 is the constant 0, nodes 1 to n are inputs, and
every later node is an AND of two literals. The graph is changed in
place. For each node the pass looks at its cuts of at most 3 leaves,
finds the NPN class of the function of the cut, and tries the smallest
AIG of that class. The gain counts the nodes that would be freed (the
maximum fanout-free cone of the node over the cut) minus the nodes that
the new structure would add, where an old node that the structure reuses
through the hash table counts as added only if it is in that cone.
The paper of Mishchenko, Chatterjee and Brayton uses 4-input cuts and
the 222 NPN classes of 4-input functions. This version uses 3 inputs and
the 14 classes of 3-input functions, whose smallest AIGs are stored below.
"""
from itertools import permutations
from typing import Iterable, Optional
FULL3 = 0xFF
VAR3 = (0xF0, 0xCC, 0xAA) # x1, x2, x3 as 8-bit truth tables, x1 the high bit
# NPN class representative -> (gates, root) of a smallest AIG over y1, y2, y3.
# Literals: 0 and 1 are constants, 2 * j + c is y_j for j = 1, 2, 3, and gate
# number g (from 0) is the node 4 + g, with the literal 2 * (4 + g).
LIBRARY: dict[int, tuple[list[tuple[int, int]], int]] = {
0: ([], 0),
1: ([(5, 7), (3, 8)], 10),
3: ([(3, 5)], 8),
6: ([(5, 6), (4, 7), (9, 11), (3, 13)], 14),
7: ([(4, 6), (3, 9)], 10),
15: ([], 3),
22: ([(3, 7), (2, 6), (5, 11), (4, 8), (9, 12), (15, 17)], 19),
23: ([(3, 5), (6, 9), (2, 4), (11, 13)], 14),
24: ([(2, 7), (5, 8), (4, 6), (3, 12), (11, 15)], 17),
25: ([(3, 4), (5, 7), (6, 8), (11, 13)], 15),
27: ([(4, 7), (2, 6), (9, 11)], 12),
30: ([(5, 7), (3, 8), (2, 9), (11, 13)], 14),
60: ([(2, 4), (3, 5), (9, 11)], 12),
105: ([(3, 6), (2, 7), (9, 11), (4, 12), (5, 13), (15, 17)], 18),
}
def npn_transform(t: int, perm: tuple[int, ...], neg: int, out: int) -> int:
"""The table c with t(x) = out XOR c(y), where y_j = x_perm[j] XOR bit j of neg."""
c = 0
for ym in range(8):
x = [0, 0, 0]
for j in range(3):
x[perm[j]] = ((ym >> (2 - j)) & 1) ^ ((neg >> j) & 1)
xm = (x[0] << 2) | (x[1] << 1) | x[2]
c |= (((t >> xm) & 1) ^ out) << ym
return c
def _npn_table() -> dict[int, tuple[int, tuple[int, ...], int, int]]:
best: dict[int, tuple[int, tuple[int, ...], int, int]] = {}
for t in range(256):
for perm in permutations(range(3)):
for neg in range(8):
for out in (0, 1):
c = npn_transform(t, perm, neg, out)
if t not in best or c < best[t][0]:
best[t] = (c, perm, neg, out)
return best
NPN = _npn_table()
class Aig:
"""A structurally hashed AIG that can be changed in place."""
def __init__(self, n: int) -> None:
self.n = n
self.fanin0: list[int] = [-1] * (n + 1)
self.fanin1: list[int] = [-1] * (n + 1)
self.alive: list[bool] = [True] * (n + 1)
self.table: dict[tuple[int, int], int] = {}
self.outputs: list[int] = []
self.refs: list[int] = [0] * (n + 1)
self.fanouts: list[set[int]] = [set() for _ in range(n + 1)]
def is_and(self, v: int) -> bool:
return v > self.n
@staticmethod
def trivial(a: int, b: int) -> Optional[int]:
"""The literal of a AND b when a trivial rule gives it, else None (with a <= b)."""
if a == 0 or a == b ^ 1:
return 0
if a == 1 or a == b:
return b
return None
def and_(self, a: int, b: int) -> int:
if a > b:
a, b = b, a
r = self.trivial(a, b)
if r is not None:
return r
v = self.table.get((a, b))
if v is not None:
return 2 * v
v = len(self.fanin0)
self.fanin0.append(a)
self.fanin1.append(b)
self.alive.append(True)
self.refs.append(0)
self.fanouts.append(set())
self.table[(a, b)] = v
for x in (a, b):
self.refs[x >> 1] += 1
self.fanouts[x >> 1].add(v)
return 2 * v
# ------------------------------------------------------------ whole graph
def live_ands(self) -> list[int]:
"""The AND nodes that the outputs reach, in a topological order."""
order: list[int] = []
seen: set[int] = set()
for o in self.outputs:
stack = [(o >> 1, False)]
while stack:
v, done = stack.pop()
if done:
order.append(v)
continue
if v in seen or not self.is_and(v):
continue
seen.add(v)
stack.append((v, True))
stack.append((self.fanin1[v] >> 1, False))
stack.append((self.fanin0[v] >> 1, False))
return order
def num_ands(self) -> int:
return len(self.live_ands())
def collect_garbage(self) -> None:
"""Delete the AND nodes that no output reaches and recount the fanouts."""
live = set(self.live_ands())
for v in range(self.n + 1, len(self.fanin0)):
if self.alive[v] and v not in live:
self.alive[v] = False
key = (self.fanin0[v], self.fanin1[v])
if self.table.get(key) == v:
del self.table[key]
self.refs = [0] * len(self.fanin0)
self.fanouts = [set() for _ in range(len(self.fanin0))]
for v in live:
for x in (self.fanin0[v], self.fanin1[v]):
self.refs[x >> 1] += 1
self.fanouts[x >> 1].add(v)
for o in self.outputs:
self.refs[o >> 1] += 1
def simulate(self, lits: Optional[Iterable[int]] = None) -> list[int]:
"""Truth tables over all 2^n input points of the outputs (or of the given literals)."""
lits = self.outputs if lits is None else list(lits)
full = (1 << (1 << self.n)) - 1
val = [0] * len(self.fanin0)
for i in range(1, self.n + 1):
t = 0
for m in range(1 << self.n):
if (m >> (self.n - i)) & 1:
t |= 1 << m
val[i] = t
saved = self.outputs
self.outputs = lits
order = self.live_ands()
self.outputs = saved
for v in order:
a, b = self.fanin0[v], self.fanin1[v]
val[v] = (val[a >> 1] ^ (full if a & 1 else 0)) & (val[b >> 1] ^ (full if b & 1 else 0))
return [val[o >> 1] ^ (full if o & 1 else 0) for o in lits]
# ------------------------------------------------------------ local views
def cuts(self, v: int, k: int = 3) -> list[frozenset[int]]:
"""All cuts of node v with at most k leaves, the trivial cut first."""
memo: dict[int, list[frozenset[int]]] = {}
def go(u: int) -> list[frozenset[int]]:
if u in memo:
return memo[u]
res = [frozenset([u])]
if self.is_and(u):
seen = {res[0]}
for c0 in go(self.fanin0[u] >> 1):
for c1 in go(self.fanin1[u] >> 1):
c = c0 | c1
if len(c) <= k and c not in seen:
seen.add(c)
res.append(c)
memo[u] = res
return res
return go(v)
def cut_table(self, v: int, leaves: list[int]) -> int:
"""The 8-bit truth table of node v over the leaves, leaf j being x_(j+1)."""
val = {u: VAR3[j] for j, u in enumerate(leaves)}
def go(u: int) -> int:
if u not in val:
a, b = self.fanin0[u], self.fanin1[u]
va = go(a >> 1) ^ (FULL3 if a & 1 else 0)
vb = go(b >> 1) ^ (FULL3 if b & 1 else 0)
val[u] = va & vb
return val[u]
return go(v)
def mffc(self, v: int, leaves: frozenset[int]) -> set[int]:
"""The nodes freed if v is removed: v and the nodes above the leaves used only inside."""
refs: dict[int, int] = {}
cone = {v}
stack = [v]
while stack:
u = stack.pop()
for x in (self.fanin0[u], self.fanin1[u]):
w = x >> 1
if w in leaves or not self.is_and(w):
continue
refs[w] = refs.get(w, self.refs[w]) - 1
if refs[w] == 0:
cone.add(w)
stack.append(w)
return cone
def leaf_map(leaves: list[int], perm: tuple[int, ...], neg: int) -> dict[int, int]:
"""Map the library literals of y1, y2, y3 and the constants to literals of the graph."""
m = {0: 0, 1: 1}
for j in range(3):
if perm[j] < len(leaves):
lit = 2 * leaves[perm[j]] ^ ((neg >> j) & 1)
else:
lit = 0 # the function does not depend on this input
m[2 * (j + 1)] = lit
m[2 * (j + 1) + 1] = lit ^ 1
return m
def count_added(g: Aig, gates: list[tuple[int, int]], root: int, m: dict[int, int], freed: set[int]) -> tuple[int, Optional[int]]:
"""Dry run of a library structure: the nodes it would add and its root literal (None if new)."""
big = 2 * len(g.fanin0) # literals at or above big stand for nodes not yet made
val = dict(m)
added = 0
counted: set[int] = set()
for i, (a, b) in enumerate(gates):
x, y = val[a], val[b]
if x > y:
x, y = y, x
r = Aig.trivial(x, y)
if r is None:
if y < big:
w = g.table.get((x, y))
if w is not None:
r = 2 * w
if w in freed and w not in counted:
counted.add(w)
added += 1
if r is None:
r = big + 2 * i
added += 1
val[2 * (4 + i)] = r
val[2 * (4 + i) + 1] = r ^ 1
out = val[root]
return added, (out if out < big else None)
def build(g: Aig, gates: list[tuple[int, int]], root: int, m: dict[int, int]) -> int:
val = dict(m)
for i, (a, b) in enumerate(gates):
r = g.and_(val[a], val[b])
val[2 * (4 + i)] = r
val[2 * (4 + i) + 1] = r ^ 1
return val[root]
def replace(g: Aig, old: int, new: int) -> None:
"""Move every use of node old to the literal new, and merge or simplify the fanouts that change."""
work = [(old, new)]
moved: dict[int, int] = {}
while work:
o, r = work.pop()
while r >> 1 in moved:
r = moved[r >> 1] ^ (r & 1)
if not g.alive[o] or o == r >> 1:
continue
g.outputs = [r ^ (x & 1) if x >> 1 == o else x for x in g.outputs]
for p in list(g.fanouts[o]):
if not g.alive[p]:
continue
a, b = g.fanin0[p], g.fanin1[p]
if g.table.get((a, b)) == p:
del g.table[(a, b)]
a = r ^ (a & 1) if a >> 1 == o else a
b = r ^ (b & 1) if b >> 1 == o else b
if a > b:
a, b = b, a
g.fanin0[p], g.fanin1[p] = a, b
g.fanouts[o].discard(p)
g.fanouts[r >> 1].add(p)
t = Aig.trivial(a, b)
if t is not None:
work.append((p, t))
elif (a, b) in g.table:
work.append((p, 2 * g.table[(a, b)]))
else:
g.table[(a, b)] = p
key = (g.fanin0[o], g.fanin1[o])
if g.table.get(key) == o:
del g.table[key]
g.alive[o] = False
moved[o] = r
def rewrite(g: Aig) -> list[tuple[int, int, int]]:
"""One pass of DAG-aware rewriting in place. Returns (gain, size before, size after) per change."""
g.collect_garbage()
log: list[tuple[int, int, int]] = []
for v in g.live_ands(): # @line L1
if not g.alive[v] or not g.is_and(v) or g.refs[v] == 0:
continue
best = None # @line L2
for cut in g.cuts(v)[1:]: # @line L3
leaves = sorted(cut)
canon, perm, neg, out = NPN[g.cut_table(v, leaves)] # @line L4
freed = g.mffc(v, cut) # @line L5
gates, root = LIBRARY[canon] # @line L6
m = leaf_map(leaves, perm, neg)
added, lit = count_added(g, gates, root ^ out, m, freed) # @line L7
if lit is not None and lit >> 1 == v:
continue
gain = len(freed) - added
if best is None or gain > best[0]: # @line L8
best = (gain, gates, root ^ out, m)
if best is None or best[0] <= 0: # @line L9
continue
before = g.num_ands()
r = build(g, best[1], best[2], best[3]) # @line L10
replace(g, v, r) # @line L11
g.collect_garbage() # @line L12
log.append((best[0], before, g.num_ands()))
return log
test_aig_rewriting.py 149 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/aig-rewriting/. The authors are listed in prov/CJJRNE.jsonl.
import random
from aig_rewriting import FULL3, LIBRARY, NPN, VAR3, Aig, npn_transform, rewrite
def structure_table(gates: list[tuple[int, int]], root: int) -> int:
val = {0: 0, 1: FULL3}
for j in range(3):
val[2 * (j + 1)] = VAR3[j]
val[2 * (j + 1) + 1] = VAR3[j] ^ FULL3
for i, (a, b) in enumerate(gates):
v = val[a] & val[b]
val[2 * (4 + i)] = v
val[2 * (4 + i) + 1] = v ^ FULL3
return val[root]
def min_sizes_by_search(limit: int) -> dict[int, int]:
"""The least number of AND nodes for every 3-input function, by breadth-first search up to limit."""
cost = {0: 0, FULL3: 0}
for t in VAR3:
cost[t] = 0
cost[t ^ FULL3] = 0
level = {()}
for k in range(1, limit + 1):
nxt = set()
for st in level:
sig = list(VAR3) + list(st)
have = set(sig) | {s ^ FULL3 for s in sig} | {0, FULL3}
for i in range(len(sig)):
for j in range(i + 1, len(sig)):
for pa in (0, FULL3):
for pb in (0, FULL3):
x = (sig[i] ^ pa) & (sig[j] ^ pb)
if x not in have:
nxt.add(tuple(sorted(st + (x,))))
level = nxt
for st in level:
for x in st:
for y in (x, x ^ FULL3):
cost.setdefault(y, k)
return cost
def test_npn_classes() -> None:
assert len(set(c for c, _, _, _ in NPN.values())) == 14
assert sorted(LIBRARY) == sorted(set(c for c, _, _, _ in NPN.values()))
for t, (c, perm, neg, out) in NPN.items():
assert npn_transform(t, perm, neg, out) == c
def test_library_is_right_and_smallest() -> None:
cost = min_sizes_by_search(5)
for c, (gates, root) in LIBRARY.items():
assert structure_table(gates, root) == c
if len(gates) <= 5:
assert cost[c] == len(gates)
else:
assert c not in cost # no AIG of 5 or fewer nodes exists
assert max(len(g) for g, _ in LIBRARY.values()) == 6
def example() -> Aig:
g = Aig(3)
ab = g.and_(2, 4)
ac = g.and_(2, 6)
o = g.and_(ab ^ 1, ac ^ 1) ^ 1 # ab + ac
g.outputs = [o]
return g
def test_example_saves_one_node() -> None:
g = example()
table = g.simulate()
assert g.num_ands() == 3
log = rewrite(g)
assert g.simulate() == table == [0b11100000]
assert g.num_ands() == 2
assert log == [(1, 3, 2)]
def test_example_with_shared_node_is_kept() -> None:
g = example()
g.outputs.append(g.and_(2, 4)) # a & b is also an output
table = g.simulate()
log = rewrite(g)
assert log == []
assert g.num_ands() == 3 and g.simulate() == table
def test_redundant_logic_is_removed() -> None:
g = Aig(3)
x = g.and_(2, 4)
y = g.and_(x, g.and_(2, 6)) # a & b & c with a twice
z = g.and_(y ^ 1, x ^ 1) ^ 1 # (abc) + (ab) = ab
g.outputs = [z]
table = g.simulate()
rewrite(g)
assert g.simulate() == table
assert g.num_ands() == 1
def check_invariants(g: Aig) -> None:
live = g.live_ands()
pos = {v: i for i, v in enumerate(live)}
keys = set()
for v in live:
a, b = g.fanin0[v], g.fanin1[v]
assert g.alive[v] and 2 <= a < b and a != b ^ 1
assert g.table[(a, b)] == v
keys.add((a, b))
for x in (a, b):
if g.is_and(x >> 1):
assert pos[x >> 1] < pos[v]
assert len(keys) == len(live)
def random_aig(rng: random.Random) -> Aig:
n = rng.randrange(3, 7)
g = Aig(n)
lits = [2 * i for i in range(1, n + 1)]
for _ in range(rng.randrange(4, 35)):
a = lits[-1] if rng.random() < 0.4 else rng.choice(lits)
x = g.and_(a ^ rng.randrange(2), rng.choice(lits) ^ rng.randrange(2))
if x > 1:
lits.append(x)
g.outputs = [rng.choice(lits[n:] or lits) ^ rng.randrange(2) for _ in range(rng.randrange(1, 4))]
return g
def test_random_aigs_keep_function_and_shrink() -> None:
rng = random.Random(31)
changed = 0
for _ in range(500):
g = random_aig(rng)
g.collect_garbage()
table = g.simulate()
size = g.num_ands()
log = rewrite(g)
assert g.simulate() == table
assert g.num_ands() <= size
for gain, before, after in log:
assert gain > 0 and after <= before - gain
check_invariants(g)
changed += bool(log)
assert changed > 100
History
Rewriting circuits with local rules goes back to the transformation systems of the 1980s, such as the rule based LSS system of IBM. Bjesse and Borälv (2004) compressed AIGs for formal verification by replacing small cuts with precomputed structures while counting the shared nodes, and the 2006 paper builds on their work. Mishchenko, Chatterjee and Brayton (2006) made the method fast enough for synthesis, with the NPN classes of 4-input functions, a shared library of non-redundant subgraphs, and the gain over the maximum fanout-free cone. They reported that scripts of rewriting and balancing on AIGs give results close to those of the older SOP based scripts in much less run time. Their method became the rewrite command of ABC, which Brayton and Mishchenko (2010) describe as the base of its synthesis.
References
- Alan Mishchenko, Satrajit Chatterjee and Robert Brayton, DAG-aware AIG rewriting, a fresh look at combinational logic synthesis, Proceedings of the 43rd Design Automation Conference, 2006, pages 532 to 535, the 4-input cuts, the 222 NPN classes of 4-input functions, the precomputed non-redundant subgraphs of the useful classes, the count of gain over the shared graph, and the experiments with balancing
- Robert Brayton and Alan Mishchenko, ABC, an academic industrial-strength verification tool, Computer Aided Verification (CAV 2010), Lecture Notes in Computer Science 6174, Springer, 2010, pages 24 to 40, the synthesis commands of ABC on AIGs, among them rewrite, refactor and balance
- Donald E. Knuth, The Art of Computer Programming, Volume 4A, Combinatorial Algorithms Part 1, 2011, Section 7.1.2, Boolean evaluation (the least cost of the functions of 3 and 4 variables, and their classes under permutation and complementation)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag CJJRNE Edit this page History Report an error Markdown