Data structurecore
And-inverter graph
Also called AIG.
A Boolean network of two-input AND nodes with optional inverted edges, kept free of duplicate nodes by structural hashing, the main form of modern logic synthesis.
- Time
- O(1) expected andO(N) levelsO(N 2^n / w) simulate
- Space
- O(N) nodes
- Where
- N = the number of AND nodes; n = the number of primary inputs; w = the number of bits in a machine word
- Model
- Word RAM
- Properties
- not concurrentnot externalpersistent
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Andreas Kuehlmann, Viresh Paruthi, Florian Krohm, Malay K. Ganai, 2002
An and-inverter graph, or AIG, is a Boolean network in which every inner node is an AND of two inputs and every edge may carry an inverter. It is a directed acyclic graph whose sources are the primary inputs and the constant 0, and each primary output is an edge, possibly inverted, to one node. A hash table on the pair of fanins makes sure that no two nodes have the same two fanins, which is hash consing applied to circuits and is called structural hashing. AND and NOT can express every Boolean function, so an AIG can hold any circuit, at the cost of a few nodes for each XOR or multiplexer.
In plain words
Draw a circuit with only one kind of gate, a two-input AND. To get NOT, put a small dot on a wire. OR is an AND with dots on its two inputs and on its output. With these two parts you can build every circuit.
Keep a dictionary of every gate you have built, keyed by its two input wires. Before you build a new gate, look it up. If the same gate is already there, use the old one. So the graph never holds two copies of the same gate, and shared logic is shared by itself.
The graph is small and simple to walk, and every program in a tool chain can read it. It does not decide by itself if two gates compute the same thing, because two different shapes can give the same function.
The abstract type
An AIG over the inputs stores a set of nodes, each one a Boolean function of the inputs. A literal names a node and a phase: the node itself or its complement. The operations are:
- INPUT(i): the literal of .
- AND(a, b): a literal whose function is . NOT(a) is free: it flips the phase of . OR, XOR and MUX are made from AND and NOT.
- SIMULATE(o_1, ..., o_k): the truth tables of the given literals.
- LEVELS: the depth of each node, the number of AND nodes on the longest path from an input.
The contract of AND is that the function is right and that no node is ever added twice for the same pair of fanins. Two literals with the same function may still differ, so the type gives no constant-time equality test of functions. That is the main difference from the ROBDD, where equal functions have equal nodes.
Representation
A literal is the integer , where is the node number and means a complemented edge. Node 0 is the constant 0, so the literal 0 is false and the literal 1 is true. Nodes 1 to are the inputs. Every later node holds two fanin literals of older nodes, in two arrays fanin0 and fanin1. A hash table maps the pair to . The node numbers are a topological order, since a node is made after its fanins. This is also the literal code of the AIGER file format, which most tools use to exchange AIGs.
Operations
AND(a, b)- 1
if a > b then swap a and b ▷ one order for each pair - 2
if a = 0 then return 0 ▷ x ∧ 0 = 0 - 3
if a = 1 then return b ▷ x ∧ 1 = x - 4
if a = b then return a ▷ x ∧ x = x - 5
if a = b xor 1 then return 0 ▷ x ∧ ¬x = 0 - 6
if T holds the key (a, b) then return 2·T[a, b] ▷ structural hashing - 7
v ← a new node with fanins (a, b); T[a, b] ← v; return 2v SIMULATE(o_1, ..., o_k) ▷ truth tables as integers of 2^n bits- 8
val[0] ← 0; val[i] ← the table of x_i for i = 1 to n - 9
for v ← n + 1 to the last node: val[v] ← lit(fanin0[v]) ∧ lit(fanin1[v]) - 10
return lit(o_1), ..., lit(o_k) ▷ lit(2u + c) = val[u], complemented if c = 1
Line L1 fixes one order for the two fanins, so that and find the same key. Lines L2 to L5 remove the cases where the result is a constant or an old literal, so no node has a constant fanin, two equal fanins or two opposite fanins. Line L6 is the hash lookup. NOT(a) returns and adds nothing. OR(a, b) is , one node. XOR(a, b) is , three nodes, and MUX(s, t, e) is , also three nodes.
SIMULATE keeps one integer of bits for each node, bit being the value at input point , with the high bit as in sum of products. Line L9 does one machine AND per word, so all points are simulated at once. With random words in place of full tables, the same loop is the random simulation that equivalence checkers run first to split nodes into candidate classes.
Example
Build a full adder with sum and carry , over the inputs with literals 2, 4 and 6.
| step | call | key | result | nodes |
|---|---|---|---|---|
| 1 | AND(2, 4), the of | (2, 4) | new node 4, literal 8 | 1 |
| 2 | AND(3, 5), the of | (3, 5) | new node 5, literal 10 | 2 |
| 3 | AND(9, 11), so | (9, 11) | new node 6, literal 12 | 3 |
| 4 | AND(12, 6), the of | (6, 12) | new node 7, literal 14 | 4 |
| 5 | AND(13, 7), the of | (7, 13) | new node 8, literal 16 | 5 |
| 6 | AND(15, 17), so | (15, 17) | new node 9, literal 18 | 6 |
| 7 | AND(2, 4), the of the carry | (2, 4) | found node 4, literal 8 | 6 |
| 8 | AND(12, 6), the of the carry | (6, 12) | found node 7, literal 14 | 6 |
| 9 | AND(9, 15), carry | (9, 15) | new node 10, literal 20, then NOT | 7 |
Steps 7 and 8 find the nodes of steps 1 and 4 in the table, so the carry costs one new node, and the adder has 7 AND nodes in all. SIMULATE gives the tables 240, 204 and 170 for , and , 150 (the bits 10010110) for the sum and 232 (the bits 11101000) for the carry. The deepest node is node 9 at level 4, and the carry is at level 4 too. In step 4, line L1 swaps the call AND(12, 6) to the key (6, 12).
Structural hashing does not find every equal pair. In a new AIG, AND(AND(a, b), c) and AND(a, AND(b, c)) give two different literals, 10 and 14, with the same table 128. Finding that two such literals are equal needs a SAT call or a BDD, which is what SAT sweeping does.
Correctness
The full proof shows two invariants. First, every AND node has fanins with and both from nodes older than , and the table maps each node's pair to that node and holds no other key. Second, AND(a, b) returns a literal whose function is : lines L2 to L5 are the identities , , and , line L6 returns a node whose fanins are exactly and , and line L7 makes one. From the first invariant, no two AND nodes share a pair of fanins, and the graph has no cycle. SIMULATE is right by induction on the node number, since the fanins of a node come before it.
Proof: AND keeps the AIG hashed and acyclic, and SIMULATE computes the truth tablesfull
The inputs are . For a literal we write for its function: if and if . The node 0 has , the input node has , and an AND node with fanins has . So , and for every literal.
Invariant (H). For every AND node : (a) its fanins satisfy and ; (b) and are literals of nodes with numbers smaller than ; (c) the table maps to . And has no key other than the fanin pairs of the AND nodes.
At the start there are no AND nodes and is empty, so (H) holds. Only line L7 adds a node or a key.
Lemma 1. If (H) holds before a call AND(a, b), it holds after the call, and the call returns a literal with .
Proof. Line L1 swaps the arguments, which does not change . So assume from now on. If , then and the result 0 is right. If , then and the result is right. If , then . If , then and . None of these cases changes the graph or , so (H) still holds.
Otherwise and . If holds the key , then by (H) the key belongs to a node with fanins exactly and , so , and line L6 returns with no change. If does not hold the key, line L7 makes a node with the fanins . Part (a) of (H) holds for by the cases just ruled out. The literals and were made before this call, so their nodes have numbers smaller than , which is part (b). Line L7 adds the key with the value , which is part (c), and this key is new, so it does not change the value of any older key. The result has the function .
Corollary 2. No two AND nodes have the same pair of fanins, and the graph has no directed cycle.
Proof. If two nodes had the same pair , then by part (c) the table would map to both, which a table cannot do. Every edge goes from a node to a node with a smaller number by part (b), so every directed path has strictly falling numbers and cannot close.
Lemma 3. SIMULATE returns, for each , the integer whose bit is at the input point .
Proof. We show by induction on that after line L9 has handled node , has bit equal to at point , for every node up to . Line L8 sets this for the node 0 and the inputs. For an AND node with fanins and , both fanin nodes are smaller than by part (b), so their values are already right. The value of a literal is when and its bitwise complement in bits when , so it is the table of . The bitwise AND of the two fanin tables is the table of . Line L10 reads the literal tables in the same way.
Complexity
AND does a constant number of steps and one hash lookup, so it takes expected time. SIMULATE takes word operations for nodes and inputs, or for random patterns. LEVELS is one pass in . The space is two integers for each node and one table entry, .
The size of an AIG is close to the size of the circuit it comes from. A circuit of two-input AND, OR and NOT gates gives at most AND nodes. A circuit with XOR gates gives at most three nodes for each. The parity of inputs needs AND nodes, while its smallest sum of products has cubes, and an ROBDD of parity has inner nodes in any order. The ROBDD of a multiplier is exponential in every order (Bryant 1991), while its AIG has nodes. This size bound is why tools keep the AIG as the main form and build BDDs only for small parts.
Variants
- Complemented edges on BDDs. The same trick of a bit on the edge is used by complemented edges in BDD packages, where it also keeps the diagram canonical.
- Functionally reduced AIGs. A FRAIG merges every two nodes with the same function, found by simulation and SAT, so that equal functions get equal literals. See SAT sweeping.
- Hashing two levels. Some packages also look up small patterns of two levels, so that, for example, and meet. This finds more sharing, but the result still depends on the order of construction.
- Sequential AIGs. Latches are kept as extra inputs and outputs, and the AIGER format lists them with their next-state literals.
- Other node types. The majority-inverter graph uses three-input majority nodes, and XOR-AND graphs add an XOR node, which suits arithmetic and cryptographic circuits.
When to use it
Use an AIG as the main form of a combinational or sequential circuit in a synthesis or verification tool. It is small, its size grows like the circuit, it turns into CNF with three clauses per node by the Tseitin transformation, and the bit-blasting of word-level formulas gives one directly. Most of the work on it is local: AIG balancing for depth, AIG rewriting for size, and technology mapping over cuts. Use a binary decision diagram when you need equality of functions in constant time or counts of solutions, and the function is small enough for one.
Pitfalls
- No order on the key. Without line L1, AND(a, b) and AND(b, a) make two nodes for one gate.
- Hashing before the trivial rules. Lines L2 to L5 must come before the lookup. Otherwise the graph gets nodes such as , which are constant but look like gates.
- Treating hashing as a canonical form. Two literals with the same function can differ, as the example shows. A tool that tests equality of literals as equality of functions misses most equivalences.
- Forgetting the output phase. An output is a literal, and its complement bit is part of the function. A simulator that reads only the node number gives the wrong table for half of the outputs.
- Counting inverters as nodes. Inverters are bits on edges and cost nothing. The size of an AIG is the number of AND nodes, and its depth counts only AND nodes.
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/and-inverter-graph/. The authors are listed in prov/PGBE80.jsonl.
"""An and-inverter graph with complemented edges and structural hashing.
A literal is the integer 2 * id + c, where id names a node and c = 1
means the edge is complemented. Node 0 is the constant 0, so literal 0
is false and literal 1 is true. Nodes 1 to n are the primary inputs.
Every later node is a two-input AND whose fanins are two literals of
older nodes. The hash table maps an ordered fanin pair to its node, so
the graph never holds two AND nodes with the same pair of fanins.
"""
from typing import Iterable
class Aig:
"""A structurally hashed AIG over n primary inputs."""
def __init__(self, n: int) -> None:
self.n = n
self.fanin0: list[int] = [-1] * (n + 1)
self.fanin1: list[int] = [-1] * (n + 1)
self.table: dict[tuple[int, int], int] = {}
# ---------------------------------------------------------------- building
def input(self, i: int) -> int:
"""The positive literal of input i, for 1 <= i <= n."""
if not 1 <= i <= self.n:
raise ValueError("no such input")
return 2 * i
def is_and(self, node: int) -> bool:
return node > self.n
def num_ands(self) -> int:
return len(self.fanin0) - self.n - 1
def and_(self, a: int, b: int) -> int:
"""The literal of a AND b, after the trivial rules and a hash lookup."""
if a > b: # @line L1
a, b = b, a
if a == 0: # @line L2
return 0
if a == 1: # @line L3
return b
if a == b: # @line L4
return a
if a == b ^ 1: # @line L5
return 0
node = self.table.get((a, b)) # @line L6
if node is not None:
return 2 * node
node = len(self.fanin0) # @line L7
self.fanin0.append(a)
self.fanin1.append(b)
self.table[(a, b)] = node
return 2 * node
def or_(self, a: int, b: int) -> int:
return self.and_(a ^ 1, b ^ 1) ^ 1
def xor(self, a: int, b: int) -> int:
"""a XOR b as NOT(a AND b) AND NOT(NOT a AND NOT b), three AND nodes."""
return self.and_(self.and_(a, b) ^ 1, self.and_(a ^ 1, b ^ 1) ^ 1)
def mux(self, s: int, t: int, e: int) -> int:
"""The literal of (s AND t) OR (NOT s AND e)."""
return self.or_(self.and_(s, t), self.and_(s ^ 1, e))
# -------------------------------------------------------------- simulation
def input_table(self, i: int) -> int:
"""The truth table of input i as an integer of 2^n bits, x1 the high bit of the minterm."""
t = 0
for m in range(1 << self.n):
if (m >> (self.n - i)) & 1:
t |= 1 << m
return t
def simulate(self, outputs: Iterable[int]) -> list[int]:
"""Truth tables of the given literals, one bit per input assignment."""
full = (1 << (1 << self.n)) - 1
val = [0] * len(self.fanin0) # @line L8
for i in range(1, self.n + 1):
val[i] = self.input_table(i)
for v in range(self.n + 1, len(self.fanin0)): # @line L9
a, b = self.fanin0[v], self.fanin1[v]
va = val[a >> 1] ^ (full if a & 1 else 0)
vb = val[b >> 1] ^ (full if b & 1 else 0)
val[v] = va & vb
return [val[o >> 1] ^ (full if o & 1 else 0) for o in outputs] # @line L10
# ---------------------------------------------------------------- measures
def levels(self) -> list[int]:
"""The level of each node: 0 for inputs and the constant, 1 + the larger fanin level for an AND."""
lev = [0] * len(self.fanin0)
for v in range(self.n + 1, len(self.fanin0)):
lev[v] = 1 + max(lev[self.fanin0[v] >> 1], lev[self.fanin1[v] >> 1])
return lev
def cone_size(self, outputs: Iterable[int]) -> int:
"""The number of AND nodes that the given literals reach."""
seen: set[int] = set()
stack = [o >> 1 for o in outputs]
while stack:
v = stack.pop()
if v in seen or not self.is_and(v):
continue
seen.add(v)
stack.append(self.fanin0[v] >> 1)
stack.append(self.fanin1[v] >> 1)
return len(seen)
test_and_inverter_graph.py 124 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/and-inverter-graph/. The authors are listed in prov/PGBE80.jsonl.
import itertools
import random
from and_inverter_graph import Aig
def test_full_adder_example() -> None:
g = Aig(3)
a, b, c = g.input(1), g.input(2), g.input(3)
t = g.xor(a, b)
s = g.xor(t, c)
before = g.num_ands()
carry = g.or_(g.and_(a, b), g.and_(t, c))
assert (t, s) == (12, 18)
assert before == 6
assert g.num_ands() == 7
assert carry == 21
assert g.simulate([a, b, c, s, carry]) == [240, 204, 170, 150, 232]
assert max(g.levels()) == 4
def test_trivial_rules() -> None:
g = Aig(2)
a, b = g.input(1), g.input(2)
assert g.and_(a, 0) == 0
assert g.and_(1, a) == a
assert g.and_(a, a) == a
assert g.and_(a, a ^ 1) == 0
assert g.num_ands() == 0
x = g.and_(a, b)
assert g.and_(b, a) == x
assert g.or_(a, 1) == 1
assert g.num_ands() == 1
def test_hashing_is_not_canonical() -> None:
g = Aig(3)
a, b, c = g.input(1), g.input(2), g.input(3)
left = g.and_(g.and_(a, b), c)
right = g.and_(a, g.and_(b, c))
assert left != right
assert g.simulate([left]) == g.simulate([right])
def test_no_two_nodes_share_fanins() -> None:
rng = random.Random(7)
g = Aig(4)
lits = [0, 1] + [g.input(i) ^ c for i in range(1, 5) for c in (0, 1)]
for _ in range(300):
x = g.and_(rng.choice(lits) ^ rng.randrange(2), rng.choice(lits) ^ rng.randrange(2))
lits.append(x)
pairs = list(zip(g.fanin0[g.n + 1:], g.fanin1[g.n + 1:]))
assert len(pairs) == len(set(pairs))
for v in range(g.n + 1, len(g.fanin0)):
a, b = g.fanin0[v], g.fanin1[v]
assert 2 <= a < b and (a >> 1) < v and (b >> 1) < v and a ^ 1 != b
assert g.table[(a, b)] == v
def random_formula(rng: random.Random, n: int, depth: int):
if depth == 0 or rng.random() < 0.2:
return ("x", rng.randrange(1, n + 1), rng.randrange(2))
op = rng.choice(["and", "or", "xor", "mux"])
k = 3 if op == "mux" else 2
return (op, [random_formula(rng, n, depth - 1) for _ in range(k)], rng.randrange(2))
def evaluate(f, x: tuple[int, ...]) -> int:
if f[0] == "x":
return x[f[1] - 1] ^ f[2]
vals = [evaluate(h, x) for h in f[1]]
if f[0] == "and":
v = vals[0] & vals[1]
elif f[0] == "or":
v = vals[0] | vals[1]
elif f[0] == "xor":
v = vals[0] ^ vals[1]
else:
v = vals[1] if vals[0] else vals[2]
return v ^ f[2]
def build(g: Aig, f) -> int:
if f[0] == "x":
return g.input(f[1]) ^ f[2]
args = [build(g, h) for h in f[1]]
if f[0] == "and":
v = g.and_(*args)
elif f[0] == "or":
v = g.or_(*args)
elif f[0] == "xor":
v = g.xor(*args)
else:
v = g.mux(*args)
return v ^ f[2]
def test_random_formulas_against_truth_tables() -> None:
rng = random.Random(2024)
for trial in range(600):
n = rng.randrange(1, 6)
g = Aig(n)
forms = [random_formula(rng, n, rng.randrange(1, 5)) for _ in range(3)]
outs = [build(g, f) for f in forms]
tables = g.simulate(outs)
for f, t in zip(forms, tables):
for m, x in enumerate(itertools.product((0, 1), repeat=n)):
assert (t >> m) & 1 == evaluate(f, x)
# building the same formulas again adds no node
size = g.num_ands()
assert [build(g, f) for f in forms] == outs
assert g.num_ands() == size
def test_equal_tables_after_rebuild_in_fresh_graph() -> None:
rng = random.Random(11)
for _ in range(200):
n = rng.randrange(2, 5)
f = random_formula(rng, n, 4)
g1, g2 = Aig(n), Aig(n)
assert g1.simulate([build(g1, f)]) == g2.simulate([build(g2, f)])
History
Graphs of AND gates and inverters are as old as switching theory, but their use as a shared, hashed data structure came from equivalence checking in the 1990s. Kuehlmann, Paruthi, Krohm and Ganai (2002) gave the form used today: an AND graph with complemented edges, structural hashing of the fanins, and SAT, BDD and simulation engines that work on it together. Mishchenko, Chatterjee and Brayton (2006) showed that synthesis can work on the AIG directly with local rewriting, and the ABC system of Brayton and Mishchenko (2010) made the AIG the common form of its synthesis, mapping and verification commands. Biere's AIGER format with the literal code became the standard file format, and the hardware model checking competitions use it.
References
- Andreas Kuehlmann, Viresh Paruthi, Florian Krohm and Malay K. Ganai, Robust Boolean reasoning for equivalence checking and functional property verification, IEEE Transactions on Computer-Aided Design 21(12), 2002, pages 1377 to 1394, the AND graph with complemented edges, structural hashing of the two fanins, and its use with SAT, BDDs and random simulation
- 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 AIG as the common form of the synthesis and verification engines of ABC
- 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 AIG of the paper, its structural hashing and its node count as the cost of synthesis
Where this leads
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 | W4 complete |
|
Tag PGBE80 Edit this page History Report an error Markdown