Optimization Passes List
This is an automatically generated list of all optimization passes available
with the default opt_main. This is generated automatically based on comments
in the header files.
Note
Additional development passes are available listed here.
If the opt level is set below 'Min opt level' the pass will act as a no-op.
If the opt level is set above 'Cap opt level' the pass (or passes within the compound pass) will be executed with the opt level capped to the specified value.
Warning
Many of these passes have descriptions generated by the Gemini LLM and may not accurately reflect the behavior of the passes. As time goes on manual verification or editing of the pass descriptions may be done to improve accuracy.
default_pipeline - The default pipeline.
Invoked Passes
arith_simp - Arithmetic Simplifications
This pass performs various arithmetic optimizations such as replacement of divide by a constant with non-divide operations.
Note
What follows was generated by the Gemini LLM. Not human verified.
The ArithSimplificationPass applies a wide range of local and algebraic
transformations to simplify arithmetic, shift, decode, and comparison
expressions in XLS IR. It uses a UnionQueryEngine combining
StatelessQueryEngine and a cached PartialInfoQueryEngine to inspect known
constant values, bit patterns, and value intervals, visiting nodes in reverse
topological order and iterating to a fixed point until no further
simplifications apply.
Key optimizations performed by this pass include:
-
Division and Modulo Optimizations: * Division by Power of Two:
udiv(x, 2^K)is replaced by resizingxand shifting right logically (shrl(x, K)). Signed divisionsdiv(x, +/- 2^L)is replaced with arithmetic and logical right shifts plus a sign-bias addition ((x + ((x >> (L - 1)) >>> (N - L))) >> L, negated if the divisor is negative) to round toward zero. * Division by Non-Power-of-Two Constant:udiv(x, K)andsdiv(x, K)(whereK != 0) are strength-reduced into "magic number" multiplication and shifts (following Granlund and Montgomery's algorithm for division by invariant integers). * Division with Small Constant Dividend:udiv(K, x)andsdiv(K, x)where|K| <= 4095are replaced with a compressed lookup table combining a directarray_indextable (for small divisors up to 64) and apriority_selover cutoff comparisons for larger divisors. * Division by Variable Power of Two or Small Divisor Set (MatchWithLimitedDivisorSpace): WhenSplitsEnabled(opt_level)is true andudivorsdivhas a divisor whoseIntervalSethas at mostkMaxArbitraryDivisorLUTSize(16) possible values (and the dividend is not a known constant with multiple divisor values) or satisfiesAtMostOneBitTrue(divisor): if the divisor is a variable power of two (decode(K)or2^L << K) and satisfiesAtMostOneBitTrue(divisor), the division is replaced with variable right shifts (MakePow2ShiftNode); otherwise (when the divisor space has at most 16 values), it is replaced with apriority_sellookup table (MakeDivLutNode) keyed byeq(divisor, C)over the per-constant strength-reduced divisions. * Division by Shifted Divisor:x / (y << k)is rewritten into(x / y) / (1 << k)(with a division-by-zero guard if needed) whenyhas enough known leading zeros thaty << kcannot overflow. * Modulo by Constant:umod(x, K)andsmod(x, K)by0or1simplify to0.umod(x, 2^K)extracts theKleast-significant bits viabit_sliceandzero_ext.smod(x, 2^K)extracts theKlow bits and conditionally subtracts2^Kwhenx < 0and the remainder is non-zero. Modulo by any other constantK(or with a small constant dividendK % x) is expanded tox - (x / K) * Kso the division can be strength-reduced. -
Multiplication Optimizations: * Multiply by Zero or Zero-Width Operands:
umul/smulby0, orumul/smul/umulp/smulpwith a zero-width operand, are replaced with0. * Multiply by Positive Power of Two:umul(x, 2^K)andsmul(x, 2^K)are replaced by resizingxand left-shifting byK(shll(x, K)). * Multiply by Small Constant (whenSplitsEnabled(opt_level)is true, atopt_level >= 3): Multiplication by a positive constant requiring at most one adder/subtractor is decomposed into shifts and anaddorsub(e.g.,x * 5becomes(x << 2) + x, andx * 7becomes(x << 3) - x). * Narrowing Multiplies: If all users of aumulorsmularebit_sliceoperations that only read the lowerWbits, the multiplication itself is narrowed toWbits. -
Shift and Extension Optimizations: * Shift by Constant: Shifts by
0are replaced with the shifted operand.shll(x, K)andshrl(x, K)by a constantKare replaced with aconcatof abit_sliceofxand a zero literal (or0ifK >= width(x)), avoiding a barrel shifter:``` // Original IR amt: bits[8] = literal(value=2) ret res: bits[8] = shrl(x, amt) // Optimized IR zero: bits[2] = literal(value=0) slice: bits[6] = bit_slice(x, start=2, width=6) ret res: bits[8] = concat(zero, slice) ```* Arithmetic Shift Right by Constant:
shra(x, K)is replaced withsign_ext(bit_slice(x, ...)). * 1-Bit and Constant-1 Shifts:shll(x: bits[1], amt)andshrl(x: bits[1], amt)becomeand(x, eq(amt, 0));shra(x: bits[1], amt)becomesx; and right-shifting a constant1becomeszero_ext(eq(amt, 0)). * Power-of-Two Left Shift:(2^K) << Nis rewritten aszero_ext(decode(N)) << K. * Strip Redundant Shift Extensions and Clamps: Leading zero concatenations (concat(0, amt)) and upper-bound clamps (LIMIT >= width(x)) on shift amounts are removed. * Collapse Nested Extensions:zero_ext(zero_ext(x))andsign_ext(sign_ext(x))are collapsed into a single extension. -
Decode and Mask Optimizations: * Small Decodes: A 1-bit wide
decode(x)becomeseq(x, 0). A 2-bit widedecode(x: bits[1])becomesconcat(x, not(x)). * Decode Index Cleanup: Strips leading zeros (concat(0, idx)) and redundant upper-bound clamps (LIMIT >= width(decode)) from decode inputs. * Mask Idiom (decode(N) - 1): Rewritessub(decode(N), 1)andadd(decode(N), all_ones)tonot(shll(all_ones, N)), eliminating an adder. -
Addition and Comparison Optimizations: * Two's Complement Negation:
add(not(x), 1)is simplified toneg(x). * Sign-Extended Boolean Addition:add(sign_ext(c: bits[1]), K)is simplified tosel(c, cases=[K, K - 1]). * Inverted Comparisons:not(cmp(x, y))with a single-use comparison is replaced by the inverse comparison (e.g.,uge(x, y)fornot(ult(x, y))). * Sign-Bit Comparisons (whenNarrowingEnabled(opt_level)is true, atopt_level >= 2):slt(x, 0)is replaced withmsb(x)andsge(x, 0)withnot(msb(x)). * Unsigned Comparison to LSB Mask (whenNarrowingEnabled(opt_level)is true): Unsigned comparisons (ult,ugt,ule,uge) against a constant mask of trailing ones0...01...1(orugtagainstmask - 1) are reduced toor_reduce,nor_reduce, andand_reduceover the leading and trailing bit slices. * Comparisons with Negation or Bitwise Not: Eliminates single-usenegin signed comparisons (cmp(-lhs, -rhs)andcmp(-expr, K)withxorcorrections forMIN_SIGNED), simplifieseq(not(x), K)toeq(x, ~K), and simplifieseq(sel(p, cases=[x, neg(x)]), 0)toeq(x, 0). * Comparison of Injective Operations: Rewriteseq/necomparisons ofX + C0,X - C0,C0 - X, or non-overflowingumul(X, C0)against a constantC1to directly compareXagainst the solved constant (or folds impossibleumulcomparisons to a constant boolean). * Same-Width Modular Equality Cancellation: Simplifieseqandnecomparisons of a 2-operandadd,sub, orxoragainst one of its own operands—(x + y) cmp x,(y + x) cmp x,(x - y) cmp x,(x ^ y) cmp x, or(y ^ x) cmp x—toy cmp 0(forsub, cancellation applies only when the shared operandxis the minuend).
array_simp - Array Simplification
Pass which simplifies or eliminates some array-type operations such as ArrayIndex.
Note
What follows was generated by the Gemini LLM. Not human verified.
The ArraySimplificationPass simplifies and eliminates array-related
operations (array, array_index, array_update, array_slice, and
array-typed sel/priority_sel/one_hot_sel) to reduce multiplexer width
and eliminate unnecessary array storage. It uses a UnionQueryEngine
combining StatelessQueryEngine and LazyTernaryQueryEngine.
The pass executes in three stages:
-
Clamping Known Out-of-Bounds
ArrayIndexIndices: Scans allarray_indexnodes and clamps any index operand whose minimum unsigned value (MinUnsignedValue) is greater than or equal to the dimension size to a literalsize - 1. -
Flattening Sequential
ArrayUpdateChains: Walks the graph in reverse topological order to find chains ofarray_updateoperations sharing a common index prefix. When the chain updates at least half of the subarray's elements (or at least 2 elements whenSplitsEnabled(opt_level)is true, atopt_level >= 3), the chain is collapsed into a singlearrayconstruction where each element uses apriority_selover the update indices. -
Worklist-Driven Iterative Simplifications: Seeds a worklist in reverse topological order and repeatedly applies local rewrites until reaching a fixed point:
*
ArrayIndexSimplifications: * Empty Indices:array_index(A, {})is replaced withA. * Unit-Size Dimensions: Any non-literal index into a dimension of size 1 is replaced with0. * Indexing intoArray: If the first index into anarraynode is constant, extracts the selected operand directly (clamping if out of bounds). If the index is dynamic, replaces thearray_indexwith aselover the reachablearrayoperands (using the last element asdefaultfor clamping):``` // Original IR arr: bits[32][3] = array(a, b, c) ret res: bits[32] = array_index(arr, indices=[idx]) // Optimized IR (for idx: bits[2]) ret res: bits[32] = sel(idx, cases=[a, b], default=c) ``` * **Indexing into `ArrayConcat`**: If the first index is a known in-bounds constant, bypasses `array_concat` to index directly into the corresponding concatenated array operand. * **Consecutive `ArrayIndex` Operations**: Flattens nested `array_index(array_index(A, {i}), {j})` into `array_index(A, {i, j})`. * **`ArrayIndex` of Select**: Pushes `array_index` into the cases of `sel`, `one_hot_sel`, or `priority_sel` when the select has a single user, or when `SplitsEnabled(opt_level)` is true and either the array is small (`size <= 3`) or every live user of the select is a constant-indexed `array_index` (`ArrayOnlyConstIndexed`). * **`ArrayIndex` of `ArrayUpdate`**: * If the update indices match the read indices (or are a prefix of them) and the access is known in-bounds, bypasses the array to read directly from `update_value` (preserving `assumed_in_bounds` when provably in bounds). * If the update and read indices are provably unequal and the read is in-bounds, bypasses the `array_update` to read from the original array. * For small 1D arrays (`size <= 3`) when `SplitsEnabled(opt_level)` is true, unwinds `array_index(array_update(A, v, {u_idx}), {r_idx})` into a `priority_sel` comparing `u_idx` against the clamped `r_idx`.*
ArrayUpdateSimplifications: * Empty or Redundant Updates:array_update(A, v, {})becomesv, andarray_update(A, array_index(A, {idx}), {idx})becomesA. * Unit-Size Dimensions: Replaces updates to leading size-1 dimensions with apriority_selchecking whether the indices are0(or directly with the wrapped value if assumed in-bounds). * HoistingArrayUpdateintoArray: When updating a single-usearraynode and either the first index is constant orSplitsEnabled(opt_level)is true, pushes the update into the compatible elements of thearray(insertingpriority_sels when the index is not fully known), or unpacks a constant array updated at a constant in-bounds index. * Nested and Overwritten Updates: Mergesarray_update(A, array_update(array_index(A, {i}), v, {j}), {i})intoarray_update(A, v, {i, j})(preservingassumed_in_boundswhen both outer and inner updates are provably in bounds), and removes earlier updates in a single-use chain whose index is overwritten by a later prefix update.*
ArrayandArraySliceSimplifications: * Decompose/Recompose Elimination: Replaces anarraybuilt from sequentialarray_index(A, {prefix..., 0..N-1})elements withA(orarray_index(A, {prefix...})). * StaticArraySlice: Replaces anarray_slicewith a known constantstartindex with anarrayof staticarray_indexoperations.* Array-Typed Select Simplifications: * Conditional Update Hoisting: Rewrites
sel(p, cases=[A, array_update(A, v, {idx})])intoarray_update(A, sel(p, cases=[array_index(A, {idx}), v]), {idx})so the mux operates on a single element rather than the entire array. * Select ofArrays toArrayof Selects: When all branches (up to 2) of a select arearraynodes, pushes the select element-wise into a singlearrayof narrower selects.
array_untuple - Array UnTuple
Pass which changes any (non-external) array-of-tuple into a tuple-of-arrays. We can see through tuples quite well but can't see through arrays to anywhere near the same extent. Therefore the struct-of-array representation is always superior.
Note that this pass makes no attempt to unpack or repack arrays which escape the function-base. This means that anything which comes in through a function param, or a procs recv or escapes through a function return or a proc send is not untuple'd.
TODO(allight): We could do this at the cost of a significant number of ir nodes. We should experiment to see if this is worth doing.
Note
What follows was generated by the Gemini LLM. Not human verified.
The ArrayUntuplePass transforms internal arrays of tuples
(Array<Tuple<A, B, ...>>) into conceptual tuples of component arrays
(Array<A>, Array<B>, ...) within functions and procs (blocks are skipped).
This struct-of-arrays (SoA) transformation separates independent tuple fields
into distinct arrays so that subsequent passes (such as
DataflowSimplificationPass, ArraySimplificationPass, and
DeadCodeEliminationPass) can optimize or eliminate unused fields
independently.
How it Works:
-
Grouping Connected Array Operations (
FindUntupleGroups): Uses aUnionFind<Node*>structure to group nodes that must be transformed together. Connected operations that union their array operands and results into the same equivalence class includearray_update,array_slice,array_concat,eq,ne,sel,priority_sel,one_hot_sel,gate, and allstate_reads andnext_valuevalueoperands associated with the same procStateElement. -
Excluding Externally Visible or Unhandled Groups (
FindExternalGroups): Identifies equivalence groups that cannot be untupled without repacking: * Function parameters (param) and function return values of array type. * Procsenddata operands of array type. * ProcStateElements whosestate_reads are only used in no-op self-updates (IsNoOpNext). * Arrays of empty tuples (()[N]). * Nested arrays of arrays of tuples ((A, B)[M][N]). * Theupdate_valueoperand of anarray_update. * Arrays of tuples produced or consumed by any other unhandled operation (such astuple_indexextracting an array from areceivetoken/data tuple). -
Rewriting Eligible Groups (
UntupleVisitor): Traverses the graph in topological order and splits each eligibleArray<Tuple<T_0, ..., T_{k-1}>>node intokcomponent arraysArray<T_0>, ..., Array<T_{k-1}>: *Literal: Splits an array-of-tuples literal intokseparate arrayliterals, one for each tuple element. *StateReadandNext: Splits an array-of-tuples procStateElementintoknew state elements (<name>_tuple_element_i) with correspondingstate_readandnext_valuenodes, detaching the original state element into a dead no-op update. *Array: Extracts tuple elements from each operand viatuple_indexand constructskseparatearraynodes. *ArrayIndex: Replacesarray_index(arr, indices)with atupleofkarray_indexnodes indexing into each component array. *ArrayUpdate,ArraySlice,ArrayConcat,Gate, and Selects (Sel,PrioritySel,OneHotSel): Distributes the operation across each of thekcomponent arrays. *EqandNe: Compares each pair of component arrays individually and combines the boolean results withand(foreq) oror(forne).
Example:
// Original IR
fn read_second_field(t0: (bits[32], bits[16]),
t1: (bits[32], bits[16]),
idx: bits[1]) -> bits[16] {
arr: (bits[32], bits[16])[2] = array(t0, t1)
elem: (bits[32], bits[16]) = array_index(arr, indices=[idx])
ret res: bits[16] = tuple_index(elem, index=1)
}
// After ArrayUntuplePass (and subsequent tuple/dead-code cleanup)
fn read_second_field(t0: (bits[32], bits[16]),
t1: (bits[32], bits[16]),
idx: bits[1]) -> bits[16] {
t0_f1: bits[16] = tuple_index(t0, index=1)
t1_f1: bits[16] = tuple_index(t1, index=1)
arr_tuple_idx_1: bits[16][2] = array(t0_f1, t1_f1)
ret elem_tuple_idx_1: bits[16] = array_index(arr_tuple_idx_1,
indices=[idx])
}
basic_simp - Basic Simplifications
This pass does simple pattern-matching optimizations which are ~always a good idea to do (replacing a node with a constant, removing operands of nodes, etc). They improve QoR, do not increase the number of nodes in the graph, preserve the same abstraction level, and do not impede later optimizations via obfuscation. These optimizations require no analyses beyond looking at the node and its operands. Examples include: not(not(x)) => x, x + 0 => x, etc.
Note
What follows was generated by the Gemini LLM. Not human verified.
The BasicSimplificationPass applies fast, local pattern-matching
optimizations to the XLS IR using a StatelessQueryEngine. It iteratively
transforms nodes in the function or proc until reaching a fixed point,
reducing node count and simplifying expressions without increasing graph
complexity or obscuring high-level structure.
Key simplifications performed by this pass include:
-
Select and Control-Flow Simplifications: *
priority_sel(bits[0], cases=[], default=X)=>X. * Select of Compared Operands: A binary select (selorpriority_sel) whose selector iseq(x, y)orne(x, y)and whose branches arexandysimplifies directly toxory(e.g.,sel(eq(x, y), cases=[x, y])=>x, andsel(ne(x, y), cases=[x, y])=>y). * Not/Increment Zero-Equivalence: Since both~x == 0andx + 1 == 0hold if and only ifxis all ones,(eq|ne)(sel(c, cases=[not(x), add(x, 1)]), 0)(with either operand or branch ordering) is simplified to(eq|ne)(x, all_ones). * Commutative Op on Swapped Selects: For any non-side-effecting commutative binary operationop,op(sel(p, cases=[a, b]), sel(p, cases=[b, a]))is simplified toop(a, b). -
Arithmetic Identities and Involutions: *
add(x, 0),sub(x, 0),shll(x, 0),shrl(x, 0), andshra(x, 0)=>x. *sub(x, x)=>0. *umul(x, 0)andsmul(x, 0)=>0. *add(x, not(x))andadd(not(x), x)=>all_ones. *neg(neg(x))=>x. * 1-Bit Arithmetic:neg(x: bits[1])=>xandsub(0, x: bits[1])=>x. -
Bitwise and N-ary Logical Simplifications: *
not(not(x))=>x. *xor(x, all_ones)=>not(x). * Single-Operand N-ary Ops:and(x)andor(x)=>x;nand(x)andnor(x)=>not(x). * Duplicate Operand Removal: Deduplicates repeated operands inand,or,nand, andnor(e.g.,and(x, y, x)=>and(x, y)). Inxor, operands appearing an even number of times cancel out (xor(x, x)=>0) and operands appearing an odd number of times collapse to a single instance (xor(x, x, x)=>x). * Identity and Absorbing Constants: Removes0operands fromor,xor, andnor, and removesall_onesoperands fromandandnand. Replacesor(..., all_ones, ...)withall_ones,nor(..., all_ones, ...)with0,and(..., 0, ...)with0, andnand(..., 0, ...)withall_ones. * Complementary Operands: Replacesand(..., x, ..., not(x), ...)with0andor(..., x, ..., not(x), ...)withall_ones. * Flattening Single-Use Associative N-ary Ops: Inlines single-use nested N-ary operations of the same associative opcode into the parent operation:``` // Original IR or.1: bits[8] = or(w, x) or.2: bits[8] = or(y, z) ret res: bits[8] = or(or.1, or.2) // Optimized IR (after dead code elimination) ret res: bits[8] = or(w, x, y, z) ```* Constant Folding in N-ary Ops: Combines multiple known constant operands in associative and commutative N-ary operations into a single literal operand.
-
Bitwise Reduction Simplifications: *
and_reduce(x),or_reduce(x), andxor_reduce(x)on a 1-bitx=>x; on a 0-bit operand => the operation's identity (1forand_reduce,0foror_reduceandxor_reduce). *or_reduce(neg(x))=>or_reduce(x). * Sign-Extension Mask Reduction: For widthw > 1andb: bits[1], rewritesor_reduce(and(x, sign_ext(b, new_bit_count=w)))toand(b, or_reduce(x))andand_reduce(and(x, sign_ext(b, new_bit_count=w)))toand(b, and_reduce(x))(and similarly withnot(b)when thesign_extmask is inverted withnot). -
Comparison Simplifications: * 1-Bit Equality:
eq(x: bits[1], 1)=>xandeq(x: bits[1], 0)=>not(x). * Reflexive and Irreflexive Relations: Replaceseq(x, x),sge(x, x),uge(x, x),sle(x, x), andule(x, x)with1; replacesne(x, x),sgt(x, x),ugt(x, x),slt(x, x), andult(x, x)with0. * Zero-Width Comparisons: For zero-width values,eq(x, y)=>1andne(x, y)=>0. * Inequality Disjunction:or(ugt(a, b), ult(a, b))=>ne(a, b).
bdd_cse - BDD-based Common Subexpression Elimination
Pass which commons equivalent expressions in the graph using binary decision diagrams.
Note
What follows was generated by the Gemini LLM. Not human verified.
The BddCsePass (BDD-based Common Subexpression Elimination) identifies and
merges logically equivalent bits-typed expressions within a function or
proc using Binary Decision Diagrams (BDDs). Unlike the purely syntactic
CsePass, BddCsePass can detect semantic equivalence across expressions
with different IR structures by comparing their canonical BDD
representations.
How it Works:
-
Canonical BDD Representation: The pass queries a shared
BddQueryEngineto obtain the BDD node index for every bit of eachbits-typed node in the graph. Because reduced ordered BDDs are canonical for a fixed variable ordering, two nodes compute the same Boolean function on every bit if and only if they have the same bit width and identical BDD node indices for all bit positions. -
Delay-Aware Topological Ordering (
GetNodeOrder): Before comparing nodes, the pass computes each node's critical-path delay from the graph roots usingGetStandardDelayEstimator(). Nodes are sorted in monotonically non-decreasing order of critical-path delay, breaking ties by topological sort index. This guarantees a valid topological traversal (preventing cycles) while ensuring that when an earlier node replaces a later node, the replacement never increases the critical-path delay of any path through the graph. -
Hash Bucketing and Replacement: The pass iterates through the sorted nodes (skipping non-
bitsnodes andliterals) and hashes the vector of per-bit BDD node indices for each node. Nodes with matching hashes are grouped into buckets and compared bit-by-bit (is_same_value). When a node matches an earlier candidate in the same bucket, all uses of the node are replaced with the earlier candidate.
Example: Two syntactically distinct expressions that compute the same Boolean value will share the same BDD node and be commoned into a single node:
// Original IR
fn compare_twice(x: bits[16]) -> (bits[1], bits[1]) {
forty_two: bits[16] = literal(value=42)
x_eq_42: bits[1] = eq(x, forty_two)
x_ne_42: bits[1] = ne(forty_two, x)
not_ne: bits[1] = not(x_ne_42)
ret res: (bits[1], bits[1]) = tuple(x_eq_42, not_ne)
}
// Optimized IR (after BddCsePass and dead code elimination)
fn compare_twice(x: bits[16]) -> (bits[1], bits[1]) {
forty_two: bits[16] = literal(value=42)
x_eq_42: bits[1] = eq(x, forty_two)
ret res: (bits[1], bits[1]) = tuple(x_eq_42, x_eq_42)
}
bdd_simp - BDD-based Simplification
Runs BDD-based simplifications on the function.
Note
What follows was generated by the Gemini LLM. Not human verified.
The BddSimplificationPass leverages Binary Decision Diagrams (BDDs) via a
UnionQueryEngine (combining StatelessQueryEngine and BddQueryEngine) to
perform logic-level simplifications on the IR in topological order.
The pass performs the following transformations:
-
Replacing Statically Known Bits with Literals: For each non-literal
bits-typed node, the pass inspects known constant bits at the most-significant end (prefix) and least-significant end (suffix): * Fully Known Nodes: If all bits of the node are statically known, the node is replaced with aliteralat any optimization level. * Known Prefix/Suffix Splitting (whenSplitsEnabled(opt_level)is true, atopt_level >= 3): If a contiguous prefix and/or suffix of bits is constant (and not already exposed as aliteraloperand of aconcat), the node is replaced by aconcatof the known prefixliteral, abit_sliceof the remaining unknown middle bits, and the known suffixliteral. -
Removing Redundant Operands in 1-Bit Boolean Operations: For 1-bit
and,nand,or, andnoroperations with up to 10 operands (kMaxBooleanFanIn), the pass checks whether any operand is logically implied by the others (ImpliedNodeValue). Specifically, for each operand, it assumes all other non-redundant operands take the non-controlling ("ignorable") value (1forand/nand,0foror/nor). If the target operand is guaranteed to also take that non-controlling value under those assumptions, the operand is replaced with the constant1or0literal:// Original IR c: bits[1] = and(a, b) ret res: bits[1] = and(a, b, c) // Optimized IR (c is implied to be 1 whenever a == 1 and b == 1) one: bits[1] = literal(value=1) ret res: bits[1] = and(a, b, one) -
Replacing Two-Way
OneHotSelectwithSelect(whenSplitsEnabled(opt_level)is true, atopt_level >= 3): If aone_hot_selhas a 2-bit selector that BDD analysis proves is strictly one-hot (AtLeastOneBitTrueandAtMostOneBitTrue), it is replaced with a 2-wayselindexed bybit_slice(selector, start=0, width=1)withcases=[case(1), case(0)]. -
Eliminating
OneHoton Inputs with at Most One Bit Set: If BDD analysis proves that the operandxof aone_hotnode has at most one bit set (AtMostOneBitTrue(x)), theone_hotoperation is replaced withconcat(eq(x, 0), x). -
Narrowing
PrioritySelectwith Guaranteed Set Bits (whenNarrowingEnabled(opt_level)is true, atopt_level >= 2): If BDD analysis proves that at least one bit of apriority_selselector is always set (AtLeastOneBitTrue), the pass finds the lowest bit indexlast_bitsuch that at least one bit inselector[0..last_bit]is guaranteed to be true. It then slices the selector tolast_bitbits, retainscases[0..last_bit-1], and promotescase(last_bit)to be the newdefaultvalue, discarding unreachable higher-index cases and the previous default.
bdd_simp(2) - BDD-based Simplification with opt level <= 2
Runs BDD-based simplifications on the function.
Note
What follows was generated by the Gemini LLM. Not human verified.
The BddSimplificationPass leverages Binary Decision Diagrams (BDDs) via a
UnionQueryEngine (combining StatelessQueryEngine and BddQueryEngine) to
perform logic-level simplifications on the IR in topological order.
The pass performs the following transformations:
-
Replacing Statically Known Bits with Literals: For each non-literal
bits-typed node, the pass inspects known constant bits at the most-significant end (prefix) and least-significant end (suffix): * Fully Known Nodes: If all bits of the node are statically known, the node is replaced with aliteralat any optimization level. * Known Prefix/Suffix Splitting (whenSplitsEnabled(opt_level)is true, atopt_level >= 3): If a contiguous prefix and/or suffix of bits is constant (and not already exposed as aliteraloperand of aconcat), the node is replaced by aconcatof the known prefixliteral, abit_sliceof the remaining unknown middle bits, and the known suffixliteral. -
Removing Redundant Operands in 1-Bit Boolean Operations: For 1-bit
and,nand,or, andnoroperations with up to 10 operands (kMaxBooleanFanIn), the pass checks whether any operand is logically implied by the others (ImpliedNodeValue). Specifically, for each operand, it assumes all other non-redundant operands take the non-controlling ("ignorable") value (1forand/nand,0foror/nor). If the target operand is guaranteed to also take that non-controlling value under those assumptions, the operand is replaced with the constant1or0literal:// Original IR c: bits[1] = and(a, b) ret res: bits[1] = and(a, b, c) // Optimized IR (c is implied to be 1 whenever a == 1 and b == 1) one: bits[1] = literal(value=1) ret res: bits[1] = and(a, b, one) -
Replacing Two-Way
OneHotSelectwithSelect(whenSplitsEnabled(opt_level)is true, atopt_level >= 3): If aone_hot_selhas a 2-bit selector that BDD analysis proves is strictly one-hot (AtLeastOneBitTrueandAtMostOneBitTrue), it is replaced with a 2-wayselindexed bybit_slice(selector, start=0, width=1)withcases=[case(1), case(0)]. -
Eliminating
OneHoton Inputs with at Most One Bit Set: If BDD analysis proves that the operandxof aone_hotnode has at most one bit set (AtMostOneBitTrue(x)), theone_hotoperation is replaced withconcat(eq(x, 0), x). -
Narrowing
PrioritySelectwith Guaranteed Set Bits (whenNarrowingEnabled(opt_level)is true, atopt_level >= 2): If BDD analysis proves that at least one bit of apriority_selselector is always set (AtLeastOneBitTrue), the pass finds the lowest bit indexlast_bitsuch that at least one bit inselector[0..last_bit]is guaranteed to be true. It then slices the selector tolast_bitbits, retainscases[0..last_bit-1], and promotescase(last_bit)to be the newdefaultvalue, discarding unreachable higher-index cases and the previous default.
bdd_simp(3) - BDD-based Simplification with opt level <= 3
Runs BDD-based simplifications on the function.
Note
What follows was generated by the Gemini LLM. Not human verified.
The BddSimplificationPass leverages Binary Decision Diagrams (BDDs) via a
UnionQueryEngine (combining StatelessQueryEngine and BddQueryEngine) to
perform logic-level simplifications on the IR in topological order.
The pass performs the following transformations:
-
Replacing Statically Known Bits with Literals: For each non-literal
bits-typed node, the pass inspects known constant bits at the most-significant end (prefix) and least-significant end (suffix): * Fully Known Nodes: If all bits of the node are statically known, the node is replaced with aliteralat any optimization level. * Known Prefix/Suffix Splitting (whenSplitsEnabled(opt_level)is true, atopt_level >= 3): If a contiguous prefix and/or suffix of bits is constant (and not already exposed as aliteraloperand of aconcat), the node is replaced by aconcatof the known prefixliteral, abit_sliceof the remaining unknown middle bits, and the known suffixliteral. -
Removing Redundant Operands in 1-Bit Boolean Operations: For 1-bit
and,nand,or, andnoroperations with up to 10 operands (kMaxBooleanFanIn), the pass checks whether any operand is logically implied by the others (ImpliedNodeValue). Specifically, for each operand, it assumes all other non-redundant operands take the non-controlling ("ignorable") value (1forand/nand,0foror/nor). If the target operand is guaranteed to also take that non-controlling value under those assumptions, the operand is replaced with the constant1or0literal:// Original IR c: bits[1] = and(a, b) ret res: bits[1] = and(a, b, c) // Optimized IR (c is implied to be 1 whenever a == 1 and b == 1) one: bits[1] = literal(value=1) ret res: bits[1] = and(a, b, one) -
Replacing Two-Way
OneHotSelectwithSelect(whenSplitsEnabled(opt_level)is true, atopt_level >= 3): If aone_hot_selhas a 2-bit selector that BDD analysis proves is strictly one-hot (AtLeastOneBitTrueandAtMostOneBitTrue), it is replaced with a 2-wayselindexed bybit_slice(selector, start=0, width=1)withcases=[case(1), case(0)]. -
Eliminating
OneHoton Inputs with at Most One Bit Set: If BDD analysis proves that the operandxof aone_hotnode has at most one bit set (AtMostOneBitTrue(x)), theone_hotoperation is replaced withconcat(eq(x, 0), x). -
Narrowing
PrioritySelectwith Guaranteed Set Bits (whenNarrowingEnabled(opt_level)is true, atopt_level >= 2): If BDD analysis proves that at least one bit of apriority_selselector is always set (AtLeastOneBitTrue), the pass finds the lowest bit indexlast_bitsuch that at least one bit inselector[0..last_bit]is guaranteed to be true. It then slices the selector tolast_bitbits, retainscases[0..last_bit-1], and promotescase(last_bit)to be the newdefaultvalue, discarding unreachable higher-index cases and the previous default.
bitslice_simp - Bit-slice simplification
Pass which simplifies bit-slices. This includes collapsing sequential bit-slices, eliminating degenerate full-width slices, and others.
Note
What follows was generated by the Gemini LLM. Not human verified.
The BitSliceSimplificationPass optimizes bit_slice, dynamic_bit_slice,
and bit_slice_update operations in the IR. It combines local pattern
matching with a UnionQueryEngine (pairing StatelessQueryEngine with
PartialInfoQueryEngine when opt_level >= 3, or LazyTernaryQueryEngine
at lower optimization levels).
The pass first visits nodes in reverse topological order to simplify
dynamic_bit_slice and bit_slice_update nodes, and then processes all
static bit_slice nodes via a worklist until reaching a fixed point:
-
Simplifying
DynamicBitSliceOperations: * Out-of-Bounds Start: IfMinUnsignedValue(start)is at least the bit width ofto_slice, replaces the slice with a zeroliteral. * Constant Start Index: Converts adynamic_bit_slicewith a statically knownstartinto a staticbit_slice(zero-extending if the slice extends past the MSB ofto_slice). * Lifting through Select of Literals: Ifstartis produced by a tree ofsel,priority_sel, or one-hotone_hot_selnodes whose leaves are known constants, lifts the slice into the select tree so each leaf becomes a staticbit_slice:``` // Original IR s0: bits[32] = literal(value=5) s1: bits[32] = literal(value=25) start: bits[32] = sel(p, cases=[s0, s1]) ret q: bits[16] = dynamic_bit_slice(x, start, width=16) // Optimized IR slice0: bits[16] = bit_slice(x, start=5, width=16) slice1: bits[16] = bit_slice(x, start=25, width=16) ret q: bits[16] = sel(p, cases=[slice0, slice1]) ```* Scaled Start Index: When
startis a known multiple ofwidth(either becausewidthis a power of two andstarthas enough low zero bits, orstartis a non-overflowingumul(idx, width)), partitionsto_sliceintowidth-bit chunks and replaces thedynamic_bit_slicewith aselindexed by the unscaledidx(with a zero default if out-of-bounds indices are possible). -
Simplifying
BitSliceUpdateOperations: * Out-of-Bounds Start: IfMinUnsignedValue(start)is at least the width ofto_update, replaces the operation withto_update. * Constant Start Index: Replaces abit_slice_updatewith a known constantstartwith aconcatofbit_slices ofto_updateandupdate_value. * Lifting through Select of Literals: Ifstartis a select tree of known constants, lifts thebit_slice_updateinto the leaves as staticconcat/bit_sliceupdates. * Scaled Start Index: Whenstartis a known multiple of theupdate_valuewidth, slicesto_updateinto anarrayof chunks, appliesarray_updateusing the unscaled index, and flattens the updated elements back into a bit vector withconcat. -
Simplifying Static
BitSliceOperations: * Full-Width Slice: Replacesbit_slice(x, start=0, width=width(x))withx. * Collapsed Nested Slices: Combinesbit_slice(bit_slice(x, s0, w0), s1, w1)intobit_slice(x, s0 + s1, w1). * Hoisting aboveConcat(whenNarrowingEnabled(opt_level)is true, atopt_level >= 2): Rewritesbit_slice(concat(...))as aconcatof only the overlapping operands (slicing boundary operands as needed). * Pushing into Single-Use Bitwise and Low-Bit Arithmetic Operations (whenNarrowingEnabled(opt_level)is true): If abit_sliceis the sole user of a bitwise operation, or extracts the low bits (start == 0) of a single-useadd,sub, orneg, pushes thebit_sliceinto the operands so the operation runs at the narrower width. * Hoisting aboveSignExt(whenNarrowingEnabled(opt_level)is true): Simplifiesbit_slice(sign_ext(x))to a direct slice ofx(if withinx), or for a single-usesign_ext, to asign_extof a slice ofx's top bits or sign bit. * Narrowing Shifts,Decode, and Selects: When all users of an operation arebit_slices contained within a dominatingbit_slice, hoists the slice aboveshll(whenstart == 0),shrl/shra(when slicing the MSBs),decode(whenstart == 0), orsel/priority_sel/one_hot_sel(whenNarrowingEnabled(opt_level)is true), and rewrites all sibling slice users to slice from the narrowed operation.
bitwise_recombine - bitwise recombination
Pass which recombines concats of contiguous bit slices & inverted bit slices from a single source node (and constants) into masked bitwise operations.
The pass uses 1D dynamic programming optimal partitioning to balance readability: - Identifies localized sub-runs that can be merged into clean 1-gate masks (nibble-aligned or periodic, e.g. x ^ 0x5555). - Naturally peels boundary constants (e.g. address alignment or padding) to form clean hybrid concats like {x[31:8] ^ 24'h555555, 8'b0}. - Preserves coarse struct/bus layouts where non-aligned hex masks would be unreadable. - Recombines dense bit-salad into 2-gate operations when the splinter count is high.
Recombined operations are composed in NOT -> AND -> XOR -> OR order: - all inverted slices => not(x) - raw and inverted slices => (x ^ mask) - raw slices and 0 literals => (x & mask) - raw slices and 1 literals => (x | mask) - raw slices, 0s, and 1s (no inv) => ((x & mask_and) | mask_or) - inverted and 1s (no raw) => (not(x) | mask_or) - raw, inverted, and 1s => ((x ^ mask_xor) | mask_or) - inverted and 0s (no raw) => (not(x) & mask_and) - raw, inverted, and 0s => ((x & mask_and) ^ mask_xor) - inverted, 0s, and 1s (no raw) => ((not(x) & mask_and) | mask_or) - all four (raw, inv, 0s, 1s) => ((x & mask_and) ^ mask_xor)
This is typically run late in the compiler pipeline (e.g. in codegen 1.5 block cleanup and optimization) to fold un-cancelled bitwise splits back into clean, idiomatic hardware operations before Verilog emission.
Note
What follows was generated by the Gemini LLM. Not human verified.
The BitwiseRecombinationPass acts as a counterpart to
BitwiseSimplificationPass and is intended to run after bitwise
simplification has finished. While BitwiseSimplificationPass splits
masked bitwise operations into concats of bit_slices, literals, and
nots to expose bit-level simplification opportunities, any remaining
un-cancelled splinters can produce verbose bit-slice concatenations.
BitwiseRecombinationPass re-folds contiguous runs of slices and constants
back into concise, readable bitwise operations.
How it Works:
-
Operand Classification (
ClassifyOperand): For eachconcatnode, the pass classifies every operand into one of fourSliceElementKindcategories if possible: *kRaw:bit_slice(x, start, width)or a fullbits-typed nodex(start = 0). *kInverted:not(bit_slice(x, start, width)),bit_slice(not(x), start, width), ornot(x). *kZero: An all-zerosliteralof widthw. *kOne: An all-onesliteralof widthw. -
Contiguous Run Formation (
TryFormRun): A candidate sub-span ofconcatoperands (ordered MSB-to-LSB) forms a valid contiguous run if all non-literal slices reference the same source nodexand their bit offsets (with literal widths filling the exact intervening bit ranges) form a contiguous, in-bounds slice ofx. -
Cost Model and 1D Dynamic Programming (
SimplifyConcat): To avoid merging coarse bus fields into unreadable hex masks, the pass evaluates candidate runs withEvaluateSegmentCost: * Mask Periodicity (GetMaskPeriodicity): Masks that are all zeros, nibble-aligned all ones, or periodically repeating at the largest power-of-two periodp <= 16with2 * p <= hex_widthand2 <= p < widthwhose virtual top-nibble continuation bits are all zeros are classified askCleanand incur no penalty. Non-nibble-aligned all-ones masks and periodic masks whose virtual top-nibble continuation bits are nonzero are classified askAlmostCleanand incur a flat penalty of1. Non-periodic (kUnclean) masks incur a readability penalty proportional to their bit width (1penalty unit per 8 bits). * Gate Costs: Unarynotcosts 1, each binary mask operation costs 2 plus its mask periodicity penalty, and using two binary masks incurs an extra penalty of 1. * DP Partitioning: A 1D dynamic program finds the minimum-cost partitioning of theconcatoperands into segments, favoring shorter (unmerged) segments on ties. -
Recombination Synthesis (
RecombineRun): Each merged segment of length>= 2is synthesized over a single basebit_slice(or the full source nodex) using at most two binary bitwise gates innot -> and -> xor -> ororder. When all four element kinds (kRaw,kInverted,kZero,kOne) are present, theandmask clears bothkZeroandkOnebitfields so the subsequentxormask can simultaneously invertkInvertedbits and setkOnebits without a third gate.
Example:
// Original IR (alternating raw/inverted nibbles with low zero padding)
slice4: bits[4] = bit_slice(x, start=16, width=4)
slice3: bits[4] = bit_slice(x, start=12, width=4)
inv3: bits[4] = not(slice3)
slice2: bits[4] = bit_slice(x, start=8, width=4)
slice1: bits[4] = bit_slice(x, start=4, width=4)
inv1: bits[4] = not(slice1)
z0: bits[4] = literal(value=0)
ret res: bits[20] = concat(slice4, inv3, slice2, inv1, z0)
// Optimized IR (after dead code elimination; peels low zero padding and
// recombines upper 16 bits into periodic XOR)
hi: bits[16] = bit_slice(x, start=4, width=16)
mask: bits[16] = literal(value=0x0f0f)
xored: bits[16] = xor(hi, mask)
z0: bits[4] = literal(value=0)
ret res: bits[20] = concat(xored, z0)
bitwise_simp - bitwise simplification
Pass which simplifies bitwise operations (AND, OR, XOR) with constant masks by transforming them into concats of BitSlices, Literals, and Nots. This optimization is only enabled when SplitsEnabled is true.
Note
What follows was generated by the Gemini LLM. Not human verified.
The BitwiseSimplificationPass simplifies and, or, and xor operations
using per-bit ternary knowledge from a UnionQueryEngine (combining
StatelessQueryEngine and PartialInfoQueryEngine).
How it Works:
-
Full Constant Folding and Inversion (All Optimization Levels): * If the query engine determines that all bits of an
and,or, orxornode are statically known, the node is replaced with aliteral. * WhenSplitsEnabled(opt_level)is false (opt_level < 3), if anxorhas a single non-constant operand and its accumulated constant mask is all ones, it is simplified tonot(x). -
Bitwise Mask Decomposition (when
SplitsEnabled(opt_level)is true, atopt_level >= 3): * Mask Accumulation: Across all operands of anand,or, orxornode, the pass accumulates a composite mask of known bits: * Forandandor, known bits from both fully known and partially known operands are intersected (and) or unioned (or) into the composite mask (with unknown bits set to the identity value:1forand,0foror). * Forxor, fully known constant operands are XORed into the composite mask. * Contiguous Run Splitting: If the composite mask is not the identity (all ones forand, all zeros foror/xor), the bit width is partitioned into maximal contiguous runs[pos, end)where the mask bit is uniform: * Absorbing Runs (0inand,1inor): Replaced with a constant0orall_onesliteralof widthend - pos. * Identity or Inverting Runs (1inand,0inor, or any run inxor): Each non-constant operand whose bits in[pos, end)are not already known to be the identity is sliced tobit_slice(op, pos, end - pos). If multiple sliced operands remain, they are combined with a narrowerand/or/xor; forxorruns where the mask bit is1, the slice (or narrowerxor) is inverted withnot. * Reassembly: The resulting per-run nodes are joined from MSB to LSB usingconcat, exposing narrower slices and constants to downstream passes such asBitSliceSimplificationPass.
Example:
// Original IR
mask: bits[8] = literal(value=0xf0)
ret res: bits[8] = and(x, mask)
// Optimized IR (when SplitsEnabled is true)
hi: bits[4] = bit_slice(x, start=4, width=4)
lo_zero: bits[4] = literal(value=0)
ret res: bits[8] = concat(hi, lo_zero)
bool_simp - boolean simplification
Attempts to simplify bitwise / boolean expressions (e.g. of multiple variables).
Note
What follows was generated by the Gemini LLM. Not human verified.
The BooleanSimplificationPass simplifies clusters of bit-parallel Boolean
operations (and, or, nand, nor, and not) over arbitrary bit-width
bits[N] values by evaluating their local truth tables over up to 3 input
frontier nodes and replacing them with a single canonical logical operation
or constant literal.
How it Works:
-
Frontier Tracking (
BooleanFlowTracker): A DFS visitor traversesand,or,nand,nor, andnotnodes, computing for each node the set of "frontier" inputs (operands not produced by one of those five logical operations). If a node depends on 2 or 3 unique frontier nodes (X,Y, and optionallyZ, up tokMaxFrontierNodes = 3), it is eligible for truth-table simplification. Subgraphs that depend on more than 3 frontier nodes are marked withTooManySentineland skipped. -
8-Bit Truth Table Evaluation (
FlowFromFrontierToNode): The frontier nodes are assigned 8-bit initial truth-table vectors representing all 8 input combinations of(X, Y, Z):X (frontier[0]): 0b00001111 Y (frontier[1]): 0b00110011 Z (frontier[2]): 0b01010101The pass recursively evaluates the intermediate bitwise operations (
and,or,nand,nor,not) with memoization to compute the resulting 8-bit truth table at the target node (for example,and(X, Y)produces0b00000011). -
Canonical Lookup and Replacement (
ResolveTruthTable): * Tautology / Contradiction: If the resulting 8-bit truth table is0b11111111or0b00000000, the node is replaced with an all-ones (-1) or all-zeros (0)literalof the node's bit width. * Precomputed Single-Gate Table (GetTruthTables): Otherwise, the 8-bit vector is looked up in a memoized table of canonical forms populated in increasing cost order: 1. A single frontier operand or its negation (xornot(x)). 2. A single N-ary operation (nand,nor,xor,and,or) over 2 or 3 unnegated frontier operands. 3. A single N-ary operation (nand,nor,xor,and,or) over 2 or 3 frontier operands where one or more inputs are negated withnot. * If a match is found and the node is not already in that minimal form (MatchesSymmetrical), the node is replaced with the canonical expression.
Example:
// Original IR
fn f(x: bits[42], y: bits[42]) -> bits[42] {
and_op: bits[42] = and(x, y)
ret not_op: bits[42] = not(and_op)
}
// Optimized IR (after dead code elimination)
fn f(x: bits[42], y: bits[42]) -> bits[42] {
ret nand_op: bits[42] = nand(x, y)
}
canon - Canonicalization
IR Canonicalization.
Note
What follows was generated by the Gemini LLM. Not human verified.
The CanonicalizationPass transforms the IR into a standardized, canonical
form by iteratively applying local rewrite rules to a fixed point
(TransformNodesToFixedPoint) using a StatelessQueryEngine. Establishing
consistent structural patterns for common expressions reduces the number of
syntactic variations that downstream optimization passes need to match.
Key canonicalizations include:
-
Moving Constants to the Right in Commutative and Comparison Ops: For binary commutative operations (such as
add,umul,and,or,xor,eq,ne) and ordered comparison operations, if operand 0 is a known constant and operand 1 is not, the operands are swapped so the constant is on the right-hand side. Comparison opcodes are reversed accordingly (e.g.,ult(C, x)becomesugt(x, C)).one: bits[2] = literal(value=1) ret addval: bits[2] = add(one, x)becomes:
one: bits[2] = literal(value=1) ret addval: bits[2] = add(x, one) -
Strict Unsigned Comparisons Against Constants: Non-strict unsigned comparisons with a constant on the right-hand side are converted to strict comparisons by adjusting the constant: *
uge(x, K)(whereK > 0) becomesugt(x, K - 1). *ule(x, K)(whereK < MAX) becomesult(x, K + 1). -
Canonicalizing Unsigned Clamp (Min/Max) Expressions: Two-way
selectoperations driven by an unsigned comparison (ugtorult) that clamp a valuexto a constant boundKare rewritten into a standard form: * Clamp high:x > K - 1 ? K : x,x < K ? x : K, andx < K + 1 ? x : Kall canonicalize tosel(ugt(x, K), cases=[x, K]). * Clamp low:x < K + 1 ? K : x,x > K ? x : K, andx > K - 1 ? x : Kall canonicalize tosel(ult(x, K), cases=[x, K]). -
Converting Subtraction of a Constant to Addition:
sub(x, K)whereKis a known constant is replaced withadd(x, -K)using the two's complement negation ofK.one: bits[2] = literal(value=1) ret subval: bits[2] = sub(x, one)becomes:
three: bits[2] = literal(value=3) ret addval: bits[2] = add(x, three) -
Removing No-Op Bit Extensions: Any
zero_extorsign_extoperation whose target bit width equals its operand's bit width is replaced directly by its operand. -
Replacing Zero-Extend with Concat: A widening
zero_extoperation is replaced with aconcatthat prepends a zero literal of the extension width to the operand.ret ext: bits[42] = zero_ext(x, new_bit_count=42) // x: bits[33]becomes:
zero: bits[9] = literal(value=0) ret ext: bits[42] = concat(zero, x) -
Removing Single-Bit Bitwise Reductions: Bitwise reduction operations (
and_reduce,or_reduce,xor_reduce) applied to a 1-bit operand are replaced with the operand itself. -
Eliminating Negated Selectors in Binary Selects: If a 2-case binary
select(with no default) hasnot(p)as its selector, thenotis bypassed and the two cases are swapped.not_p: bits[1] = not(p) ret result: bits[8] = sel(not_p, cases=[x, y])becomes:
ret result: bits[8] = sel(p, cases=[y, x]) -
Promoting Single-Value Defaults in Selects: If a
select(with selector width < 63) has adefaultvalue that only covers a single remaining selector value (cases.size() + 1 == 2^width), thedefaultvalue is appended tocasesand removed. -
Simplifying Constant Predicates on
next_valueandstate_read: * If anext_valueorstate_readhas a known1predicate, the predicate is removed to make the operation unconditional. * If anext_valuehas a known0predicate, it is replaced with an empty tuple literal()and removed. Whendecouple_state_accessis enabled, astate_readwith a known0predicate is similarly replaced with a zero literal and removed (in coupled mode it is preserved for downstream state legalization).
canonicalize_proc_state - canonicalize proc state representation
Bring proc-state representation to the canonical 'flat' representationother passes expect.
Options Set
Run to a fixedpoint.
Invoked Passes
- fixedpoint_proc_state_flattening
- proc_state_bits_shatter
- proc_state_tuple_flat
- ident_remove
- dataflow
- dce
channel_legalization - Legalize multiple send/recvs per channel
Pass that legalizes multiple send/receive operations per channel.
This pass adds cross-activation tokens to guarantee that later activations of a proc cannot send or receive on a channel until all previous activations have completed working with that channel.
Note
What follows was generated by the Gemini LLM. Not human verified.
The ChannelLegalizationPass legalizes streaming channels (kStreaming)
that are accessed by multiple send or multiple receive operations within
a Proc. All multiple sends (or multiple receives) on a channel must reside
in the same Proc, map uniquely to that channel, and (for receives) be
blocking.
For each streaming channel with multiple sends or receives, the pass performs two steps:
-
Strictness Verification and Mutual Exclusion (
CheckMutualExclusion): The pass builds a projected token dependency DAG (GetProjectedDAG) over the channel's operations and enforces the channel'sChannelStrictness: *kTotalOrder: Verifies (CheckProjectedDAG) that the existing token DAG already forms a strict linear chain where the first operation depends only on tokenparam(s) and each subsequent operation depends on the previous one. *kRuntimeOrdered: Respects existing token dependencies; for any pair of operations not ordered by a token dependency chain, inserts a runtimeassertchecking that their predicates are not simultaneously true (or fails at compile time if both are unconditional). *kProvenMutuallyExclusive: Ignores token dependencies and uses a Z3 SMT solver (solvers::SolverKind::kZ3) with proc state assumptions (GetProcStateAssumptions) to formally prove at compile time that at most one operation on the channel can be active per activation. *kRuntimeMutuallyExclusive: Ignores token dependencies and inserts a runtimeassertchecking that no other operation on the channel is active in the same activation. *kArbitraryStaticOrder: Imposes a total topological order in the projected DAG so all operations are treated as ordered. -
Cross-Activation Token Insertion: To ensure that an activation cannot issue a
sendorreceiveon the channel before all operations on that channel from previous activations have completed: * For each operation in the group, atoken-typed state element (implicit_token__<op_name>) is appended to theProc. * Anext_valuenode updates that state element with the operation's output token (tuple_index(recv, index=0)forreceive, orsenditself forsend), gated by the operation'spredicate. * Each operation's input token is replaced with anafter_allcombining its original input token with thestate_reads of all newly added implicit token state elements for that channel.
Example:
chan in(bits[32], id=0, kind=streaming, ops=receive_only,
flow_control=ready_valid, strictness=proven_mutually_exclusive)
top proc my_proc() {
tok: token = literal(value=token)
recv0: (token, bits[32]) = receive(tok, predicate=p0, channel=in)
recv1: (token, bits[32]) = receive(tok, predicate=p1, channel=in)
}
After ChannelLegalizationPass (assuming Z3 proves !(p0 && p1)):
top proc my_proc(implicit_token__recv0: token,
implicit_token__recv1: token, init={token, token}) {
tok: token = literal(value=token)
prev_tok0: token = state_read(state_element=implicit_token__recv0)
prev_tok1: token = state_read(state_element=implicit_token__recv1)
tok_all0: token = after_all(tok, prev_tok0, prev_tok1)
recv0: (token, bits[32]) = receive(tok_all0, predicate=p0, channel=in)
recv0_tok: token = tuple_index(recv0, index=0)
next_tok0: () = next_value(state_element=implicit_token__recv0,
value=recv0_tok, predicate=p0)
tok_all1: token = after_all(tok, prev_tok0, prev_tok1)
recv1: (token, bits[32]) = receive(tok_all1, predicate=p1, channel=in)
recv1_tok: token = tuple_index(recv1, index=0)
next_tok1: () = next_value(state_element=implicit_token__recv1,
value=recv1_tok, predicate=p1)
}
collapse_select_chains - BDD-based Select Chain Collapsing
Pass which collapses chains of selects with disjoint selectors into a single one-hot-select.
Chains of binary select operations, particularly where one case of a
select feeds into another select (e.g.,
sel(pred_a, {val_a, sel(pred_b, {val_b, default_val})})), are transformed
into a single one_hot_select if the selectors are provably disjoint (at
most one can be true at any given time). This simplifies the IR structure and
can lead to more efficient hardware implementations.
Note
What follows was generated by the Gemini LLM. Not human verified.
The CollapseSelectChainsPass identifies chains of select operations whose
selector bits are mutually exclusive and collapses them into a single
one_hot_sel operation, reducing logic depth and mux delay.
How it Works:
-
Query Engine Setup: The pass uses a
UnionQueryEnginecombining aStatelessQueryEngineand aBddQueryEngineto reason about Boolean relationships (such as mutual exclusivity and exhaustiveness) among selector bits. -
Chain Discovery (
GetSelectNodeChains): The pass traverses the function in reverse topological order (ReverseTopoSort) to build chains ofbits-typed select operations (IsChainableSelect, sorted by root node ID in ascending order) where the fall-through branch of one select feeds into a single-use inner select: * Binarysel: Either a 2-caseselwithout a default (wherecase[1]is the selected value whenselector == 1andcase[0]is the fall-through) or a 1-caseselwith a 1-bit selector and adefault(wheredefaultis selected whenselector == 1andcase[0]is the fall-through). *priority_sel: Contributes all of itscases(selected by bits0..N-1of its selector) and chains through itsdefault_value. *one_hot_sel: Contributes all of itscasesand terminates the chain (with nofinal_default). -
Subchain Selection and Profitability (
DetermineBestSelectSubchain): * Searches from the root of each chain toward the leaf across contiguous subchains whose selector bit locations (TreeBitLocation) satisfyquery_engine.AtMostOneTrue(...), selecting the mutually exclusive subchain with the most total cases (breaking ties in favor of subchains closer to the root). * Length Threshold: To avoid interfering with other select optimizations on small mux trees, a subchain is only collapsed if it contains more than 4 total active cases (total_cases > 4, i.e., at least 5 cases) and has at least 2 select nodes (subchain_length > 1). * Default Computation and Elimination: If the selected subchain ends before the leaf of the full chain, the next select node in the chain becomes the subchain'sfinal_default. If the subchain has afinal_defaultandquery_engine.AtLeastOneTrue(...)proves that at least one selector bit in the subchain is always active, the unreachablefinal_defaultis dropped. -
Collapsing to
one_hot_sel(CollapseSelectNodeChain): * Iffinal_defaultmay still be reached (all selector bits can be simultaneously zero), a default selector bit is constructed as the conjunction (and) ofeq(selector, 0)across all selects in the subchain, andfinal_defaultis placed ascase[0](the LSB case). * Active cases are ordered from the leaf of the subchain to the root. * The new selector is formed by concatenating the subchain selectors from root (MSB) to leaf, followed by the default selector bit (LSB) if present, and the root select is replaced withone_hot_sel.
Example (5 mutually exclusive predicates p0..p4 where at most one is 1):
s0: bits[8] = sel(p0, cases=[d, v0])
s1: bits[8] = sel(p1, cases=[s0, v1])
s2: bits[8] = sel(p2, cases=[s1, v2])
s3: bits[8] = sel(p3, cases=[s2, v3])
ret s4: bits[8] = sel(p4, cases=[s3, v4])
becomes:
z0: bits[1] = eq(p0, literal(0))
z1: bits[1] = eq(p1, literal(0))
z2: bits[1] = eq(p2, literal(0))
z3: bits[1] = eq(p3, literal(0))
z4: bits[1] = eq(p4, literal(0))
all_zero: bits[1] = and(z4, z3, z2, z1, z0)
sel_bits: bits[6] = concat(p4, p3, p2, p1, p0, all_zero)
ret s4: bits[8] = one_hot_sel(sel_bits, cases=[d, v0, v1, v2, v3, v4])
comparison_simp - Comparison Simplification
Simplifies logical operations on the results of comparison operations. For example:
eq(x, 0) && ne(x, 1) => eq(x, 0) eq(x, 0) && ne(x, 0) => 0 eq(x, 0) || ne(x, 0) => 1
Note
What follows was generated by the Gemini LLM. Not human verified.
The ComparisonSimplificationPass simplifies comparisons and Boolean logic
trees over comparisons across three stages in a topological traversal:
-
Range-Equivalence Simplification (
ComputeRangeEquivalence): * Using aStatelessQueryEngine, the pass maps 1-bit nodes to aRangeEquivalence{node, IntervalSet}, indicating that the 1-bit node evaluates to1if and only ifnodelies withinIntervalSet. * Base intervals are seeded from comparisons against known constants (eq,ne,ult,ugt) and propagated throughand,or,not,nand, andnoroperations whose operands all constrain the same underlyingnode(using interval intersection, union, and complement). * Each node with a computedRangeEquivalence{x, range}is simplified based on its normalizedIntervalSet(skipping nodes that are already in minimal comparison form or that are singlenotinversions of multi-use comparisons): * Maximal range: Replaced withliteral(1). * Empty range: Replaced withliteral(0). * Single value[C, C]: Replaced witheq(x, C). * Complement of a single valueC: Replaced withne(x, C). * Contiguous prefix[0, C - 1]: Replaced withult(x, C). * Contiguous suffix[C + 1, MAX]: Replaced withugt(x, C). -
Removing Non-Wrapping Unit Offsets (
SimplifyComparisonWithUnitOffset): * Rewrites ordered signed and unsigned comparisons (ult,ule,ugt,uge,slt,sle,sgt,sge) where one operand adds or subtracts1(+ 1or- 1), toggling strictness to eliminate the offset whenPartialInfoQueryEngineproves the base operand cannot take on the wrapping boundary value (MAXfor+ 1,MINfor- 1): *a < b + 1=>a <= b*a >= b + 1=>a > b*a <= b - 1=>a < b*a > b - 1=>a >= b -
Deduplicating Derived Comparisons (
TransformDerivedComparisons): * Scans comparisons in topological order and reuses an earlier comparison (a cmp b) when a later comparison is: * Commuted (e.g.,ult(b, a)becomesugt(a, b)). * Inverted (e.g.,ule(a, b)becomesnot(ugt(a, b))). * Commuted and inverted (e.g.,uge(b, a)becomesnot(ugt(a, b))).
Example (eq(x, 0) && ne(x, 1)):
fn f(x: bits[32]) -> bits[1] {
literal.0: bits[32] = literal(value=0)
literal.1: bits[32] = literal(value=1)
x_eq_0: bits[1] = eq(x, literal.0)
x_ne_1: bits[1] = ne(x, literal.1)
ret and.final: bits[1] = and(x_eq_0, x_ne_1)
}
ComputeRangeEquivalence maps x_eq_0 to [[0, 0]] and x_ne_1 to
[[0, 0], [2, MAX]]. Their intersection at and.final is [[0, 0]], so
and.final is replaced with a single equality comparison (shown after dead
code elimination):
fn f(x: bits[32]) -> bits[1] {
literal.0: bits[32] = literal(value=0)
ret eq.final: bits[1] = eq(x, literal.0)
}
concat_select_removal - Concat Select Removal
Replaces a concat of selects with the same selectors with a single select of concats. This seems to be optimized better by synthesis tools.
For example, (concat (select a b c) (select a d e)) would be replaced with (select a (concat b d) (concat c e))
Or (concat X (select a b c) (select a d e) Y) would be replaced with (Concat X (select a (concat b d) (concat c e)) Y)
We will not add additional bit-slices to support things like (concat (select a b c) X (select a d e)) TODO(allight): Should we do this?
Nor will we combine selects with unlike selectors. (concat (select a b c) (select d e f))
Note
What follows was generated by the Gemini LLM. Not human verified.
The ConcatSelectRemovalPass hoists select operations (sel,
priority_sel, and one_hot_sel, represented uniformly via GenericSelect)
above concat operations when adjacent operands of a concat share the
same select kind and selector. Combining narrow parallel selects with
identical control into a single wider select over concatenated data branches
reduces control fanout and improves synthesis quality.
How it Works:
-
Identifying Mergeable Runs (
FindConcatSelects,CanMerge,PickTransform): * The pass traverses nodes in topological order and inspects eachconcatoperation using aStatelessQueryEngine. * Adjacentconcatoperands that are select operations can be merged (CanMerge) if: * They have the sameGenericSelectkind (sel,priority_sel, orone_hot_sel). * Their selectors are provably equal viaNodesKnownUnsignedEquals(a.selector(), b.selector()). * In scheduled functions (IsScheduled()), both select nodes are staged (IsStaged()) and belong to the same pipeline stage (GetStageIndex). * Contiguous runs of 2 or more compatible selects within aconcat's operands are grouped for merging, while non-select operands (or single unmerged selects) are preserved in place. -
Rewriting to Select of Concats (
TransformToSelectOfConcats,DoTransform): * For each mergeable run of selects, the pass determines the maximum number of explicitcases(and whether adefaultvalue is needed) from the select in the run with the most explicit cases. * For each case indexi(and for thedefaultbranch, if present), it collects thei-th case from every select in the run (using a select'sdefault_valuewheni >= select.cases().size()) and concatenates them into a newconcatnode. * It creates a single merged select (CloneSelectLike) choosing among the per-caseconcatnodes. If the function is scheduled, all newconcatnodes and the merged select are added to the original stage (AddNodeToStage). * If all operands of the originalconcatwere merged into a single select, theconcatis replaced directly by that select; otherwise, it is replaced by an outerconcatcombining the unmerged operands and the newly merged select(s).
Example:
fn f(s: bits[1], a: bits[4], b: bits[4],
c: bits[8], d: bits[8]) -> bits[12] {
sel_hi: bits[4] = sel(s, cases=[a, b])
sel_lo: bits[8] = sel(s, cases=[c, d])
ret result: bits[12] = concat(sel_hi, sel_lo)
}
becomes:
fn f(s: bits[1], a: bits[4], b: bits[4],
c: bits[8], d: bits[8]) -> bits[12] {
case_0: bits[12] = concat(a, c)
case_1: bits[12] = concat(b, d)
ret result: bits[12] = sel(s, cases=[case_0, case_1])
}
concat_simp - Concat simplification
Pass which simplifies concats. This includes removing single-operand concats, flattening trees of dependent concats, and others.
Note
What follows was generated by the Gemini LLM. Not human verified.
The ConcatSimplificationPass simplifies concat operations and optimizes
operations that consume or feed into concats. It first processes concat
nodes iteratively using a worklist (so newly created or modified concats
are re-evaluated), and then performs a topological pass over the graph when
narrowing optimizations are enabled (options.narrowing_enabled()).
Key optimizations include:
-
Removing Single-Operand Concats: A
concatwith a single operand is replaced directly by that operand:concat(x) => x -
Flattening Trees of Concats (
FlattenConcatTree): Nestedconcatoperations are flattened into a singleconcat:concat(a, b, concat(c, concat(d, e))) => concat(a, b, c, d, e) -
Merging Consecutive Constant Operands (
ReplaceConsecutiveConstantOperands): Using aStatelessQueryEngine, consecutive operands with known constant values are merged into a single widerliteraloperand. -
Eliminating Zero-Bit Operands: Any
bits[0]operands are removed from theconcatoperand list. -
Hoisting
reverseAboveconcat(whenNarrowingEnabled): IfNarrowingEnabled(opt_level)is true and aconcathas a singlereverseuser (and no other users besides bitwise reductions), thereverseis distributed to each operand in reverse order:reverse(concat(a, b, c)) => concat(reverse(c), reverse(b), reverse(a)) -
Merging Consecutive Forward Bit Slices (
ReplaceConsecutiveBitSlices): Consecutivebit_sliceoperands slicing contiguous ranges from the same source node in descending bit order (slice.start + slice.width == prev.start) are merged into a single widerbit_slice(or replaced by the source node itself if the merged slice covers the full bit width):concat(bit_slice(x, start=4, width=4), bit_slice(x, start=0, width=4)) // => x (when x is bits[8]) -
Merging Consecutive Reversed Bit Slices (
ReplaceConsecutiveReversedSlices): Consecutive operands that are eitherreverse(bit_slice(x, ...))or 1-bitbit_slice(x, start, 1)(which are trivially self-reversed) from the same source node in ascending bit order (prev.start + prev.width == slice.start) are merged into a singlereverse(bit_slice(x, ...))(orreverse(x)if covering the full source width):concat(reverse(bit_slice(x, start=0, width=4)), reverse(bit_slice(x, start=4, width=4))) // => reverse(x) (when x is bits[8]) -
Narrowing and Hoisting Binary Bitwise Users of Padded Concats (
TryNarrowAndHoistBitWiseOperation, whennarrowing_enabled()): When a 2-operandconcathas one variable operand and one constant operand that is all-zeros (0) or all-ones (~0) of at least 6 bits (kMinNarrowingBits = 6), binary bitwise users (and,or,xor) are narrowed to operate only on the variable bits: * Masking constant (andwith0, ororwith~0): The constant bits pass through unchanged to the newconcat. * Identity constant (xorwith0,orwith0, orandwith~0): The corresponding bits of the other operand are sliced and concatenated alongside the narrowed bitwise operation.// Given x: bits[10], b: bits[4] or(x, concat(0b111111, b)) // => concat(0b111111, or(bit_slice(x, start=0, width=4), b)) -
Hoisting Bitwise Operations Above Concats (
TryHoistBitWiseOperationandTryHoistBitWiseWithConstant, whennarrowing_enabled()): * If a binary bitwise operation has one known-constant operand and oneconcatoperand, the operation is distributed across eachconcatoperand using slices of the constant. * If all operands of a bitwise operation areconcats, the pass finds the union of bit-range boundaries across the inputconcats (GetBitRangeUnionOfInputConcats), slices each inputconcatto those aligned sub-ranges, applies the bitwise operation to each sub-range, and concatenates the results:xor(concat(a, b), concat(c, d)) => concat(xor(a, c), xor(b, d)) -
Distributing
eqandneAcross Concats (TryDistributeReducibleOperation, whennarrowing_enabled()): Distributes equality (eq) and inequality (ne) comparisons with aconcatacross theconcat's operands by slicing the other comparison operand to match each piece and combining the element-wise comparisons withand(foreq) oror(forne):// Given x: bits[5], y: bits[10], z: bits[15] eq(concat(x, y), z) // => and(eq(x, bit_slice(z, start=10, width=5)), // eq(y, bit_slice(z, start=0, width=10))) -
Bypassing Bitwise Reductions of Concats (
TryBypassReductionOfConcatenation, whennarrowing_enabled()): Replacesand_reduce,or_reduce, orxor_reduceof aconcatwith anand,or, orxorof the reductions of each non-zero-width operand (using 1-bit operands directly without a reduction node):or_reduce(concat(a, b)) => or(or_reduce(a), or_reduce(b))
cond_spec(Bdd) - Conditional specialization
Pass which specializes arms of select operations based on their selector
value. When analyzing a particular arm of a sel, the value of the
selector is known. This knowledge can be used to simplify the expression
within the arm.
Note
What follows was generated by the Gemini LLM. Not human verified.
For example, consider the following IR:
fn f(a: bits[1], b: bits[31], z: bits[32]) -> bits[32] {
concat: bits[32] = concat(a, b)
ret sel.2: bits[32] = sel(a, cases=[z, concat])
}
In the sel operation, the selector is a. When considering case[1] (the
concat operation), we know that a must have the value 1. Therefore, the
concat(a, b) can be simplified to concat(1, b). The pass will transform
the sel to:
sel.2: bits[32] = sel(a, cases=[z, concat(literal(1), b)])
This optimization applies to sel, priority_sel, and one_hot_sel. It can
also use Binary Decision Diagrams (BDDs) for more powerful analysis of the
conditions.
cond_spec(false) - Conditional specialization
Pass which specializes arms of select operations based on their selector
value. When analyzing a particular arm of a sel, the value of the
selector is known. This knowledge can be used to simplify the expression
within the arm.
Note
What follows was generated by the Gemini LLM. Not human verified.
For example, consider the following IR:
fn f(a: bits[1], b: bits[31], z: bits[32]) -> bits[32] {
concat: bits[32] = concat(a, b)
ret sel.2: bits[32] = sel(a, cases=[z, concat])
}
In the sel operation, the selector is a. When considering case[1] (the
concat operation), we know that a must have the value 1. Therefore, the
concat(a, b) can be simplified to concat(1, b). The pass will transform
the sel to:
sel.2: bits[32] = sel(a, cases=[z, concat(literal(1), b)])
This optimization applies to sel, priority_sel, and one_hot_sel. It can
also use Binary Decision Diagrams (BDDs) for more powerful analysis of the
conditions.
cond_spec(noBdd) - Conditional specialization
Pass which specializes arms of select operations based on their selector
value. When analyzing a particular arm of a sel, the value of the
selector is known. This knowledge can be used to simplify the expression
within the arm.
Note
What follows was generated by the Gemini LLM. Not human verified.
For example, consider the following IR:
fn f(a: bits[1], b: bits[31], z: bits[32]) -> bits[32] {
concat: bits[32] = concat(a, b)
ret sel.2: bits[32] = sel(a, cases=[z, concat])
}
In the sel operation, the selector is a. When considering case[1] (the
concat operation), we know that a must have the value 1. Therefore, the
concat(a, b) can be simplified to concat(1, b). The pass will transform
the sel to:
sel.2: bits[32] = sel(a, cases=[z, concat(literal(1), b)])
This optimization applies to sel, priority_sel, and one_hot_sel. It can
also use Binary Decision Diagrams (BDDs) for more powerful analysis of the
conditions.
cond_spec(true) - Conditional specialization
Pass which specializes arms of select operations based on their selector
value. When analyzing a particular arm of a sel, the value of the
selector is known. This knowledge can be used to simplify the expression
within the arm.
Note
What follows was generated by the Gemini LLM. Not human verified.
For example, consider the following IR:
fn f(a: bits[1], b: bits[31], z: bits[32]) -> bits[32] {
concat: bits[32] = concat(a, b)
ret sel.2: bits[32] = sel(a, cases=[z, concat])
}
In the sel operation, the selector is a. When considering case[1] (the
concat operation), we know that a must have the value 1. Therefore, the
concat(a, b) can be simplified to concat(1, b). The pass will transform
the sel to:
sel.2: bits[32] = sel(a, cases=[z, concat(literal(1), b)])
This optimization applies to sel, priority_sel, and one_hot_sel. It can
also use Binary Decision Diagrams (BDDs) for more powerful analysis of the
conditions.
const_fold - Constant folding
Pass which performs constant folding. Every op with only literal operands is replaced by an equivalent literal.
Note
What follows was generated by the Gemini LLM. Not human verified.
The ConstantFoldingPass evaluates operations whose operands are all known
compile-time constants and replaces their uses with a new literal node
containing the computed result.
How it Works:
The pass traverses the nodes of a FunctionBase in topological order
(context.TopoSort(f)) using a StatelessQueryEngine. Because nodes are
visited in topological order, replacing an operation with a literal
immediately exposes that constant to downstream users during the same pass,
folding entire constant subgraphs in a single traversal.
A node is eligible for constant folding (NodeIsConstantFoldable) if all of
the following hold:
- Has Users or Implicit Use: The node has at least one user or is
implicitly used by the
FunctionBase(such as a function return value). - Not Already a Literal: The node is not already a
literal. - No Token Types: The node's type does not contain a
token(!TypeHasToken(node->GetType())). - Not Side-Effecting (Except
gate): Side-effecting operations cannot be folded, with the exception ofgate, which can be folded when its condition and data operands are constant. - All Operands Are Known Constants: Every operand is fully known
according to
StatelessQueryEngine::IsFullyKnown.
For each eligible node, the pass extracts the constant Value of each
operand, evaluates the node via InterpretNode, and replaces its uses with
a newly created literal node (ReplaceUsesWithNew<Literal>). The pass
does not delete the replaced nodes itself; they are cleaned up by subsequent
DeadCodeEliminationPass runs.
Example:
fn IdenticalLiterals() -> bits[8] {
literal.1: bits[8] = literal(value=42)
literal.2: bits[8] = literal(value=123)
ret add.3: bits[8] = add(literal.1, literal.2)
}
After ConstantFoldingPass (and subsequent dead code elimination):
fn IdenticalLiterals() -> bits[8] {
ret literal.4: bits[8] = literal(value=165)
}
cse - Common subexpression elimination
Pass which performs common subexpression elimination. Equivalent ops with the same operands are commoned. The pass can find arbitrarily large common expressions.
Note
What follows was generated by the Gemini LLM. Not human verified.
The CsePass (Common Subexpression Elimination) identifies and merges
equivalent computations within a FunctionBase. Because it traverses the IR
in topological order and canonicalizes operands to unique arena pointers, it
can detect and merge arbitrarily deep isomorphic expression trees in a single
pass.
How it Works:
-
Canonical Node Representation (
CseNodeandCseNodeArena): As the pass visits each live node (!node->IsDead()) in topological order,CseNodeArenainterns a canonicalCseNodekey consisting of: * Opcode (Op) and Result Type (Type*). * Canonical Operands (std::vector<CseNode*>): Pointers to the already-internedCseNodes of the node's operands. For commutative operations (OpIsCommutative), operand pointers are sorted by their arena ID so commuted expressions map to the sameCseNode. * Pipeline Stage: If the node is staged in a scheduled function (IsStaged), its stage index (GetStageIndex) is included so nodes are only merged within the same pipeline stage. * Operation Metadata: Captures attributes not reflected in the opcode, operands, or result type: *array_index,array_update:assumed_in_bounds. *bit_slice:startoffset. *one_hot:LsbOrMsbpriority. *tuple_index: elementindex. *counted_for:trip_count,stride, andbodyfunction. *invoke,map: target function pointer. *literal: serializedValueProtowhencommon_literalsistrue, or a unique ID whencommon_literalsisfalse. * Non-CSE-able operations (param,state_read,next_value,receive,send,assert,cover,trace, register and port ops, etc., including all side-effecting ops exceptgate): assigned a unique ID so they never compare equal to any other node. -
Grouping and Representative Replacement (
RunCse): * Live nodes that intern to the sameCseNode*are collected into an equivalence bucket. * For each bucket with multiple nodes, a single representative is chosen deterministically (CompareName): preferring nodes with an assigned name (HasAssignedName()), then shorter assigned names, and finally the lowest nodeid(). * All other nodes in the bucket have their uses replaced by the representative (ReplaceUsesWith), leaving the duplicate nodes dead for subsequentDeadCodeEliminationPasscleanup.
Example:
fn nontrivial(x: bits[8], y: bits[8], z: bits[8]) -> bits[8] {
and.1: bits[8] = and(x, y)
neg.2: bits[8] = neg(and.1)
or.3: bits[8] = or(neg.2, z)
and.4: bits[8] = and(y, x) // Commutatively equivalent to and.1
neg.5: bits[8] = neg(and.4) // Equivalent to neg.2
or.6: bits[8] = or(neg.5, z) // Equivalent to or.3
ret add.7: bits[8] = add(or.3, or.6)
}
After CsePass (and subsequent dead code elimination):
fn nontrivial(x: bits[8], y: bits[8], z: bits[8]) -> bits[8] {
and.1: bits[8] = and(x, y)
neg.2: bits[8] = neg(and.1)
or.3: bits[8] = or(neg.2, z)
ret add.7: bits[8] = add(or.3, or.3)
}
dataflow - Dataflow Optimization
An optimization which uses a lattice-based dataflow analysis to find equivalent nodes in the graph and replace them with a simpler form. The analysis traces through tuples, arrays, and select operations. Optimizations which can be performed by this pass:
tuple_index(tuple(x, y), index=1) => y
select(selector, {z, z}) => z
array_index(array_update(A, x, index={42}), index={42}) => x
Note
What follows was generated by the Gemini LLM. Not human verified.
The DataflowSimplificationPass uses a lattice-based dataflow analysis
(NodeSourceDataflowVisitor, built on DataflowVisitor<NodeSource>) to
track the origin of every leaf element (tuple fields, array elements, and
leaf bits or token values) through structural and control-flow operations
(tuple, tuple_index, array, array_index, array_slice,
array_update, array_concat, identity, sel, priority_sel, and
one_hot_sel). Nodes whose leaf elements originate from the exact same
sources are replaced with earlier equivalent nodes or reconstructed directly
from existing element nodes.
How it Works:
-
Leaf-Level Source Analysis (
NodeSourceDataflowVisitor): * The pass traverses the function in topological order and computes aLeafTypeTree<NodeSource>for every node. * Each leaf holds aNodeSource(node, tree_index)identifying the earliest node and aggregate index path from which that leaf value statically originates. * When joining branches in select or dynamic array operations (JoinElements), if all possible data sources for a leaf element are identical, that commonNodeSourceis preserved; otherwise, the join falls back to the current node (NodeSource(node, index)). -
Replacing Equivalent Nodes via
source_map: * During a topological walk, the pass inserts each node'sLeafTypeTreeView<NodeSource>intosource_map. * If a later node has the exact sameLeafTypeTreeView<NodeSource>as an earlier node insource_map(and is not an empty type with zero flat bits and no tokens, which is skipped viaIsEmptyTypeto avoid infinite replacement loops between empty-typed nodes), the later node is replaced directly with the earlier node (ReplaceUsesWith). * This single mechanism handles unboxing (tuple_index(tuple(x, y), 1)->y), redundant select elimination (sel(s, cases=[z, z])->z), forwarding through array updates, and replacing anarrayreconstructed from orderedarray_indexoperations of an existing arrayaback witha:``` // Original: e0: bits[32] = array_index(a, indices=[zero]) e1: bits[32] = array_index(a, indices=[one]) ret arr: bits[32][2] = array(e0, e1) // After optimization (arr has the same NodeSource tree as 'a'): ret a: bits[32][2] = param(name=a) ``` -
Materializing Arrays from Existing Element Nodes (
MaybeReplaceWithArrayOfExistingNodes): * If an array-typed node is not already insource_map(and is not aliteral,array,array_index, or empty type—avoidingarrayandarray_indexprevents infinite loops withArraySimplificationPass), the pass checks whether theNodeSourceview for every element0..size-1of the array is already present as a standalone node insource_map. * If all element sources exist insource_map, the operation (such as a chain ofarray_updates, anarray_concat, or anarray_slice) is replaced with a directarray(e_0, e_1, ..., e_{n-1})node.
dce - Dead Code Elimination
class DeadCodeEliminationPass removes dead nodes from a FunctionBase by starting from unused deletable nodes and iteratively removing them and any operands that become unused.
Note
What follows was generated by the Gemini LLM. Not human verified.
The DeadCodeEliminationPass (DCE) is a fundamental optimization pass in XLS
that removes "dead" or unused nodes from a FunctionBase (a function, proc,
or block). Dead code refers to any operation whose result has no consumers
and is not required for its observable outputs or side effects. Removing
dead code simplifies the IR graph, reduces synthesized hardware area, and
speeds up subsequent optimization passes.
How it Works:
Rather than marking live nodes from roots, the pass uses a bottom-up worklist algorithm starting from nodes that already have zero users:
-
Deletability Criterion (
is_deletable): A nodenis eligible for deletion if all of the following hold: * No Implicit Uses:!n->function_base()->HasImplicitUse(n)(for example, a function's return value node or a legacy proc's next-state node has an implicit use and cannot be deleted). * Not aninvoke:!n->Is<Invoke>(). Invoked functions are conservatively preserved by DCE because they may contain side-effecting operations;InliningPassis responsible for eliminatinginvokenodes. * Not Side-Effecting (Exceptgate):!OpIsSideEffecting(n->op()) || n->Is<Gate>(). Side-effecting nodes such asassert,cover,trace,send,receive,next_value,register_write,instantiation_input,output_port, andparamare preserved even when they have no explicit users.gateis specially exempted so unused gated values can be eliminated. (Gate is considered side-effecting so it can force itself into the verilog output.) -
Worklist Initialization: The pass scans
f->nodes()and seeds a FIFO worklist (std::deque<Node*>) with every nodenwheren->users().empty()andis_deletable(n)is true. -
Iterative Removal: While the worklist is non-empty, the pass pops a node from the front of the queue: * It inspects each unique operand of the node (using
ForEachUniqueso an operand referenced multiple times by the same node is only checked once). If an operand is only used by this node (HasSingleUse(operand)) and satisfiesis_deletable(operand), that operand will become userless once the current node is removed, so it is pushed onto the worklist. * The current node is removed from theFunctionBaseviaf->RemoveNode(node). -
Optimization Context Garbage Collection: If any nodes were removed during the pass,
context.CollectGarbage()is called to clean up cached query engine and analysis state associated with the deleted nodes.
Example:
Consider a function with dead intermediate operations:
// Original IR snippet
fn some_dead_code(x: bits[42], y: bits[42]) -> bits[42] {
neg.1: bits[42] = neg(x)
add.2: bits[42] = add(x, y) // Only used by dead node neg.3
neg.3: bits[42] = neg(add.2) // Dead: zero users
ret sub.4: bits[42] = sub(neg.1, y)
}
DeadCodeEliminationPass executes as follows:
1. Initial scan finds neg.3 has zero users and is deletable, so the
worklist is initialized to [neg.3]. (sub.4 has zero explicit users
but is the function return value, so HasImplicitUse(sub.4) is true.)
2. neg.3 is popped. Its unique operand add.2 has a single use (neg.3)
and is deletable, so add.2 is added to the worklist. neg.3 is
removed.
3. add.2 is popped. Its operands x and y still have other uses (and
are param nodes), so neither is added to the worklist. add.2 is
removed.
The resulting IR is:
// Optimized IR (after DCE)
fn some_dead_code(x: bits[42], y: bits[42]) -> bits[42] {
neg.1: bits[42] = neg(x)
ret sub.4: bits[42] = sub(neg.1, y)
}
dfe - Dead Function Elimination
Dead Function Elimination.
Note
What follows was generated by the Gemini LLM. Not human verified.
DeadFunctionEliminationPass (DFE) is a package-level optimization pass that
removes unreachable functions, procs, and blocks (collectively
FunctionBases) as well as unused global channels from a Package.
The pass requires that a top entity be specified on the package
(p->GetTop()); if no top is set, the pass returns false without making
any changes.
How it Works:
-
Identifying Live Roots (
FunctionBaseLiveness): * Iftopis aFunctionorBlock,topis the sole live root (and no global channels are marked live). * Iftopis a new-styleProc(top->is_new_style_proc()with proc-scoped channels), the pass runsProcElaboration::Elaborate(top)and treats all elaborated procs in the hierarchy (elab.procs()) as live roots. * Iftopis an old-styleProc(using package-level global channels), the pass seeds a worklist withtopand any proc in the package that accesses an external channel (channel->supported_ops() != ChannelOps::kSendReceive, i.e.,send_onlyorreceive_only). It then performs a breadth-first traversal across the proc-to-channel graph so that any proc communicating with a live proc over an internalSendReceivechannel is also marked as a live root, and every channel used by a live proc is recorded inlive_global_channels. -
Reachability Traversal (
MarkReachedFunctions): Starting from each live root, the pass performs a depth-first search (DFS) to mark all transitively referencedFunctionBases: *counted_fornodes mark theirbody()function. *invokeandmapnodes mark theirto_apply()function. * If a visitedFunctionBaseis aBlock, any sub-blocks referenced viaBlockInstantiationinGetInstantiations()are recursively marked. -
Removal of Dead Entities: * Every
FunctionBaseinp->GetFunctionBases()not in thereachedset is evicted from theOptimizationContext(context.Abandon(f)) and removed from the package (p->RemoveFunctionBase(f)). * Every global channel inp->channels()not inlive_global_channelsis removed viap->RemoveChannel(channel).
Example:
Consider a package with three functions where f_top is the top entity and
invokes f_live, while f_dead is never referenced:
package my_package
fn f_dead() -> bits[32] {
ret literal.0: bits[32] = literal(value=42)
}
fn f_live(x: bits[32]) -> bits[32] {
literal.1: bits[32] = literal(value=1)
ret add.2: bits[32] = add(x, literal.1)
}
top fn f_top(y: bits[32]) -> bits[32] {
ret invoke.3: bits[32] = invoke(y, to_apply=f_live)
}
After DeadFunctionEliminationPass runs, f_dead is removed because it is
not reachable from f_top:
package my_package
fn f_live(x: bits[32]) -> bits[32] {
literal.1: bits[32] = literal(value=1)
ret add.2: bits[32] = add(x, literal.1)
}
top fn f_top(y: bits[32]) -> bits[32] {
ret invoke.3: bits[32] = invoke(y, to_apply=f_live)
}
fixedpoint_proc_state_flattening - Proc State Flattening
Prepare proc state for further analysis by removing arrays and tuples.
Options Set
Run to a fixedpoint.
Invoked Passes
fixedpoint_simp - Fixed-point Simplification
Standard simplification pipeline.
This is run to a fixedpoint and avoids many time-consuming analyses.
Options Set
Run to a fixedpoint.
Invoked Passes
fixedpoint_simp(2) - Max-2 Fixed-point Simplification
Standard simplification pipeline.
Opt level is capped at 2
Options Set
Run to a fixedpoint.
Cap opt level: 2
Invoked Passes
fixedpoint_simp(3) - Max-3 Fixed-point Simplification
Standard simplification pipeline.
Opt level is capped at 3
Options Set
Run to a fixedpoint.
Cap opt level: 3
Invoked Passes
fixedpoint_simp(>=1,<=2) - Min-1 Max-2 Fixedpoint Simplification
Standard simplification pipeline.
Opt level is capped at 2 and skipped if less than 1
Options Set
Run to a fixedpoint.
Min opt level: 1
Cap opt level: 2
Invoked Passes
full-inlining - full function inlining passes
Fully inline all functions in a single step.
Invoked Passes
ident_remove - Identity Removal
Identity Removal - eliminate all identity() expressions.
Note
What follows was generated by the Gemini LLM. Not human verified.
The IdentityRemovalPass is a pass that simplifies the Intermediate
Representation (IR) by bypassing all identity operations in a
FunctionBase. An identity operation (Op::kIdentity) simply forwards its
single operand unchanged.
How it Works:
- Single Forward Pass: The pass iterates once through
f->nodes(). - Use Replacement: For each node with
node->op() == Op::kIdentity, it callsnode->ReplaceUsesWith(node->operand(0)), rewiring all explicit consumers (as well as implicit uses such as a function's return value) directly to the operand of theidentitynode. - Cleanup by DCE:
IdentityRemovalPassdoes not delete the now-unusedidentitynodes itself; a subsequentDeadCodeEliminationPassremoves them from theFunctionBase.
Example:
Consider a function with a chain of identity operations:
// Original IR snippet
fn simple_ident(x: bits[8]) -> bits[8] {
one: bits[8] = literal(value=1)
v1: bits[8] = identity(x)
add: bits[8] = add(v1, one)
v2: bits[8] = identity(add)
v3: bits[8] = identity(v2)
ret res: bits[8] = sub(v3, one)
}
After IdentityRemovalPass (and DeadCodeEliminationPass to remove the
orphaned identity nodes), the IR becomes:
// Optimized IR (after IdentityRemovalPass and DCE)
fn simple_ident(x: bits[8]) -> bits[8] {
one: bits[8] = literal(value=1)
add: bits[8] = add(x, one)
ret res: bits[8] = sub(add, one)
}
inlining - Inlines invocations
Inlines a package toward the top function/proc.
If full then all functions are inlined into the top.
If leaf then only leaf functions are inlined into their caller. This allows
other passes to optimize on smaller graphs.
Note
What follows was generated by the Gemini LLM. Not human verified.
The InliningPass replaces invoke operations (function calls) with the
body of the invoked function, exposing interprocedural optimization
opportunities to intraprocedural passes (such as CSE, narrowing, and DCE) and
flattening the call hierarchy for hardware synthesis. Foreign functions
(those with ForeignFunctionData for FFI) cannot be inlined and are
skipped.
Inlining Depth Modes (InlineDepth):
-
InlineDepth::kFull(registered as"inlining"): Processes allFunctionBases in the package in post-order of the call graph (FunctionsInPostOrder(p), leaves first) and inlines every non-foreigninvokein each caller whereShouldInlineInto(caller)is true. Processing leaves first guarantees that when a callee is inlined into its caller, anyinvokes inside that callee have already been inlined, avoiding duplicate work. -
InlineDepth::kLeafOnly(registered as"leaf-inlining"): UsesGetFunctionsToInlineByLeafto inline into a callerfonly if everyinvokeinftargets either: * A leaf function (one that contains zero inlineableinvokes), or * A non-leaf function that has only a single inlineableinvokecall (to_inline_cnt == 1) and is itself selected for inlining in the same pass. Note thatGetFunctionsToInlineByLeafrequires allmapand loop constructs (counted_for/dynamic_counted_for) to have been lowered toinvokes prior to running.
How InlineInvoke Works:
For each eligible Invoke node:
-
Parameter Mapping & Topological Cloning: Maps each
Paramof the callee (invoke->to_apply()) to the corresponding argument operand of theinvoke. It then iterates through the callee's nodes in topological order (context.TopoSort(invoked)) and clones each non-parameter node into the callerFunctionBaseviaCloneInNewFunction. -
Source Location Merging: If a cloned node has an empty
SourceInfo, it inheritsinvoke->loc(); otherwise, theSourceLocationentries frominvoke->loc()are appended to the cloned node's location list. -
Node Name Propagation: * Return Value: If the
invokenode has an assigned name, the cloned return value node's name is cleared beforeReplaceUsesWithso that it inherits theinvokenode's assigned name. * Parameter-Derived Names (GetInlinedNodeName): For any other node in the callee with an assigned name, if its name starts with a callee parameter's name and the correspondinginvokeargument also has an assigned name, the longest matching parameter prefix is replaced with the argument's name (e.g., inliningx_neg: neg(x)with argumentfoonames the cloned nodefoo_neg). -
coverandassertLabel Qualification (GetPrefixedLabel): To prevent duplicate Verilog cover/assert property labels when a function is inlined multiple times, anycovernode or labeledassertnode has its original user label saved inoriginal_label(if not already set) and its activelabelprefixed with<caller_name>_<inline_count>_<callee_name>_<label>. (A laterLabelRecoveryPasscan restoreoriginal_labelwhen no collisions occur.) -
Replacement: All uses of
invokeare replaced with the cloned return value node, and theinvokenode is removed from the caller.
Example (kFull Inlining):
// Original IR
package some_package
fn callee(x: bits[32], y: bits[32]) -> bits[32] {
ret add.1: bits[32] = add(x, y)
}
top fn caller() -> bits[32] {
literal.2: bits[32] = literal(value=2)
ret invoke.3: bits[32] = invoke(literal.2, literal.2, to_apply=callee)
}
After InliningPass (followed by DeadFunctionEliminationPass to remove the
unreferenced callee), invoke.3 is replaced by the cloned add:
// Optimized IR (after Inlining and DFE)
package some_package
top fn caller() -> bits[32] {
literal.2: bits[32] = literal(value=2)
ret add.4: bits[32] = add(literal.2, literal.2)
}
invalidate_cached_proc_state_info - Invalidate proc state cached range information.
Helper fake class that invalidates cached proc-state information in the query engines.
This invalidates the givens in PartialInfoQueryEngine and LazyTernaryQueryEngine.
Note
What follows was generated by the Gemini LLM. Not human verified.
InvalidateCachedProcStateInfoPass is a bookkeeping pseudo-pass for Procs
that clears cached proc state range and ternary invariants ("givens") stored
in the OptimizationContext's shared query engines, without modifying the
IR itself.
Background and Motivation:
During proc optimization (such as ProcStateRangeQueryEngine and
ProcStateNarrowingPass), XLS analyzes how proc state elements evolve across
ticks and records proven state-element invariants in
CachedStateElementQueryEngine wrappers around PartialInfoQueryEngine and
LazyTernaryQueryEngine. Caching these state invariants allows subsequent
passes to retain narrowed state bounds even after intermediate rewrites make
the state evolution harder to re-derive from scratch. However, once a group
of passes finishes or before transformations that might invalidate those
cached assumptions, the cached state "givens" must be explicitly cleared.
How it Works:
When run on a Proc, RunOnProcInternal retrieves both cached query engines
from OptimizationContext and clears their recorded state-element givens:
1. CachedStateElementQueryEngine::FromContext<PartialInfoQueryEngine>
->ClearGivens()
2. CachedStateElementQueryEngine::FromContext<LazyTernaryQueryEngine>
->ClearGivens()
The pass always returns false because it only mutates analysis cache state
in OptimizationContext and never alters the IR graph.
Example:
Suppose a proc has a 32-bit state element st that ProcStateNarrowingPass
proves is always in [0, 7], caching that range in
CachedStateElementQueryEngine:
// IR remains unchanged before and after InvalidateCachedProcStateInfoPass;
// only the cached state-element givens in OptimizationContext are cleared.
proc counter(st: bits[32], init={0}) {
lit1: bits[32] = literal(value=1)
sum: bits[32] = add(st, lit1)
mask: bits[32] = literal(value=7)
next_st: bits[32] = and(sum, mask)
next (next_st)
}
label-recovery - LabelRecovery
At the end of the pass pipeline (when inlining and optimizations have been performed) attempts to recover original names for coverpoints and assertions to whatever degree possible so they're more human-readable -- we mangle them for inlining to ensure they're unique, but often those names are way overqualified.
Note
What follows was generated by the Gemini LLM. Not human verified.
The LabelRecoveryPass restores human-readable user-defined labels on
cover and assert nodes after function inlining and subsequent
optimizations have completed. During InliningPass, cover and assert
labels are prefixed with caller, inline-count, and callee identifiers (e.g.,
<caller>_<inline_count>_<callee>_<label>) while preserving the pre-inlined
name in the node's original_label attribute. This avoids duplicate property
names in generated Verilog when a function is inlined multiple times, but can
leave overly verbose labels when only a single instance survives.
How it Works:
-
Grouping by
original_label: The pass scans all nodes in theFunctionBaseand collects everycover(Op::kCover) andassert(Op::kAssert) node that has anoriginal_labelattribute into a map keyed byoriginal_label(original_label_to_nodes). Note thatcoverandassertnodes share the same collision map. -
Collision-Free Restoration: For each
original_labelin the map: * Unique Instance (nodes.size() == 1): If only a singlecoverorassertnode in theFunctionBasehas thatoriginal_label, restoring it cannot cause a label collision. The pass updates the node's active label viaset_label(original_label). * Multiple Instances (nodes.size() > 1): If multiple inlined nodes share the sameoriginal_label, their mangled labels are kept unchanged so each instance retains a unique identifier.
Example:
Consider a callee function with a cover point that is invoked once by
caller:
// IR after InliningPass and DCE (before LabelRecoveryPass)
package p
top fn caller(p: bits[1]) -> () {
ret cover.1: () = cover(p, label="caller_0_callee_my_cover_label",
original_label="my_cover_label")
}
Because cover.1 is the only node in caller with
original_label="my_cover_label", LabelRecoveryPass restores its label:
// IR after LabelRecoveryPass
package p
top fn caller(p: bits[1]) -> () {
ret cover.1: () = cover(p, label="my_cover_label",
original_label="my_cover_label")
}
leaf-inlining - Inlines invocations
Inlines a package toward the top function/proc.
If full then all functions are inlined into the top.
If leaf then only leaf functions are inlined into their caller. This allows
other passes to optimize on smaller graphs.
Note
What follows was generated by the Gemini LLM. Not human verified.
The InliningPass replaces invoke operations (function calls) with the
body of the invoked function, exposing interprocedural optimization
opportunities to intraprocedural passes (such as CSE, narrowing, and DCE) and
flattening the call hierarchy for hardware synthesis. Foreign functions
(those with ForeignFunctionData for FFI) cannot be inlined and are
skipped.
Inlining Depth Modes (InlineDepth):
-
InlineDepth::kFull(registered as"inlining"): Processes allFunctionBases in the package in post-order of the call graph (FunctionsInPostOrder(p), leaves first) and inlines every non-foreigninvokein each caller whereShouldInlineInto(caller)is true. Processing leaves first guarantees that when a callee is inlined into its caller, anyinvokes inside that callee have already been inlined, avoiding duplicate work. -
InlineDepth::kLeafOnly(registered as"leaf-inlining"): UsesGetFunctionsToInlineByLeafto inline into a callerfonly if everyinvokeinftargets either: * A leaf function (one that contains zero inlineableinvokes), or * A non-leaf function that has only a single inlineableinvokecall (to_inline_cnt == 1) and is itself selected for inlining in the same pass. Note thatGetFunctionsToInlineByLeafrequires allmapand loop constructs (counted_for/dynamic_counted_for) to have been lowered toinvokes prior to running.
How InlineInvoke Works:
For each eligible Invoke node:
-
Parameter Mapping & Topological Cloning: Maps each
Paramof the callee (invoke->to_apply()) to the corresponding argument operand of theinvoke. It then iterates through the callee's nodes in topological order (context.TopoSort(invoked)) and clones each non-parameter node into the callerFunctionBaseviaCloneInNewFunction. -
Source Location Merging: If a cloned node has an empty
SourceInfo, it inheritsinvoke->loc(); otherwise, theSourceLocationentries frominvoke->loc()are appended to the cloned node's location list. -
Node Name Propagation: * Return Value: If the
invokenode has an assigned name, the cloned return value node's name is cleared beforeReplaceUsesWithso that it inherits theinvokenode's assigned name. * Parameter-Derived Names (GetInlinedNodeName): For any other node in the callee with an assigned name, if its name starts with a callee parameter's name and the correspondinginvokeargument also has an assigned name, the longest matching parameter prefix is replaced with the argument's name (e.g., inliningx_neg: neg(x)with argumentfoonames the cloned nodefoo_neg). -
coverandassertLabel Qualification (GetPrefixedLabel): To prevent duplicate Verilog cover/assert property labels when a function is inlined multiple times, anycovernode or labeledassertnode has its original user label saved inoriginal_label(if not already set) and its activelabelprefixed with<caller_name>_<inline_count>_<callee_name>_<label>. (A laterLabelRecoveryPasscan restoreoriginal_labelwhen no collisions occur.) -
Replacement: All uses of
invokeare replaced with the cloned return value node, and theinvokenode is removed from the caller.
Example (kFull Inlining):
// Original IR
package some_package
fn callee(x: bits[32], y: bits[32]) -> bits[32] {
ret add.1: bits[32] = add(x, y)
}
top fn caller() -> bits[32] {
literal.2: bits[32] = literal(value=2)
ret invoke.3: bits[32] = invoke(literal.2, literal.2, to_apply=callee)
}
After InliningPass (followed by DeadFunctionEliminationPass to remove the
unreferenced callee), invoke.3 is replaced by the cloned add:
// Optimized IR (after Inlining and DFE)
package some_package
top fn caller() -> bits[32] {
literal.2: bits[32] = literal(value=2)
ret add.4: bits[32] = add(literal.2, literal.2)
}
loop_unroll - Unroll counted loops
Note
What follows was generated by the Gemini LLM. Not human verified.
The UnrollPass unrolls counted_for loops within a function or proc by
expanding each iteration into an explicit invoke of the loop's body
function.
How it Works:
- Loop Discovery: The pass searches the
FunctionBasefor any effectively usedcounted_fornode (a node that has users or is the function return value). - Iterative Expansion: For a
counted_forwithtrip_countiterations and stepstride, the pass initializes the loop-carried accumulatorloop_carrytoinitial_value. For each trip0 <= trip < trip_count(with induction variableiv = trip * stride), it: * Creates aliteralnode forivmatching the bit-width of the body function's first parameter. * Emits aninvokenode callingbodywith arguments[iv, loop_carry, invariant_args...]and updatesloop_carryto the result of theinvoke. - Replacement: All uses of the
counted_fornode are replaced with the finalloop_carrynode (orinitial_valueiftrip_count == 0), and thecounted_fornode is removed. This repeats until no usedcounted_fornodes remain.
Example:
// Original IR
fn body(i: bits[4], accum: bits[32], zero: bits[32]) -> bits[32] {
zero_ext.3: bits[32] = zero_ext(i, new_bit_count=32)
add.4: bits[32] = add(zero_ext.3, accum)
ret add.5: bits[32] = add(add.4, zero)
}
fn unrollable() -> bits[32] {
literal.1: bits[32] = literal(value=0)
ret counted_for.2: bits[32] = counted_for(literal.1, trip_count=2,
stride=2, body=body, invariant_args=[literal.1])
}
// Optimized IR
fn unrollable() -> bits[32] {
literal.1: bits[32] = literal(value=0)
literal.6: bits[4] = literal(value=0)
invoke.7: bits[32] = invoke(literal.6, literal.1, literal.1, to_apply=body)
literal.8: bits[4] = literal(value=2)
ret invoke.9: bits[32] = invoke(literal.8, invoke.7, literal.1,
to_apply=body)
}
lut_conversion - LUT Conversion
Pass which opportunistically converts nodes to lookup tables (selects) where we can prove it's beneficial.
Note
What follows was generated by the Gemini LLM. Not human verified.
The LutConversionPass absorbs combinational logic feeding the selector of
one or more select operations into the select operations themselves,
converting them into direct lookup tables (LUTs) indexed by a smaller or
simpler cut of ancestor bits.
The pass is gated on options.narrowing_enabled() and uses a
UnionQueryEngine combining StatelessQueryEngine and a shared
LazyTernaryQueryEngine.
How it Works:
-
Candidate Discovery (
ComputeLutConversionCandidates): The pass traverses nodes in reverse topological order (context.ReverseTopoSort(func)), skipping dead nodes. For each node that serves as theselector()of at least oneSelectuser: * It computes the maximum number of cases (max_case_count, countingdefault_valueas an extra case if present) across allSelectusers controlled by this selector, and determines the maximum bit width required to index them:max_bits_needed = Bits::MinBitCountUnsigned(max_case_count - 1). Selectors withmax_bits_needed <= 1are skipped. * UsingDataflowGraphAnalysis::GetMinCutFor, it finds a minimum cut (min_cut) of ancestor nodes that completely determine the selector's value with at mostmax_bits_neededtotal unknown bits (unknown_bits) according to the ternary query engine. * It checks whether the selector is already trivially derived frommin_cut(IsTriviallyDerived, meaning constructed only frommin_cutnodes and literals viatuple_index,bit_slice, literal-indexedarray_index, andconcat). * Each controlledSelectuser (requiringbits_neededselector bits) is kept as a candidate user if either: *unknown_bits < bits_needed(the LUT conversion strictly narrows theSelect), or *unknown_bits == bits_needed && !selector_is_trivial(theSelectstays the same width, but non-trivial combinational selector logic is absorbed into the LUT, reducing delay). -
Truth-Table Evaluation (
ComputeLutSelectCases): * AnIrInterpreteris pre-populated with all statically known node values (query_engine.KnownValue(n)) in the cone feeding the selector. * For each node inmin_cut, all concreteValues compatible with itsTernaryVectorare enumerated (ternary_ops::AllValues). *MixedRadixIterateiterates over all combinations ofmin_cutvalues (with earliermin_cutnodes varying fastest, corresponding to lower-order bits of the new selector) and evaluates the original selector node in theIrInterpreterto record the sequence of selected case indices (new_case_sequence). -
Merging into Controlled Selects (
MergeLutIntoSelects): * Single-Case Fold: If every combination innew_case_sequenceselects the exact same case index, each controlledSelectis replaced directly by that single case node. * NewSelectConstruction: Otherwise, for each node inmin_cut, the pass extracts its unknown bits usingGatherBits, reverses the pieces so earliermin_cutnodes occupy the least-significant bits, and concatenates them intonew_selector. Each controlledSelectis then replaced with a newSelect(new_selector, new_cases, /*default_value=*/std::nullopt)whose cases are permuted/selected from the originalSelectaccording tonew_case_sequence.
Example:
Consider a select whose selector doubled_x is a non-trivial arithmetic
function (add(x, x)) of a 2-bit input x:
// Original IR snippet
fn simple_select(x: bits[2], a: bits[8], b: bits[8], c: bits[8]) -> bits[8] {
doubled_x: bits[2] = add(x, x)
ret result: bits[8] = sel(doubled_x, cases=[a, b, c], default=a)
}
DataflowGraphAnalysis finds min_cut = {x} with unknown_bits = 2, which
matches bits_needed = 2 for the 4-way sel while eliminating the add
from the selector path. Evaluating doubled_x for x = 0, 1, 2, 3 yields
selector values 0, 2, 0, 2, producing:
// Optimized IR (after LutConversionPass and DCE)
fn simple_select(x: bits[2], a: bits[8], b: bits[8], c: bits[8]) -> bits[8] {
ret result: bits[8] = sel(x, cases=[a, c, a, c])
}
map_inlining - Inline map operations
A pass to convert map nodes to in-line Invoke nodes. We don't directly lower maps to Verilog.
Note
What follows was generated by the Gemini LLM. Not human verified.
The MapInliningPass lowers map operations (Op::kMap) in a
FunctionBase into explicit per-element array_index and invoke
operations assembled into an array. Because hardware description languages
like Verilog do not directly represent higher-order map operations, this
pass unrolls them so that subsequent InliningPass and optimization passes
can inline and optimize the applied function across all array elements.
How it Works:
- Collecting
mapNodes: The pass scansfunction->nodes()and collects allMapnodes. - Unrolling (
ReplaceMap): For eachmapnode with input arraymap->operand(0)of sizeNand target functionmap->to_apply(): * For each element indexifrom0toN - 1: * Creates aLiteralnodeindexwith valueUBits(i, Bits::MinBitCountUnsigned(N)). * Creates anArrayIndexnode extracting elementifrommap->operand(0). * Creates anInvokenode applyingmap->to_apply()to thatArrayIndexelement. * Replaces all uses ofmapwith a newArraynode containing theNInvokeresults, and removes the originalmapnode from theFunctionBase.
A static helper MapInliningPass::InlineOneMap(Map* map) is also provided
for testing and ir_minimizer use.
Example:
Consider a map operation that applies map_fn to a 4-element array a:
fn map_fn(x: bits[32]) -> bits[16] {
ret bit_slice.1: bits[16] = bit_slice(x, start=0, width=16)
}
fn main(a: bits[32][4]) -> bits[16][4] {
ret result: bits[16][4] = map(a, to_apply=map_fn)
}
After MapInliningPass, the map node is replaced by an array of four
invoke operations:
fn map_fn(x: bits[32]) -> bits[16] {
ret bit_slice.1: bits[16] = bit_slice(x, start=0, width=16)
}
fn main(a: bits[32][4]) -> bits[16][4] {
literal.2: bits[3] = literal(value=0)
array_index.3: bits[32] = array_index(a, indices=[literal.2])
invoke.4: bits[16] = invoke(array_index.3, to_apply=map_fn)
literal.5: bits[3] = literal(value=1)
array_index.6: bits[32] = array_index(a, indices=[literal.5])
invoke.7: bits[16] = invoke(array_index.6, to_apply=map_fn)
literal.8: bits[3] = literal(value=2)
array_index.9: bits[32] = array_index(a, indices=[literal.8])
invoke.10: bits[16] = invoke(array_index.9, to_apply=map_fn)
literal.11: bits[3] = literal(value=3)
array_index.12: bits[32] = array_index(a, indices=[literal.11])
invoke.13: bits[16] = invoke(array_index.12, to_apply=map_fn)
ret array.14: bits[16][4] =
array(invoke.4, invoke.7, invoke.10, invoke.13)
}
name_promotion - Name Promotion
Promotes nodes whose assigned names were uniquified by the NameUniquer
back to their originally requested names if those names have since become
available (for example, because the colliding node was removed by dead code
elimination).
Note
What follows was generated by the Gemini LLM. Not human verified.
When multiple nodes in a FunctionBase request the same name foo, the
NameUniquer assigns foo to the first node and uniquified names such as
foo__1, foo__2, etc. to subsequent nodes, while recording that their
originally requested name was foo. During optimization, the original node
named foo (or an intermediate node in a collision chain) is often replaced
or deleted by dead code elimination (DeadCodeEliminationPass), releasing
foo in the FunctionBase's NameUniquer.
NamePromotionPass scans the nodes of a FunctionBase and promotes any
eligible node whose originally requested name is now free back to that
original name. The pass iterates to a fixed point so that cascading
promotions (e.g., promoting foo__1 to foo frees foo__1 for a node that
originally requested foo__1 and received foo__2) are resolved in a single
pass invocation. Parameter and port nodes are never renamed.
narrow - Narrowing
A pass which reduces the width of operations eliminating redundant or unused bits.
Note
What follows was generated by the Gemini LLM. Not human verified.
The NarrowingPass is a powerful optimization pass in XLS designed to reduce
the bit width of bits-typed operations and values within a function or
proc. This is a critical optimization for hardware generation, as a
reduction in bit widths directly translates to smaller, more efficient, and
often faster hardware (fewer wires, smaller functional units, and smaller
registers). The pass employs various advanced analysis techniques to
determine the minimum required bit width for each value without altering its
functional correctness.
The pass is configured with an AnalysisType enum, which dictates the
sophistication of the analysis used:
kTernary: Utilizes a simpler ternary logic-based query engine. This analysis determines for each bit if it is always zero, always one, or unknown.
kRange: Employs a more powerful range analysis to determine the possible numerical bounds (minimum and maximum values) that a bit-vector can take. This provides more precise information for narrowing.
kRangeWithContext: Extends range analysis to be context-sensitive. This means it considers predicates (conditions) ofselectoperations and other conditional control flow to derive more precise ranges for values within specific execution paths.
kRangeWithOptionalContext: Allows the choice betweenkRangeandkRangeWithContextbased on theoptions.use_context_narrowing_analysisflag, providing flexibility in trade-off between analysis time and precision.
The pass operates by iteratively traversing the IR and applying transformations to nodes where bit widths can be safely reduced. Key optimizations include:
-
Replacing Precise Values with Literals: If an analysis (ternary or range) can definitively determine that a node's value is precisely known (i.e., it always evaluates to a constant), that node is replaced with a
literalnode. This simplifies the graph and can enable further optimizations. -
Narrowing Comparison Operations: * Stripping Matched Leading/Trailing Bits: For comparison operations (
eq,ne,ult,ugt, etc.), if leading or trailing bits of both operands are known to be identical, these matching bits can be logically removed, and the comparison is performed on the narrower remaining bits.``` // Original: UGt(0b0110_0XXX_0011, 0b0110_0YYY_0011) // bit strings // Leading `0110` and trailing `0011` match for both operands. // Optimized: UGt(0bXXX, 0bYYY) ```* Signed Comparison Simplification: Signed comparisons with zero-extended operands (or operands whose MSBs are known to be equal) can often be converted to unsigned comparisons on narrower bit widths, as the sign information becomes redundant.
-
Narrowing
NegateOperations: * Trailing Zeros: If an operand to anegateoperation has known trailing zeros, thenegatecan be performed on the more significant bits, and the trailing zeros re-concatenated, effectively reducing the width of thenegateoperation.* Sign Extension Hoisting: For
negate(sign_ext(x)), if the range analysis shows thatxcannot be the minimum representable signed value, this can be simplified tosign_ext(negate(x)), reducing the width of thenegateoperation. More generally, it finds the minimal bit width for the innernegateand then re-extends. -
Narrowing Shift Operations (
shll,shra,shrl): * Zero Shift Amount: If a shift amount is provably zero, the shift operation is replaced directly by its value operand (a no-op).* Known Leading/Trailing Zeros/Sign Bits: For shift operations, if parts of the
shift_valueare known to be zero or sign bits, theshift_valuecan be sliced to remove these redundant bits before the shift, and the result re-extended (zero-extend or sign-extend) if necessary. Theshift_amountitself can also be narrowed if it has leading zeros.* Out-of-Bounds Shifts: Shift operations that are guaranteed to shift all bits off the end of the operand (resulting in a zero value) are replaced by a literal zero.
-
Narrowing
AddandSubOperations: * Common Leading Zeros/Sign Bits: Foraddandsuboperations, if both operands share a common number of leading zeros (for unsigned results) or sign bits (for signed results), the operation can be performed on a narrower bit width. The result is then zero-extended or sign-extended back to the original width. This includes careful handling of potential overflows for signed additions. -
Narrowing
MultiplyOperations (umul,smul,umulp,smulp): * Result Wider Than Sum of Operands: If the declared result width of a multiply operation is greater than the sum of the bit widths of its operands, the multiplication can be performed at the sum-of-operand widths, and the result then extended.* Operands Wider Than Result: If the operands are wider than the required result width, they can be narrowed (sliced) before the multiplication, reducing the complexity of the multiplier.
* Extended Operands (Zero-extend/Sign-extend): When operands are the results of
zero_extorsign_extoperations, they can often be narrowed back to their original non-extended width, with the multiplication type adjusted (e.g.,umulorsmul) if necessary to maintain correctness.* Trailing Zeros: Multiplies where one or both operands have known trailing zeros can be optimized by performing the multiplication on the non-zero bits and concatenating the result with the appropriate number of trailing zeros.
* Partial Product Optimization: For
umulp/smulp(partial product multiplies), if the two partial products are immediately summed (e.g.,add(tuple_index(mulp_op, 0), tuple_index(mulp_op, 1))), the overall operation can be narrowed, and the final sum then extended. -
Narrowing
ArrayIndexOperations: * Literal Index Values: If an index to anarray_indexis a known literal, its bit width can be narrowed to the minimum required to represent the actual array size, saving bits in the index computation.* Known Zero Index: If an index is provably zero, it's replaced with a literal zero of appropriate width.
* Known Out-of-Bounds Index: Similar to
BitSliceSimplificationPass, if an index is provably out of bounds, it's clamped to the maximum valid index.* Convert
ArrayIndextoSelect: Forarray_indexoperations with a small, discrete set of possible index values (based on range analysis), the operation can be converted to aselectchain, making explicit checks for each possible index value. This can be beneficial for small arrays by removing complex indexing logic. -
Narrowing
DecodeOperations: * Leading Zeros in Index: If the index of adecodeoperation has leading zeros, the index can be sliced to remove them, and thedecodeperformed on the narrower index, with the result zero-extended if needed.* Zero Index: A
decodewith a provably zero index is replaced by a literal one, asdecode(0)always results in a one-hot encoding with the least significant bit set.
The NarrowingPass is typically run repeatedly within an optimization
pipeline until a fixed point is reached. This iterative process is crucial
for achieving maximal bit width reduction across the entire IR, as narrowing
one node can often enable further narrowing of its consumers or producers.
narrow(Context) - Narrowing
A pass which reduces the width of operations eliminating redundant or unused bits.
Note
What follows was generated by the Gemini LLM. Not human verified.
The NarrowingPass is a powerful optimization pass in XLS designed to reduce
the bit width of bits-typed operations and values within a function or
proc. This is a critical optimization for hardware generation, as a
reduction in bit widths directly translates to smaller, more efficient, and
often faster hardware (fewer wires, smaller functional units, and smaller
registers). The pass employs various advanced analysis techniques to
determine the minimum required bit width for each value without altering its
functional correctness.
The pass is configured with an AnalysisType enum, which dictates the
sophistication of the analysis used:
kTernary: Utilizes a simpler ternary logic-based query engine. This analysis determines for each bit if it is always zero, always one, or unknown.
kRange: Employs a more powerful range analysis to determine the possible numerical bounds (minimum and maximum values) that a bit-vector can take. This provides more precise information for narrowing.
kRangeWithContext: Extends range analysis to be context-sensitive. This means it considers predicates (conditions) ofselectoperations and other conditional control flow to derive more precise ranges for values within specific execution paths.
kRangeWithOptionalContext: Allows the choice betweenkRangeandkRangeWithContextbased on theoptions.use_context_narrowing_analysisflag, providing flexibility in trade-off between analysis time and precision.
The pass operates by iteratively traversing the IR and applying transformations to nodes where bit widths can be safely reduced. Key optimizations include:
-
Replacing Precise Values with Literals: If an analysis (ternary or range) can definitively determine that a node's value is precisely known (i.e., it always evaluates to a constant), that node is replaced with a
literalnode. This simplifies the graph and can enable further optimizations. -
Narrowing Comparison Operations: * Stripping Matched Leading/Trailing Bits: For comparison operations (
eq,ne,ult,ugt, etc.), if leading or trailing bits of both operands are known to be identical, these matching bits can be logically removed, and the comparison is performed on the narrower remaining bits.``` // Original: UGt(0b0110_0XXX_0011, 0b0110_0YYY_0011) // bit strings // Leading `0110` and trailing `0011` match for both operands. // Optimized: UGt(0bXXX, 0bYYY) ```* Signed Comparison Simplification: Signed comparisons with zero-extended operands (or operands whose MSBs are known to be equal) can often be converted to unsigned comparisons on narrower bit widths, as the sign information becomes redundant.
-
Narrowing
NegateOperations: * Trailing Zeros: If an operand to anegateoperation has known trailing zeros, thenegatecan be performed on the more significant bits, and the trailing zeros re-concatenated, effectively reducing the width of thenegateoperation.* Sign Extension Hoisting: For
negate(sign_ext(x)), if the range analysis shows thatxcannot be the minimum representable signed value, this can be simplified tosign_ext(negate(x)), reducing the width of thenegateoperation. More generally, it finds the minimal bit width for the innernegateand then re-extends. -
Narrowing Shift Operations (
shll,shra,shrl): * Zero Shift Amount: If a shift amount is provably zero, the shift operation is replaced directly by its value operand (a no-op).* Known Leading/Trailing Zeros/Sign Bits: For shift operations, if parts of the
shift_valueare known to be zero or sign bits, theshift_valuecan be sliced to remove these redundant bits before the shift, and the result re-extended (zero-extend or sign-extend) if necessary. Theshift_amountitself can also be narrowed if it has leading zeros.* Out-of-Bounds Shifts: Shift operations that are guaranteed to shift all bits off the end of the operand (resulting in a zero value) are replaced by a literal zero.
-
Narrowing
AddandSubOperations: * Common Leading Zeros/Sign Bits: Foraddandsuboperations, if both operands share a common number of leading zeros (for unsigned results) or sign bits (for signed results), the operation can be performed on a narrower bit width. The result is then zero-extended or sign-extended back to the original width. This includes careful handling of potential overflows for signed additions. -
Narrowing
MultiplyOperations (umul,smul,umulp,smulp): * Result Wider Than Sum of Operands: If the declared result width of a multiply operation is greater than the sum of the bit widths of its operands, the multiplication can be performed at the sum-of-operand widths, and the result then extended.* Operands Wider Than Result: If the operands are wider than the required result width, they can be narrowed (sliced) before the multiplication, reducing the complexity of the multiplier.
* Extended Operands (Zero-extend/Sign-extend): When operands are the results of
zero_extorsign_extoperations, they can often be narrowed back to their original non-extended width, with the multiplication type adjusted (e.g.,umulorsmul) if necessary to maintain correctness.* Trailing Zeros: Multiplies where one or both operands have known trailing zeros can be optimized by performing the multiplication on the non-zero bits and concatenating the result with the appropriate number of trailing zeros.
* Partial Product Optimization: For
umulp/smulp(partial product multiplies), if the two partial products are immediately summed (e.g.,add(tuple_index(mulp_op, 0), tuple_index(mulp_op, 1))), the overall operation can be narrowed, and the final sum then extended. -
Narrowing
ArrayIndexOperations: * Literal Index Values: If an index to anarray_indexis a known literal, its bit width can be narrowed to the minimum required to represent the actual array size, saving bits in the index computation.* Known Zero Index: If an index is provably zero, it's replaced with a literal zero of appropriate width.
* Known Out-of-Bounds Index: Similar to
BitSliceSimplificationPass, if an index is provably out of bounds, it's clamped to the maximum valid index.* Convert
ArrayIndextoSelect: Forarray_indexoperations with a small, discrete set of possible index values (based on range analysis), the operation can be converted to aselectchain, making explicit checks for each possible index value. This can be beneficial for small arrays by removing complex indexing logic. -
Narrowing
DecodeOperations: * Leading Zeros in Index: If the index of adecodeoperation has leading zeros, the index can be sliced to remove them, and thedecodeperformed on the narrower index, with the result zero-extended if needed.* Zero Index: A
decodewith a provably zero index is replaced by a literal one, asdecode(0)always results in a one-hot encoding with the least significant bit set.
The NarrowingPass is typically run repeatedly within an optimization
pipeline until a fixed point is reached. This iterative process is crucial
for achieving maximal bit width reduction across the entire IR, as narrowing
one node can often enable further narrowing of its consumers or producers.
narrow(OptionalContext) - Narrowing
A pass which reduces the width of operations eliminating redundant or unused bits.
Note
What follows was generated by the Gemini LLM. Not human verified.
The NarrowingPass is a powerful optimization pass in XLS designed to reduce
the bit width of bits-typed operations and values within a function or
proc. This is a critical optimization for hardware generation, as a
reduction in bit widths directly translates to smaller, more efficient, and
often faster hardware (fewer wires, smaller functional units, and smaller
registers). The pass employs various advanced analysis techniques to
determine the minimum required bit width for each value without altering its
functional correctness.
The pass is configured with an AnalysisType enum, which dictates the
sophistication of the analysis used:
kTernary: Utilizes a simpler ternary logic-based query engine. This analysis determines for each bit if it is always zero, always one, or unknown.
kRange: Employs a more powerful range analysis to determine the possible numerical bounds (minimum and maximum values) that a bit-vector can take. This provides more precise information for narrowing.
kRangeWithContext: Extends range analysis to be context-sensitive. This means it considers predicates (conditions) ofselectoperations and other conditional control flow to derive more precise ranges for values within specific execution paths.
kRangeWithOptionalContext: Allows the choice betweenkRangeandkRangeWithContextbased on theoptions.use_context_narrowing_analysisflag, providing flexibility in trade-off between analysis time and precision.
The pass operates by iteratively traversing the IR and applying transformations to nodes where bit widths can be safely reduced. Key optimizations include:
-
Replacing Precise Values with Literals: If an analysis (ternary or range) can definitively determine that a node's value is precisely known (i.e., it always evaluates to a constant), that node is replaced with a
literalnode. This simplifies the graph and can enable further optimizations. -
Narrowing Comparison Operations: * Stripping Matched Leading/Trailing Bits: For comparison operations (
eq,ne,ult,ugt, etc.), if leading or trailing bits of both operands are known to be identical, these matching bits can be logically removed, and the comparison is performed on the narrower remaining bits.``` // Original: UGt(0b0110_0XXX_0011, 0b0110_0YYY_0011) // bit strings // Leading `0110` and trailing `0011` match for both operands. // Optimized: UGt(0bXXX, 0bYYY) ```* Signed Comparison Simplification: Signed comparisons with zero-extended operands (or operands whose MSBs are known to be equal) can often be converted to unsigned comparisons on narrower bit widths, as the sign information becomes redundant.
-
Narrowing
NegateOperations: * Trailing Zeros: If an operand to anegateoperation has known trailing zeros, thenegatecan be performed on the more significant bits, and the trailing zeros re-concatenated, effectively reducing the width of thenegateoperation.* Sign Extension Hoisting: For
negate(sign_ext(x)), if the range analysis shows thatxcannot be the minimum representable signed value, this can be simplified tosign_ext(negate(x)), reducing the width of thenegateoperation. More generally, it finds the minimal bit width for the innernegateand then re-extends. -
Narrowing Shift Operations (
shll,shra,shrl): * Zero Shift Amount: If a shift amount is provably zero, the shift operation is replaced directly by its value operand (a no-op).* Known Leading/Trailing Zeros/Sign Bits: For shift operations, if parts of the
shift_valueare known to be zero or sign bits, theshift_valuecan be sliced to remove these redundant bits before the shift, and the result re-extended (zero-extend or sign-extend) if necessary. Theshift_amountitself can also be narrowed if it has leading zeros.* Out-of-Bounds Shifts: Shift operations that are guaranteed to shift all bits off the end of the operand (resulting in a zero value) are replaced by a literal zero.
-
Narrowing
AddandSubOperations: * Common Leading Zeros/Sign Bits: Foraddandsuboperations, if both operands share a common number of leading zeros (for unsigned results) or sign bits (for signed results), the operation can be performed on a narrower bit width. The result is then zero-extended or sign-extended back to the original width. This includes careful handling of potential overflows for signed additions. -
Narrowing
MultiplyOperations (umul,smul,umulp,smulp): * Result Wider Than Sum of Operands: If the declared result width of a multiply operation is greater than the sum of the bit widths of its operands, the multiplication can be performed at the sum-of-operand widths, and the result then extended.* Operands Wider Than Result: If the operands are wider than the required result width, they can be narrowed (sliced) before the multiplication, reducing the complexity of the multiplier.
* Extended Operands (Zero-extend/Sign-extend): When operands are the results of
zero_extorsign_extoperations, they can often be narrowed back to their original non-extended width, with the multiplication type adjusted (e.g.,umulorsmul) if necessary to maintain correctness.* Trailing Zeros: Multiplies where one or both operands have known trailing zeros can be optimized by performing the multiplication on the non-zero bits and concatenating the result with the appropriate number of trailing zeros.
* Partial Product Optimization: For
umulp/smulp(partial product multiplies), if the two partial products are immediately summed (e.g.,add(tuple_index(mulp_op, 0), tuple_index(mulp_op, 1))), the overall operation can be narrowed, and the final sum then extended. -
Narrowing
ArrayIndexOperations: * Literal Index Values: If an index to anarray_indexis a known literal, its bit width can be narrowed to the minimum required to represent the actual array size, saving bits in the index computation.* Known Zero Index: If an index is provably zero, it's replaced with a literal zero of appropriate width.
* Known Out-of-Bounds Index: Similar to
BitSliceSimplificationPass, if an index is provably out of bounds, it's clamped to the maximum valid index.* Convert
ArrayIndextoSelect: Forarray_indexoperations with a small, discrete set of possible index values (based on range analysis), the operation can be converted to aselectchain, making explicit checks for each possible index value. This can be beneficial for small arrays by removing complex indexing logic. -
Narrowing
DecodeOperations: * Leading Zeros in Index: If the index of adecodeoperation has leading zeros, the index can be sliced to remove them, and thedecodeperformed on the narrower index, with the result zero-extended if needed.* Zero Index: A
decodewith a provably zero index is replaced by a literal one, asdecode(0)always results in a one-hot encoding with the least significant bit set.
The NarrowingPass is typically run repeatedly within an optimization
pipeline until a fixed point is reached. This iterative process is crucial
for achieving maximal bit width reduction across the entire IR, as narrowing
one node can often enable further narrowing of its consumers or producers.
narrow(Range) - Narrowing
A pass which reduces the width of operations eliminating redundant or unused bits.
Note
What follows was generated by the Gemini LLM. Not human verified.
The NarrowingPass is a powerful optimization pass in XLS designed to reduce
the bit width of bits-typed operations and values within a function or
proc. This is a critical optimization for hardware generation, as a
reduction in bit widths directly translates to smaller, more efficient, and
often faster hardware (fewer wires, smaller functional units, and smaller
registers). The pass employs various advanced analysis techniques to
determine the minimum required bit width for each value without altering its
functional correctness.
The pass is configured with an AnalysisType enum, which dictates the
sophistication of the analysis used:
kTernary: Utilizes a simpler ternary logic-based query engine. This analysis determines for each bit if it is always zero, always one, or unknown.
kRange: Employs a more powerful range analysis to determine the possible numerical bounds (minimum and maximum values) that a bit-vector can take. This provides more precise information for narrowing.
kRangeWithContext: Extends range analysis to be context-sensitive. This means it considers predicates (conditions) ofselectoperations and other conditional control flow to derive more precise ranges for values within specific execution paths.
kRangeWithOptionalContext: Allows the choice betweenkRangeandkRangeWithContextbased on theoptions.use_context_narrowing_analysisflag, providing flexibility in trade-off between analysis time and precision.
The pass operates by iteratively traversing the IR and applying transformations to nodes where bit widths can be safely reduced. Key optimizations include:
-
Replacing Precise Values with Literals: If an analysis (ternary or range) can definitively determine that a node's value is precisely known (i.e., it always evaluates to a constant), that node is replaced with a
literalnode. This simplifies the graph and can enable further optimizations. -
Narrowing Comparison Operations: * Stripping Matched Leading/Trailing Bits: For comparison operations (
eq,ne,ult,ugt, etc.), if leading or trailing bits of both operands are known to be identical, these matching bits can be logically removed, and the comparison is performed on the narrower remaining bits.``` // Original: UGt(0b0110_0XXX_0011, 0b0110_0YYY_0011) // bit strings // Leading `0110` and trailing `0011` match for both operands. // Optimized: UGt(0bXXX, 0bYYY) ```* Signed Comparison Simplification: Signed comparisons with zero-extended operands (or operands whose MSBs are known to be equal) can often be converted to unsigned comparisons on narrower bit widths, as the sign information becomes redundant.
-
Narrowing
NegateOperations: * Trailing Zeros: If an operand to anegateoperation has known trailing zeros, thenegatecan be performed on the more significant bits, and the trailing zeros re-concatenated, effectively reducing the width of thenegateoperation.* Sign Extension Hoisting: For
negate(sign_ext(x)), if the range analysis shows thatxcannot be the minimum representable signed value, this can be simplified tosign_ext(negate(x)), reducing the width of thenegateoperation. More generally, it finds the minimal bit width for the innernegateand then re-extends. -
Narrowing Shift Operations (
shll,shra,shrl): * Zero Shift Amount: If a shift amount is provably zero, the shift operation is replaced directly by its value operand (a no-op).* Known Leading/Trailing Zeros/Sign Bits: For shift operations, if parts of the
shift_valueare known to be zero or sign bits, theshift_valuecan be sliced to remove these redundant bits before the shift, and the result re-extended (zero-extend or sign-extend) if necessary. Theshift_amountitself can also be narrowed if it has leading zeros.* Out-of-Bounds Shifts: Shift operations that are guaranteed to shift all bits off the end of the operand (resulting in a zero value) are replaced by a literal zero.
-
Narrowing
AddandSubOperations: * Common Leading Zeros/Sign Bits: Foraddandsuboperations, if both operands share a common number of leading zeros (for unsigned results) or sign bits (for signed results), the operation can be performed on a narrower bit width. The result is then zero-extended or sign-extended back to the original width. This includes careful handling of potential overflows for signed additions. -
Narrowing
MultiplyOperations (umul,smul,umulp,smulp): * Result Wider Than Sum of Operands: If the declared result width of a multiply operation is greater than the sum of the bit widths of its operands, the multiplication can be performed at the sum-of-operand widths, and the result then extended.* Operands Wider Than Result: If the operands are wider than the required result width, they can be narrowed (sliced) before the multiplication, reducing the complexity of the multiplier.
* Extended Operands (Zero-extend/Sign-extend): When operands are the results of
zero_extorsign_extoperations, they can often be narrowed back to their original non-extended width, with the multiplication type adjusted (e.g.,umulorsmul) if necessary to maintain correctness.* Trailing Zeros: Multiplies where one or both operands have known trailing zeros can be optimized by performing the multiplication on the non-zero bits and concatenating the result with the appropriate number of trailing zeros.
* Partial Product Optimization: For
umulp/smulp(partial product multiplies), if the two partial products are immediately summed (e.g.,add(tuple_index(mulp_op, 0), tuple_index(mulp_op, 1))), the overall operation can be narrowed, and the final sum then extended. -
Narrowing
ArrayIndexOperations: * Literal Index Values: If an index to anarray_indexis a known literal, its bit width can be narrowed to the minimum required to represent the actual array size, saving bits in the index computation.* Known Zero Index: If an index is provably zero, it's replaced with a literal zero of appropriate width.
* Known Out-of-Bounds Index: Similar to
BitSliceSimplificationPass, if an index is provably out of bounds, it's clamped to the maximum valid index.* Convert
ArrayIndextoSelect: Forarray_indexoperations with a small, discrete set of possible index values (based on range analysis), the operation can be converted to aselectchain, making explicit checks for each possible index value. This can be beneficial for small arrays by removing complex indexing logic. -
Narrowing
DecodeOperations: * Leading Zeros in Index: If the index of adecodeoperation has leading zeros, the index can be sliced to remove them, and thedecodeperformed on the narrower index, with the result zero-extended if needed.* Zero Index: A
decodewith a provably zero index is replaced by a literal one, asdecode(0)always results in a one-hot encoding with the least significant bit set.
The NarrowingPass is typically run repeatedly within an optimization
pipeline until a fixed point is reached. This iterative process is crucial
for achieving maximal bit width reduction across the entire IR, as narrowing
one node can often enable further narrowing of its consumers or producers.
narrow(Ternary) - Narrowing
A pass which reduces the width of operations eliminating redundant or unused bits.
Note
What follows was generated by the Gemini LLM. Not human verified.
The NarrowingPass is a powerful optimization pass in XLS designed to reduce
the bit width of bits-typed operations and values within a function or
proc. This is a critical optimization for hardware generation, as a
reduction in bit widths directly translates to smaller, more efficient, and
often faster hardware (fewer wires, smaller functional units, and smaller
registers). The pass employs various advanced analysis techniques to
determine the minimum required bit width for each value without altering its
functional correctness.
The pass is configured with an AnalysisType enum, which dictates the
sophistication of the analysis used:
kTernary: Utilizes a simpler ternary logic-based query engine. This analysis determines for each bit if it is always zero, always one, or unknown.
kRange: Employs a more powerful range analysis to determine the possible numerical bounds (minimum and maximum values) that a bit-vector can take. This provides more precise information for narrowing.
kRangeWithContext: Extends range analysis to be context-sensitive. This means it considers predicates (conditions) ofselectoperations and other conditional control flow to derive more precise ranges for values within specific execution paths.
kRangeWithOptionalContext: Allows the choice betweenkRangeandkRangeWithContextbased on theoptions.use_context_narrowing_analysisflag, providing flexibility in trade-off between analysis time and precision.
The pass operates by iteratively traversing the IR and applying transformations to nodes where bit widths can be safely reduced. Key optimizations include:
-
Replacing Precise Values with Literals: If an analysis (ternary or range) can definitively determine that a node's value is precisely known (i.e., it always evaluates to a constant), that node is replaced with a
literalnode. This simplifies the graph and can enable further optimizations. -
Narrowing Comparison Operations: * Stripping Matched Leading/Trailing Bits: For comparison operations (
eq,ne,ult,ugt, etc.), if leading or trailing bits of both operands are known to be identical, these matching bits can be logically removed, and the comparison is performed on the narrower remaining bits.``` // Original: UGt(0b0110_0XXX_0011, 0b0110_0YYY_0011) // bit strings // Leading `0110` and trailing `0011` match for both operands. // Optimized: UGt(0bXXX, 0bYYY) ```* Signed Comparison Simplification: Signed comparisons with zero-extended operands (or operands whose MSBs are known to be equal) can often be converted to unsigned comparisons on narrower bit widths, as the sign information becomes redundant.
-
Narrowing
NegateOperations: * Trailing Zeros: If an operand to anegateoperation has known trailing zeros, thenegatecan be performed on the more significant bits, and the trailing zeros re-concatenated, effectively reducing the width of thenegateoperation.* Sign Extension Hoisting: For
negate(sign_ext(x)), if the range analysis shows thatxcannot be the minimum representable signed value, this can be simplified tosign_ext(negate(x)), reducing the width of thenegateoperation. More generally, it finds the minimal bit width for the innernegateand then re-extends. -
Narrowing Shift Operations (
shll,shra,shrl): * Zero Shift Amount: If a shift amount is provably zero, the shift operation is replaced directly by its value operand (a no-op).* Known Leading/Trailing Zeros/Sign Bits: For shift operations, if parts of the
shift_valueare known to be zero or sign bits, theshift_valuecan be sliced to remove these redundant bits before the shift, and the result re-extended (zero-extend or sign-extend) if necessary. Theshift_amountitself can also be narrowed if it has leading zeros.* Out-of-Bounds Shifts: Shift operations that are guaranteed to shift all bits off the end of the operand (resulting in a zero value) are replaced by a literal zero.
-
Narrowing
AddandSubOperations: * Common Leading Zeros/Sign Bits: Foraddandsuboperations, if both operands share a common number of leading zeros (for unsigned results) or sign bits (for signed results), the operation can be performed on a narrower bit width. The result is then zero-extended or sign-extended back to the original width. This includes careful handling of potential overflows for signed additions. -
Narrowing
MultiplyOperations (umul,smul,umulp,smulp): * Result Wider Than Sum of Operands: If the declared result width of a multiply operation is greater than the sum of the bit widths of its operands, the multiplication can be performed at the sum-of-operand widths, and the result then extended.* Operands Wider Than Result: If the operands are wider than the required result width, they can be narrowed (sliced) before the multiplication, reducing the complexity of the multiplier.
* Extended Operands (Zero-extend/Sign-extend): When operands are the results of
zero_extorsign_extoperations, they can often be narrowed back to their original non-extended width, with the multiplication type adjusted (e.g.,umulorsmul) if necessary to maintain correctness.* Trailing Zeros: Multiplies where one or both operands have known trailing zeros can be optimized by performing the multiplication on the non-zero bits and concatenating the result with the appropriate number of trailing zeros.
* Partial Product Optimization: For
umulp/smulp(partial product multiplies), if the two partial products are immediately summed (e.g.,add(tuple_index(mulp_op, 0), tuple_index(mulp_op, 1))), the overall operation can be narrowed, and the final sum then extended. -
Narrowing
ArrayIndexOperations: * Literal Index Values: If an index to anarray_indexis a known literal, its bit width can be narrowed to the minimum required to represent the actual array size, saving bits in the index computation.* Known Zero Index: If an index is provably zero, it's replaced with a literal zero of appropriate width.
* Known Out-of-Bounds Index: Similar to
BitSliceSimplificationPass, if an index is provably out of bounds, it's clamped to the maximum valid index.* Convert
ArrayIndextoSelect: Forarray_indexoperations with a small, discrete set of possible index values (based on range analysis), the operation can be converted to aselectchain, making explicit checks for each possible index value. This can be beneficial for small arrays by removing complex indexing logic. -
Narrowing
DecodeOperations: * Leading Zeros in Index: If the index of adecodeoperation has leading zeros, the index can be sliced to remove them, and thedecodeperformed on the narrower index, with the result zero-extended if needed.* Zero Index: A
decodewith a provably zero index is replaced by a literal one, asdecode(0)always results in a one-hot encoding with the least significant bit set.
The NarrowingPass is typically run repeatedly within an optimization
pipeline until a fixed point is reached. This iterative process is crucial
for achieving maximal bit width reduction across the entire IR, as narrowing
one node can often enable further narrowing of its consumers or producers.
next_value_opt - Next Value Optimization
Pass which tries to optimize next_value nodes within a Proc.
Note
What follows was generated by the Gemini LLM. Not human verified.
NextValueOptimizationPass simplifies next_value state update nodes in a
Proc and exposes opportunities for downstream passes such as narrowing,
constant folding, and dead code elimination.
Optimizations
-
Removing Constant Predicates: Using
StatelessQueryEngine, if anext_valuenode has apredicateoperand whose value is known to be a constant:- Constant
0(false): Thenext_valuenever fires and is removed. - Constant
1(true): Thepredicateoperand is removed, making thenext_valueunconditional.
Example (removing a dead
next_value):// Before f: bits[1] = literal(value=0) next_v: () = next_value(state_element=x, value=my_value, predicate=f) // After // (next_v is removed) - Constant
-
Splitting Select-Based Values: When
options.splits_enabled()is true andmax_split_depth > 0(defaultkDefaultMaxSplitDepth = 10), anext_valuewhosevalueoperand is a select operation can be split into separatenext_valuenodes for each case (and default case, if present). Each newnext_valueis predicated on the conjunction (and) of the originalnext_valuepredicate (if any) and the condition selecting that case:sel(Select): Split only ifoptions.split_next_value_selects(defaultkDefaultSplitNextValueSelects = 4) is set and the number of cases is at most*options.split_next_value_selects.priority_sel(PrioritySelect): Always eligible for splitting up tomax_split_depth.one_hot_sel(OneHotSelect): Split only ifStatelessQueryEngineprovesExactlyOneBitTrue(selector).
Newly split
next_valuenodes are pushed back onto the worklist so they can undergo constant-predicate removal or further recursive select splitting up tomax_split_depth.Example (splitting a
sel):// Before s: bits[2] = state_read(state_element=x) c0: bits[2] = literal(value=2) c1: bits[2] = literal(value=1) def: bits[2] = literal(value=3) next_val: bits[2] = sel(s, cases=[c0, c1], default=def) next_v: () = next_value(state_element=x, value=next_val) // After s: bits[2] = state_read(state_element=x) c0: bits[2] = literal(value=2) c1: bits[2] = literal(value=1) def: bits[2] = literal(value=3) zero: bits[2] = literal(value=0) one: bits[2] = literal(value=1) max_case: bits[2] = literal(value=1) is_0: bits[1] = eq(s, zero) is_1: bits[1] = eq(s, one) is_def: bits[1] = ugt(s, max_case) next_v_case_0: () = next_value(state_element=x, value=c0, predicate=is_0) next_v_case_1: () = next_value(state_element=x, value=c1, predicate=is_1) next_v_def: () = next_value(state_element=x, value=def, predicate=is_def) -
Decoupling Equivalent Non-Synthesizable State Elements:
NonSynthSeparationPassduplicates state elements read by non-synthesizable operations intonon_synthesizablestate elements with identical initial values andnext_valueupdates. Before processing the worklist, this pass snapshots each state element's initial value and sorted pre-pass(value, predicate)next_valuelist. When splitting a select on anext_valuefor anon_synthesizablestate element, any branch (case or default) whose value is astate_readof a synthesizable state element with an identical pre-pass snapshot is rewritten to astate_readof thatnon_synthesizablestate element with a matchingpredicate(if one exists). Because matching compares pre-pass snapshots rather than pairing elements 1-to-1, non-synthesizable updates are rewritten even when multiple synthesizable andnon_synthesizablestate elements share identical transitions, decoupling the synthesizablestate_readfrom non-synthesizable pass-through updates soConditionalSpecializationPasscan predicate the synthesizablestate_read.
non_synth_separation - Non-Synthesizable Separation
Separates out non-synthesizable nodes like assert/cover/trace from the main function into a cloned function. Every function effectively has two versions, one with synthesizable nodes and one without. The synthesizable version invokes the non-synthesizable version of its function. This ensures that non-synthesizable uses of values do not affect the optimization of the synthesizable parts of the function.
Note
What follows was generated by the Gemini LLM. Not human verified.
NonSynthSeparationPass isolates non-synthesizable operations (assert,
cover, and trace) from the synthesizable logic of each function or proc
in a package. Without this separation, values consumed by verification or
debugging operations appear live to passes like Dead Code Elimination (DCE)
or Proc state narrowing/elimination, preventing those passes from optimizing
the synthesizable hardware path.
How It Works
-
Identification: The pass inspects each
FunctionBasein the package. If a function or proc contains noassert,cover, ortracenodes, it is left unchanged. -
Cloning into a
#[non_synth]Function: For each function or proc containing non-synthesizable nodes, a new function namednon_synth_<name>(uniquified if needed) is created and marked withset_non_synth(true):- For a
Function: The function is cloned directly with the same parameters. Its return value is replaced with an empty tupletuple(), and aninvoketonon_synth_<name>(passing the function's parameters) is inserted into the original function. - For a
Proc: The proc body is cloned into a statelessFunctionviaCloneProcAsFunctionVisitor, converting proc-specific constructs so they can be passed as arguments to aninvokein the proc:Send: Bypassed in the cloned function by mapping thesendnode directly to its mapped input token.Receive: The token at tuple index 0 is sliced out (SliceTuple) in the proc, and the remaining payload elements are passed as an argument to theinvoke(becoming aParamin the cloned function, where the mapped token is spliced back in at index 0).StateRead: Pure token state reads are replaced withliteral(token)in the cloned function. For non-token state elements, the pass appends a duplicate state element<state>_non_synthmarkednon_synthesizable=true(with the same initial value) and a correspondingstate_readin the proc, passing that read into theinvoke. If the state type contains tokens, token leaf elements are stripped before theinvokeand replaced with freshliteral(token)nodes inside the cloned function.Next: Not copied into the cloned function; instead, for each non-tokennext_valuein the proc, a matchingnext_valuenode is added to update the<state>_non_synthstate element.
- For a
-
Gate-to-Select Conversion in the Non-Synthesizable Function: Any
gate(cond, data)operations insidenon_synth_<name>are replaced withsel(cond, cases=[data], default=0)(ReplaceGatesWithSelectsVisitor). Becausegatenodes are special power-optimization nodes that DCE does not remove, converting them toselprevents unnecessary gate duplication and allows unused logic in the non-synthesizable function to be optimized away. -
Stripping Non-Synthesizable Nodes from the Original Function/Proc:
RemoveNonSynthNodesVisitorremoves allassert,trace, andcovernodes from the originalFunctionBase(replacingassertandtraceuses with their inputtokenoperand andcoveruses withtuple()).
Example
// Before
fn my_func(x: bits[32]) -> bits[32] {
tok: token = literal(value=token)
intermediate: bits[32] = add(x, literal(value=1, bits=32))
is_zero: bits[1] = eq(intermediate, literal(value=0, bits=32))
assert.1: token = assert(tok, is_zero, message="intermediate is zero!")
ret result: bits[32] = umul(intermediate, literal(value=2, bits=32))
}
After NonSynthSeparationPass (and subsequent DCE cleanup):
// Synthesizable version (original function, modified)
fn my_func(x: bits[32]) -> bits[32] {
intermediate: bits[32] = add(x, literal(value=1, bits=32))
invoke.1: () = invoke(x, to_apply=non_synth_my_func)
ret result: bits[32] = umul(intermediate, literal(value=2, bits=32))
}
// Non-synthesizable version (newly created function)
#[non_synth]
fn non_synth_my_func(x: bits[32]) -> () {
tok: token = literal(value=token)
intermediate: bits[32] = add(x, literal(value=1, bits=32))
is_zero: bits[1] = eq(intermediate, literal(value=0, bits=32))
assert.1: token = assert(tok, is_zero, message="intermediate is zero!")
ret tuple.1: () = tuple()
}
one-leaf-inlining - leaf function inlining passes
inline one level of functions.
Invoked Passes
post-inlining - Post-inlining passes
Passes performed after inlining
Invoked Passes
- post-inlining-opt(>=1)
- dce
- label-recovery
- resource_sharing
- collapse_select_chains
- dce
- name_promotion
post-inlining-opt - post-inlining optimization passes
Passes performed after inlining
Invoked Passes
- fixedpoint_simp(2)
- cond_spec(noBdd)
- dce
- bdd_simp(2)
- dce
- basic_simp
- dce
- bdd_cse
- dce
- cond_spec(Bdd)
- dce
- fixedpoint_simp(2)
- narrow(OptionalContext)
- dce
- basic_simp
- dce
- arith_simp
- dce
- cse
- sparsify_select
- dce
- useless_assert_remove
- ram_rewrite
- useless_io_remove
- dce
- cond_spec(Bdd)
- channel_legalization
- token_dependency
- fixedpoint_simp(2)
- canonicalize_proc_state
- non_synth_separation
- dce
- next_value_opt
- dce
- fixedpoint_simp(2)
- dce
- invalidate_cached_proc_state_info
- proc_state_narrow
- dce
- proc_state_elimination
- proc_state_fsm
- proc_state_elimination
- dce
- proc_state_provenance_narrow
- dce
- proc_state_elimination
- proc_state_fsm
- proc_state_elimination
- dce
- repopulate_cached_proc_state_info
- bdd_simp(3)
- dce
- basic_simp
- dce
- bdd_cse
- select_lifting
- dce
- lut_conversion
- dce
- cond_spec(Bdd)
- dce
- fixedpoint_simp(3)
- select_range_simp
- dce
- fixedpoint_simp(3)
- bdd_simp(3)
- dce
- basic_simp
- dce
- bdd_cse
- dce
- invalidate_cached_proc_state_info
- proc_state_bits_shatter
- proc_state_tuple_flat
- repopulate_cached_proc_state_info
- fixedpoint_simp(3)
- useless_assert_remove
- useless_io_remove
- invalidate_cached_proc_state_info
- proc_state_provenance_narrow
- dce
- proc_state_elimination
- proc_state_fsm
- proc_state_elimination
- dce
- repopulate_cached_proc_state_info
- bdd_simp(3)
- dce
- basic_simp
- dce
- bdd_cse
- dce
- fixedpoint_simp(3)
- invalidate_cached_proc_state_info
- next_value_opt
- proc_state_elimination
- proc_state_fsm
- proc_state_elimination
- dce
- repopulate_cached_proc_state_info
- cond_spec(Bdd)
- dce
- select_merge
- dce
- fixedpoint_simp(3)
post-inlining-opt(>=1) - min-1 post-inlining optimization passes
Passes performed after inlining
Options Set
Min opt level: 1
Invoked Passes
pre-inlining - pre-inlining passes
Passes performed before each inlining.
Invoked Passes
prepare-for-scheduling - Prepare for scheduling optimization passes
Passes performed at the very end of optimization.
TODO(allight): We might want to move resource sharing into here fororganizational reasons.
TODO(allight): The duplication between this and scheduling-opt is a massive code-smell. Significant adjustments to codegen/sched pass pipelines are likely required.
Options Set
Min opt level: 1
Invoked Passes
proc_state_array_flat - Proc State Array Flattening
Pass which flattens array elements of the proc state into their constituent elements. Tuples are flattened in a different pass. Flattening improves optimizability because each state element can be considered and transformed in isolation. Flattening also gives the scheduler more flexibility; without flattening, each element in the aggregate must have the same lifetime.
Note
What follows was generated by the Gemini LLM. Not human verified.
ProcStateArrayFlatteningPass converts small array-typed StateElements in
a Proc into tuple-typed StateElements of their constituent elements,
relying on a subsequent ProcStateTupleFlatteningPass to decompose those
tuples into independent state elements.
Breaking array state elements apart allows downstream passes (such as state narrowing, constant propagation, and dead state elimination) to optimize each array slot independently, and frees the scheduler from forcing all elements of the array to share an identical register lifetime.
How It Works
- Flattening Heuristic (
ShouldFlattenStateElement): The pass inspects each array-typedStateElementowned by theProcand flattens it if its array size is at most 2 (size() <= 2). (AlthoughkMaxArrayFlattenSizeis defined on the class, the current implementation only flattens arrays of length 2 or smaller.) - State Element Conversion (
ArrayToTupleStateTransformer): UsingProc::TransformStateElement, an array state element of typeT[N]with initial value[v_0, ..., v_{N-1}]is replaced by a tuple state element of type(T, ..., T)with initial value(v_0, ..., v_{N-1}):- Transforming
StateReads: Uses of the old arrayStateReadare replaced with anarraynode (<old_state_read>_as_array) constructed fromtuple_index(new_state_read, i)fori = 0 .. N-1. - Transforming
NextValues: For eachnext_valuetargeting the state element, its array-typedvalueoperandvis converted into atuplenode (<v>_as_tuple) whose elements are extracted viaarray_index(v, indices=[literal(i)])(using index bit widthmax(1, CeilOfLog2(N))).
- Transforming
- Cleanup: The old
next_valuenodes and the original array-typedStateElementare removed from theProc.
Example
// Before
proc my_proc(s: bits[8][2], init={[0, 1]}) {
s_read: bits[8][2] = state_read(state_element=s)
idx0: bits[1] = literal(value=0)
elem0: bits[8] = array_index(s_read, indices=[idx0])
next_arr: bits[8][2] = array(elem0, literal(value=2, bits=8))
next_value(param=s, value=next_arr)
}
After ProcStateArrayFlatteningPass:
// After
proc my_proc(s: (bits[8], bits[8]), init={(0, 1)}) {
s_read: (bits[8], bits[8]) = state_read(state_element=s)
e0: bits[8] = tuple_index(s_read, index=0)
e1: bits[8] = tuple_index(s_read, index=1)
s_read_as_array: bits[8][2] = array(e0, e1)
idx0: bits[1] = literal(value=0)
elem0: bits[8] = array_index(s_read_as_array, indices=[idx0])
next_arr: bits[8][2] = array(elem0, literal(value=2, bits=8))
n0: bits[8] = array_index(next_arr, indices=[literal(value=0, bits=1)])
n1: bits[8] = array_index(next_arr, indices=[literal(value=1, bits=1)])
next_arr_as_tuple: (bits[8], bits[8]) = tuple(n0, n1)
next_value(param=s, value=next_arr_as_tuple)
}
Subsequent ArraySimplificationPass, TupleSimplificationPass, and
ProcStateTupleFlatteningPass passes then eliminate the intermediate array
and tuple reconstructions and split s into two scalar bits[8] state
elements.
proc_state_bits_shatter - Proc State Bits Shattering
Pass which transforms Bits-type elements of the proc state into tuples of components. Only flattens where it can show that doing so will enable dynamic state feedback opportunities later (assuming it's followed by a ProcStateTupleFlatteningPass).
Note
What follows was generated by the Gemini LLM. Not human verified.
ProcStateBitsShatteringPass splits wide bits-typed StateElements in a
Proc into tuples of narrower bits components when doing so will expose
independent conditional state updates for ProcStateTupleFlatteningPass and
NextValueOptimizationPass.
How It Works
-
Analyzing
next_valueNodes for Split Points: For eachbits-typedStateElement, the pass inspects all of itsnext_valuenodes:- Pass-through updates (
IsNoOpNext) are ignored because they trivially preserve all sub-slices. - If any non-no-op
next_valuehas avalueoperand that is not aconcatnode, the state element cannot be split. - For each
concatnext_value, candidate split boundaries (concat_splits, ordered from LSB to MSB) are computed from the bit widths of theconcat's operands (iterated in reverse, sinceconcatorders operands MSB-to-LSB). - Splitting is marked beneficial (
could_benefit_from_splitting = true) if at least one operand of aconcatis apriority_sel, or is aselwhenoptions.split_next_value_selects(defaultkDefaultSplitNextValueSelects = 4) is set andsel->cases().size() <= *options.split_next_value_selects.
- Pass-through updates (
-
Intersecting Split Points: When multiple non-no-op
next_valuenodes update the same state element, their candidate boundary sets are intersected (absl::c_set_intersection). Ifcould_benefit_from_splittingis true and the intersection still defines more than one component (split_ends.size() > 1), the state element is shattered. -
State Element Transformation (
TuplifyFlatStateElement): UsingProc::TransformStateElement, thebits[W]state element is replaced by a tuple(bits[w_0], bits[w_1], ..., bits[w_{k-1}])ordered from LSB slice to MSB slice:initial_value: Sliced into a tuple ofBitsvalues corresponding to[0, split_ends[0]),[split_ends[0], split_ends[1]), etc.- Transforming
StateReads: Uses of the oldStateReadare replaced withconcat(tuple_index(new_read, k-1), ..., tuple_index(new_read, 0))(reversing the LSB-to-MSB tuple elements to match MSB-to-LSBconcatorder). - Transforming
NextValues: Eachnext_value'svalueoperand is replaced withtuple(bit_slice(old_val, 0, w_0), ...).
Example
// Before
proc my_proc(x: bits[16], init={0}) {
x_read: bits[16] = state_read(state_element=x)
x_lo: bits[6] = bit_slice(x_read, start=0, width=6)
x_mid: bits[1] = bit_slice(x_read, start=6, width=1)
x_hi: bits[9] = bit_slice(x_read, start=7, width=9)
cond: bits[1] = or_reduce(x_lo)
new_mid: bits[1] = priority_sel(cond, cases=[not(x_mid)], default=x_mid)
next_x: bits[16] = concat(x_hi, new_mid, x_lo)
next_value(param=x, value=next_x)
}
After ProcStateBitsShatteringPass:
// After
proc my_proc(x: (bits[6], bits[1], bits[9]), init={(0, 0, 0)}) {
x_read: (bits[6], bits[1], bits[9]) = state_read(state_element=x)
t_lo: bits[6] = tuple_index(x_read, index=0)
t_mid: bits[1] = tuple_index(x_read, index=1)
t_hi: bits[9] = tuple_index(x_read, index=2)
x_reconstructed: bits[16] = concat(t_hi, t_mid, t_lo)
// ... next_x computed from x_reconstructed ...
s_lo: bits[6] = bit_slice(next_x, start=0, width=6)
s_mid: bits[1] = bit_slice(next_x, start=6, width=1)
s_hi: bits[9] = bit_slice(next_x, start=7, width=9)
next_tuple: (bits[6], bits[1], bits[9]) = tuple(s_lo, s_mid, s_hi)
next_value(param=x, value=next_tuple)
}
Followed by ProcStateTupleFlatteningPass, BitSliceSimplificationPass, and
NextValueOptimizationPass, the three components become independent state
elements where only the 1-bit middle element is conditionally updated.
proc_state_elimination - Proc State Elimination
Pass which tries to minimize the size and total number of elements of the proc state by removal of dead state elements and zero-width elements.
Note
What follows was generated by the Gemini LLM. Not human verified.
ProcStateEliminationPass minimizes the size and total number of state
elements in a Proc by removing zero-width, constant, and unobservable
state elements. Fewer state elements directly reduce register count and area
in synthesized hardware.
How It Works
The pass performs three elimination stages in order:
-
Removal of Zero-Width State Elements (
RemoveZeroWidthStateElements): Any state element whose flat bit count is 0 and whose type contains no tokens (!TypeHasToken) cannot store information and is removed. ItsStateReadnodes are replaced with literals of itsinitial_value, and itsNextnodes are replaced with empty tuple literals()and deleted. -
Removal of Constant State Elements (
RemoveConstantStateElements): Using aUnionQueryEnginecombiningStatelessQueryEngineand a sharedLazyTernaryQueryEngine, the pass checks whether each state element ever changes from itsinitial_value. If everyNextnode for a state element either passes through one of the state element's ownStateReads or assigns a value proven equal toinitial_value(KnownValue), the state element is constant: all of itsStateReads are replaced withLiteral(initial_value), and itsNextnodes and state element are removed. This step runs in a fixed-point loop to collapse chains of state elements whose updates become constant once upstream state elements are replaced with literals. -
Removal of Unobservable State Elements (
RemoveUnobservableStateElements): Identifies and removes state elements that cannot affect any observable output of theProc:- Single-Cycle State Dependency Analysis:
StateDependencyVisitor(aDataflowVisitor<InlineBitmap>) computes which state elements each node depends on within a single activation (unioning both data and control sources acrossLeafTypeTreeelements). - State-to-State Adjacency Matrix: For each state element, the pass
unions the state dependencies of the
valueandpredicateoperands of all of itsNextnodes. - Transitive Observability (
ReachableFrom): Starting from the state dependencies of all side-effecting orinvokenodes in theProc(excludingstate_read,next_value, andgate), the pass computes the transitive closure over the state-dependency graph. - Elimination: Any state element not reachable from a side-effecting
or
invokenode is unobservable. ItsNextnodes are removed, any liveStateReads are replaced with zero-valued literals (ZeroOfType), and the state element is removed.
- Single-Cycle State Dependency Analysis:
Example
// Before
chan out(bits[32], id=0, kind=streaming, ops=send_only,
flow_control=ready_valid)
top proc my_proc() {
state_element(const_s, bits[32], init=1)
state_element(live_s, bits[32], init=0)
state_element(dead_s, bits[32], init=0)
c_read: bits[32] = state_read(state_element=const_s)
l_read: bits[32] = state_read(state_element=live_s)
d_read: bits[32] = state_read(state_element=dead_s)
one: bits[32] = literal(value=1)
next_value(param=const_s, value=one)
next_value(param=live_s, value=add(l_read, c_read))
next_value(param=dead_s, value=add(d_read, l_read))
tkn: token = literal(value=token)
send.1: token = send(tkn, l_read, channel=out)
}
After ProcStateEliminationPass:
* const_s is replaced by literal(value=1, bits=32) because its only
update writes 1 (matching init=1).
* dead_s is removed because it only feeds its own next_value and never
influences send.1 or live_s.
// After (simplified)
top proc my_proc() {
state_element(live_s, bits[32], init=0)
l_read: bits[32] = state_read(state_element=live_s)
c_lit: bits[32] = literal(value=1)
next_value(param=live_s, value=add(l_read, c_lit))
tkn: token = literal(value=token)
send.1: token = send(tkn, l_read, channel=out)
}
proc_state_fsm - Proc State Finite state machine Optimization
Pass which tries to minimize the size and total number of elements of the proc state by optimizing implicit state-machines in the state elements.
Note
What follows was generated by the Gemini LLM. Not human verified.
ProcStateFSMPass compresses state elements whose values evolve through a
known finite sequence of constants into a compact binary-encoded saturating
counter (state machine).
How It Works
-
Query Engine Setup: Combines
StatelessQueryEngineand a sharedLazyTernaryQueryEngineviaUnionQueryEngineto identifynext_valueexpressions that evaluate to known constants (IsFullyKnown). -
Detecting Constant Chains (
ConvertConstantChainsToStateMachines): In general,ConstantChainToStateMachineis designed to compress a shift chain ofkstate elementsc[0..k-1]wherenext[c[0]]is an unconditional constant andnext[c[i+1]] == state_read[c[i]]into a single binary counter of widthCeilOfLog2(k) + 1bits (avoiding ak-bit one-hot encoding). Currently,ConvertConstantChainsToStateMachinesdetects chains of lengthk = 1: any state element (of arbitrary width or compound type) that has a single unconditionalnext_value(predicate == std::nullopt) whosevalueis fully known by the query engine. -
State Machine Replacement (
ConstantChainToStateMachine):- Appends a new state element
state_machine_<names>of typebits[CeilOfLog2(k) + 1]initialized to0(markednon_synthesizableif any element in the chain was non-synthesizable). - Updates the state machine each tick using a saturating increment:
sel(ugt(state, k - 1), cases=[add(state, 1), state]). - Replaces each original
StateReadat chain indexjwith aselindexed bystate_machinewhosecasesare the reversed initial values[init[j], ..., init[0]]and whosedefaultis the known constantchain_literal. Fork = 1, this selectsinit[0]on tick 0 (whenstate_machine == 0) andchain_literalon all subsequent ticks (whenstate_machine == 1). - Removes the original state elements and their
Nextnodes, and repopulates the query engine.
- Appends a new state element
Example
Suppose a 32-bit state element s starts at 0x1234_5678 on the first
activation and unconditionally transitions to 0xDEAD_BEEF thereafter:
// Before
proc my_proc(s: bits[32], init={0x1234_5678}) {
s_read: bits[32] = state_read(state_element=s)
c: bits[32] = literal(value=0xdead_beef)
next_value(param=s, value=c)
}
ProcStateFSMPass replaces the 32-bit register s with a 1-bit saturating
counter state_machine_s:
// After
proc my_proc(state_machine_s: bits[1], init={0}) {
state_machine_s_read: bits[1] = state_read(state_element=state_machine_s)
one: bits[1] = literal(value=1)
max: bits[1] = literal(value=0)
plus_one: bits[1] = add(state_machine_s_read, one)
too_large: bits[1] = ugt(state_machine_s_read, max)
next_sm: bits[1] = sel(too_large, cases=[plus_one, state_machine_s_read])
next_value(param=state_machine_s, value=next_sm)
init_lit: bits[32] = literal(value=0x1234_5678)
chain_lit: bits[32] = literal(value=0xdead_beef)
s_read: bits[32] = sel(state_machine_s_read, cases=[init_lit],
default=chain_lit)
}
proc_state_narrow - Proc State Narrowing
Pass which tries to minimize the size of the proc state by narrowing state elements using range analysis.
Note
What follows was generated by the Gemini LLM. Not human verified.
ProcStateNarrowingPass reduces the bit width of bits-typed
StateElements in a Proc by analyzing how state values evolve across ticks
using ProcStateRangeQueryEngine. Narrowing state elements directly reduces
the number of flip-flops required in synthesized hardware.
How It Works
The pass populates a ProcStateRangeQueryEngine on the Proc (which tracks
both per-bit ternary knowledge and value intervals across proc back-edges)
and inspects each bits-typed StateElement:
-
Removing Known Leading Bits (
RemoveLeadingBits/ProcStateConcatNarrowTransform):- Computes the intersection (
ternary_ops::Intersection) of the ternary vectors across allStateReadnodes for the state element. - Counts the number of leading (most significant) bits whose values are
known constants (
CountLeadingOnesonToKnownBits). Note that these known leading bits can be any fixed bit pattern (zeros, ones, or a mix). - If
known_leading > 0, the state element is narrowed by slicing off the topknown_leadingbits from itsinitial_valueand from eachnext_value(bit_slice(next_val, start=0, width=new_width)). EachStateReadis reconstructed to the original width viaconcat(literal(leading_bits), new_state_read).
Example (removing known leading bits):
// Before proc my_proc(foo: bits[32], init={0}) { foo_read: bits[32] = state_read(state_element=foo) low_3: bits[3] = bit_slice(foo_read, start=0, width=3) inc: bits[3] = add(low_3, literal(value=1, bits=3)) next_foo: bits[32] = zero_ext(inc, new_bit_count=32) next_value(param=foo, value=next_foo) } // After proc my_proc(foo: bits[3], init={0}) { foo_read: bits[3] = state_read(state_element=foo) leading_bits_foo: bits[29] = literal(value=0) extended_foo: bits[32] = concat(leading_bits_foo, foo_read) low_3: bits[3] = bit_slice(extended_foo, start=0, width=3) inc: bits[3] = add(low_3, literal(value=1, bits=3)) next_foo: bits[32] = zero_ext(inc, new_bit_count=32) unexpand: bits[3] = bit_slice(next_foo, start=0, width=3) next_value(param=foo, value=unexpand) } - Computes the intersection (
-
Signed Range Narrowing (
RemoveSignBits/ProcStateSignExtendNarrowTransform):- If no leading bits are constant (
known_leading == 0), the pass queriesqe.GetIntervals(state_read)for eachStateReadof the state element and computesinterval_ops::MinimumSignedBitCount(taking the maximum required signed widthmax_signed_bitsacross all reads). - If
max_signed_bitsis smaller than the state element's bit width, the state element is narrowed tomax_signed_bitsbits: itsinitial_valueandnext_valueoperands are truncated withbit_slice(..., start=0, width=max_signed_bits), and eachStateReadis reconstructed to the original width viasign_ext(new_state_read, new_bit_count=old_width).
Example (signed range narrowing for a state element bounded in
[-8, 7]):// Before proc my_proc(bar: bits[32], init={0}) { bar_read: bits[32] = state_read(state_element=bar) // ... next_bar proven by ProcStateRangeQueryEngine to stay in [-8, 7] next_value(param=bar, value=next_bar) } // After proc my_proc(bar: bits[4], init={0}) { bar_read: bits[4] = state_read(state_element=bar) extended_bar: bits[32] = sign_ext(bar_read, new_bit_count=32) // ... next_bar computed using extended_bar ... unexpand: bits[4] = bit_slice(next_bar, start=0, width=4) next_value(param=bar, value=unexpand) } - If no leading bits are constant (
proc_state_provenance_narrow - Proc State Provenance Narrowing
Pass which tries to minimize the size and total number of elements of the proc state. This pass works by examining the provenance of the bits making up the next value to determine which (if any) bits are never actually modified.
NB This is a separate pass from ProcStateNarrowing for simplicity of implementation. That pass mostly assumes we'll have a range-analysis which this does not need.
Note
What follows was generated by the Gemini LLM. Not human verified.
ProcStateProvenanceNarrowingPass reduces the bit width of bits-typed
StateElements in a Proc by identifying individual bit positions
(leading, internal, or trailing) that never change from their initial_value
across any next_value update. Unlike ProcStateNarrowingPass, which uses
inter-cycle range analysis to strip leading bits, this pass uses single-cycle
bit provenance and ternary analysis to excise unchanging bit segments at any
offset within the bit vector.
How It Works
-
Identifying Unchanged Bits (
UnchangedBits): For eachbits-typedStateElementwith initial valueinitial_bits, the pass starts with an all-ones maskunchanged_bitsand intersects it across every non-no-opNextnode (!IsNoOpNext(next)):- Ternary Match (
LazyTernaryQueryEngine): Computesternary_known_unchanged, marking bits innext->value()that are known constants equal to the corresponding bits ininitial_bits. - Provenance Match (
BitProvenanceAnalysis): Queriesprovenance.GetBitSources(next->value())(TreeBitSources) and marks any bit range whose source is aStateReadof the samestate_elementat the exact same bit positions (source_bit_index_low == dest_bit_index_lowandsource_bit_index_high == dest_bit_index_high). - A bit remains set in
unchanged_bitsif, for everyNextnode, it is preserved via either provenance or ternary equivalence.
- Ternary Match (
-
Extracting Bit Segments (
ExtractBitSegments): Ifunchanged_bitsis non-zero, the state element's bit range is partitioned into contiguousBitSegments ordered from MSB to LSB. Each segment is either a constant segment (holding the corresponding slice ofinitial_bits) or a variable segment (value == std::nullopt). -
State Element Transformation (
NarrowTransform): UsingProc::TransformStateElement, the state element is narrowed to the concatenation of its variable segments (NarrowValue):- Transforming
StateReads: Reconstructs the original width by concatenating (from MSB to LSB)Literalnodes for constant segments andBitSlicenodes (ornew_state_readdirectly if there is only a single variable segment) for variable segments. - Transforming
NextValues: Slices only the variable segments fromold_next->value()(BitSlice) and concatenates them to form the narrowednext_value.
- Transforming
Example
Consider a 96-bit state element foo whose middle 32 bits ([32:64]) are
initialized to 0xFFFF_0000 and are always either copied from foo or
overwritten with 0xFFFF_0000:
// Before
proc my_proc(foo: bits[96], init={0x0000_0000_ffff_0000_0000_0000}) {
foo_read: bits[96] = state_read(state_element=foo)
lo: bits[32] = add(bit_slice(foo_read, start=0, width=32),
literal(value=1, bits=32))
mid: bits[32] = bit_slice(foo_read, start=32, width=32)
hi: bits[32] = add(bit_slice(foo_read, start=64, width=32),
literal(value=2, bits=32))
next_foo: bits[96] = concat(hi, mid, lo)
next_value(param=foo, value=next_foo)
}
ProcStateProvenanceNarrowingPass removes the unchanging middle 32 bits,
narrowing foo from 96 bits to 64 bits:
// After
proc my_proc(foo: bits[64], init={0x0000_0000_0000_0000}) {
foo_read: bits[64] = state_read(state_element=foo)
var_hi: bits[32] = bit_slice(foo_read, start=32, width=32)
const_mid: bits[32] = literal(value=0xffff_0000)
var_lo: bits[32] = bit_slice(foo_read, start=0, width=32)
foo_reconstructed: bits[96] = concat(var_hi, const_mid, var_lo)
// ... next_foo computed from foo_reconstructed ...
next_hi: bits[32] = bit_slice(next_foo, start=64, width=32)
next_lo: bits[32] = bit_slice(next_foo, start=0, width=32)
next_foo_slice_reduced: bits[64] = concat(next_hi, next_lo)
next_value(param=foo, value=next_foo_slice_reduced)
}
proc_state_tuple_flat - Proc State Tuple Flattening
Pass which flattens tuple elements of the proc state into their constituent components. Array elements are flattened in a different pass. Flattening improves optimizability because each state element can be considered and transformed in isolation. Flattening also gives the scheduler more flexibility; without flattening, each element in the aggregate must have the same lifetime.
Note
What follows was generated by the Gemini LLM. Not human verified.
ProcStateTupleFlatteningPass recursively decomposes tuple-typed
StateElements in a Proc into separate leaf (non-tuple) StateElements.
(Array-typed state elements are not decomposed by this pass; small arrays are
first converted into tuples by ProcStateArrayFlatteningPass.)
How It Works
If a Proc has at least one tuple-typed StateElement
(HasTupleStateElement), FlattenState rebuilds the proc state:
-
Decomposing Initial Values (
DecomposeValue): Each state element'sinitial_valueis recursively flattened across nested tuples into a list ofnum_componentsleafValues.- If
num_components == 1(e.g., a scalar state element or a 1-element tuple), the new state element retains the original name. - If
num_components > 1, each leaf state element is named<name>_0,<name>_1, etc. - If
num_components == 0(an empty tuple()), the state element decomposes into zero components and is eliminated.
- If
-
Decomposing
StateReads (ComposeNode): For eachStateReadof an original state element, aStateRead(preservingpredicateandlabel) is created on each corresponding leaf state element. The original tuple structure is reconstructed from the leafStateReads usingTuplenodes and replaces all uses of the originalStateRead. -
Decomposing
NextValues (DecomposeNode): For eachNextnode of an original state element,next->value()is recursively decomposed into leaf nodes by insertingTupleIndexoperations. A separateNextnode (preservingpredicateandlabel) is created for each leaf state element. -
Replacing Proc State (
ReplaceProcState): All oldNextnodes and state elements are removed and replaced with the flattened leafStateElements,StateReads, andNextnodes.
Example
// Before
proc my_proc(s: (bits[8], (bits[16], bits[32])), init={(1, (2, 3))}) {
s_read: (bits[8], (bits[16], bits[32])) = state_read(state_element=s)
a: bits[8] = tuple_index(s_read, index=0)
inner: (bits[16], bits[32]) = tuple_index(s_read, index=1)
next_s: (bits[8], (bits[16], bits[32])) = tuple(a, inner)
next_value(param=s, value=next_s)
}
After ProcStateTupleFlatteningPass:
// After
proc my_proc(s_0: bits[8], s_1: bits[16], s_2: bits[32], init={1, 2, 3}) {
s_0_read: bits[8] = state_read(state_element=s_0)
s_1_read: bits[16] = state_read(state_element=s_1)
s_2_read: bits[32] = state_read(state_element=s_2)
reconstructed_inner: (bits[16], bits[32]) = tuple(s_1_read, s_2_read)
s_read: (bits[8], (bits[16], bits[32])) = tuple(s_0_read,
reconstructed_inner)
a: bits[8] = tuple_index(s_read, index=0)
inner: (bits[16], bits[32]) = tuple_index(s_read, index=1)
next_s: (bits[8], (bits[16], bits[32])) = tuple(a, inner)
next_0: bits[8] = tuple_index(next_s, index=0)
next_inner: (bits[16], bits[32]) = tuple_index(next_s, index=1)
next_1: bits[16] = tuple_index(next_inner, index=0)
next_2: bits[32] = tuple_index(next_inner, index=1)
next_value(param=s_0, value=next_0)
next_value(param=s_1, value=next_1)
next_value(param=s_2, value=next_2)
}
Subsequent TupleSimplificationPass and DeadCodeEliminationPass runs
simplify away the intermediate tuple and tuple_index nodes.
ram_rewrite - RAM Rewrite
Pass that rewrites RAMs of one type to a new type. Generally this will be some kind of lowering from more abstract to concrete RAMs.
Note
What follows was generated by the Gemini LLM. Not human verified.
The RamRewritePass facilitates the transformation of RAM (Random Access
Memory) interfaces within an XLS package. Its primary role is to lower
abstract RAM models into concrete RAM representations that are directly
implementable by target hardware.
The pass is driven by the ram_rewrites list in OptimizationPassOptions.
Each RamRewrite entry specifies the source RAM configuration
(from_config), the target RAM configuration (to_config), a mapping from
logical channel names (e.g., abstract_read_req) to physical channel names
in the IR (from_channels_logical_to_physical), a to_name_prefix for newly
created channels, and an optional proc_name when channels are proc-scoped.
Key aspects of RamRewritePass include:
-
RAM Abstraction Levels (
RamKind): *kAbstract: A high-level, generic RAM model with separate logical channels for read requests (abstract_read_req:(addr, mask)), read responses (abstract_read_resp:(data)), write requests (abstract_write_req:(addr, data, mask)), and write completion (write_completion:()). *k1RW(One Read/Write Port): A concrete single-port RAM that can perform either a read or a write per cycle. It uses a unified request channel (1rw_req:(addr, data, write_mask, read_mask, we, re)), a response channel (1rw_resp:(data)), and awrite_completionchannel (()). *k1R1W(One Read, One Write Port): A concrete RAM with independent read and write ports (1r1w_read_req:(addr, mask),1r1w_read_resp:(data),1r1w_write_req:(addr, data, mask), andwrite_completion:()). * If a RAM configuration has no mask width defined,GetMaskTyperepresents the absent mask as an empty tuple(), which is later stripped during codegen. -
Channel Mapping and Payload Repacking: For each
RamRewrite, the pass inspects the existing channels to infer the commondata_typeandChannelStrictness, creates the new streaming channels forto_config(configured withFlowControl::kReadyValidand zero-depth bypassFifoConfig), and rewrites allsendandreceivenodes referencing the old channels:*
kAbstracttok1RW: *abstract_read_reqsends of(addr, read_mask)are mapped to1rw_reqsends with repacked payload(addr, 0, 0, read_mask, we=0, re=1). *abstract_write_reqsends of(addr, data, write_mask)are mapped to1rw_reqsends with repacked payload(addr, data, write_mask, 0, we=1, re=0). *abstract_read_respreceives are mapped to1rw_respreceives, andwrite_completionreceives are mapped to the newwrite_completionchannel. *kAbstracttok1R1W: *abstract_read_req,abstract_read_resp,abstract_write_req, andwrite_completionmap directly to1r1w_read_req,1r1w_read_resp,1r1w_write_req, andwrite_completionwithout altering tuple layouts.// Original abstract read request send: req: (bits[10], bits[4]) = tuple(addr, mask) tok1: token = send(tok0, req, channel=ram_read_req) // Rewritten 1RW request send (after tuple simplification): zero_data: bits[32] = literal(value=0) zero_wmask: bits[4] = literal(value=0) we: bits[1] = literal(value=0) re: bits[1] = literal(value=1) rw_req: (bits[10], bits[32], bits[4], bits[4], bits[1], bits[1]) = tuple(addr, zero_data, zero_wmask, mask, we, re) tok1: token = send(tok0, rw_req, channel=ram_req) -
Channel Cleanup and Scoping: After replacing all
sendandreceiveoperations in topological order, the pass removes the old channels from the package (or removes the oldChannelInterfaces from the targetProcwhenproc_nameis set and channels are proc-scoped).
reassociation - Reassociation
Reassociates associative operations to reduce delay by transforming chains of operations to a balanced tree of operations, and gathering together constants in the expression for folding.
Note
What follows was generated by the Gemini LLM. Not human verified.
The ReassociationPass is an optimization pass in XLS that reorders
associative operations such as addition (add), subtraction (sub), and
signed/unsigned multiplication (smul, umul). Its primary objectives are
to reduce the critical path delay of the synthesized hardware and to
facilitate further constant folding by grouping literal operands.
This pass is crucial for transforming deep, unbalanced chains of operations
(e.g., (((A + B) + C) + D)) into more balanced tree structures
(e.g., ((A + B) + (C + D))). It also effectively gathers together constant
operands within an associative expression, making them amenable to subsequent
constant folding optimizations.
Key Concepts:
- Associativity: The pass exploits the associative property of
operations like addition and multiplication. This property states that
for an associative operation
op,(A op B) op Cis mathematically equivalent toA op (B op C). Reassociation leverages this to restructure the computation graph. - Critical Path Delay Reduction: A deep, unbalanced chain of operations in the IR directly translates to a long critical path in the hardware, which limits the maximum clock frequency. By rebalancing these chains into a shallower tree, the pass effectively reduces the overall critical path delay.
- Constant Folding Facilitation: Grouping constant operands together
within an associative expression allows the
ConstantFoldingPassto combine them into a single literal. This simplifies the expression and reduces dynamic computation. - Overflow Handling: The pass is designed to carefully consider potential overflow conditions, particularly for signed arithmetic and operations involving different bit widths. This ensures that the semantic correctness of the original computation is rigorously preserved during reassociation.
How it Works:
-
AssociativeElementsClass: This internal helper class is central to the pass's operation. For each node identified as part of an associative chain, it recursively collects and models: *variables_: Non-constant leaf nodes (e.g., parameters or results of other complex expressions). *constants_: Constant leaf nodes (i.e.,literaloperations). *op_: The primary associative operation (Op::kAdd,Op::kSMul, etc.) governing the combination of these elements. *needs_negate: A boolean flag indicating if a variable needs to be logically negated, typically arising from subtraction operations (e.g.,A - Bis conceptually treated asA + (-B)). *overflows_: A flag indicating whether the sub-expression represented by thisAssociativeElementsobject can potentially overflow at its current bit-width. This information is crucial for safe combination. *depth_: Tracks the depth of the longest chain of associative operations leading to this particular node. -
OneShotReassociationVisitor: This visitor traverses the IR in a single pass to compute and collect theAssociativeElementsfor each relevant node. It includes logic to handle various operations: * Associative Operations (Add,Sub,SMul,UMul): For these operations, it recursively combines theAssociativeElementsof its operands, managing negation for subtraction and tracking potential overflow conditions. *Neg: Handles negation by logically flipping theneeds_negateflag of its operand'sAssociativeElementsrepresentation. * Extensions (ZeroExtend,SignExtend) andConcatoperations that effectively act asZeroExtend: These operations can widen a value without fundamentally changing its underlying numerical value. The pass attempts to "see through" these by propagating theAssociativeElementsof the inner operand if no overflow occurs and signedness compatibility is maintained. -
ReassociationCache: This caching mechanism stores the computedAssociativeElementsfor each node. This avoids redundant computations during iterative passes and helps ensure that analyses are kept up-to-date even after transformations have altered the graph structure. -
ReassociateFunction (Main Loop): * Fixed-Point Iteration: The pass operates in a fixed-point manner. It identifies nodes that are prime candidates for reassociation and repeatedly applies the transformation until no further beneficial changes can be made across the entire function. * Candidate Selection: Nodes are selected for reassociation if they meet specific criteria, including: * Not already a leaf node (i.e., they are part of a larger associative chain). * Not composed entirely of constants (these are handled by the separateConstantFoldingPass). * Having users that require materialization (i.e., the reassociation is not trivially hidden by other optimizations). * Their current depth in the IR graph is greater than the minimum possible depth for a balanced tree of its elements, or they contain multiple constants that can be meaningfully grouped. *ReassociateOneOperation: This function is responsible for actually reconstructing the selected associative operation into a balanced tree: * Grouping Constants: It first groups all constant operands together to be combined byConstantFoldingPass. * Balancing Tree: It then constructs a balanced binary tree using the variable elements, minimizing the depth of the overall computation. The tree is typically biased to the left to ensure a consistent output structure, which can further aid subsequent Common Subexpression Elimination (CSE). * Negation and Extension Handling: It correctly applies necessary negations and extensions (sign-extend/zero-extend) during the reconstruction process to strictly preserve semantic equivalence.
Benefits:
- Reduced Critical Path: By transforming deep chains of operations into balanced trees, the pass significantly reduces the critical path delay in the generated hardware, allowing for higher clock frequencies.
- Improved Constant Folding: Grouping constant operands together within
associative expressions enables
ConstantFoldingPassto reduce them to single literals, thereby simplifying the IR and reducing dynamic computation. - Enhanced IR Structure: Creates a more canonical and optimized structure for associative expressions, which can benefit subsequent optimization passes by providing a clearer and more efficient representation of the computation.
Example (Rebalancing additions): Consider a deep, left-leaning chain of addition operations:
// Original IR snippet (deep left-leaning chain)
fn deep_add(a: bits[32], b: bits[32], c: bits[32], d: bits[32]) -> bits[32] {
add.1: bits[32] = add(a, b)
add.2: bits[32] = add(add.1, c)
ret add.3: bits[32] = add(add.2, d)
}
The ReassociationPass would transform this into a balanced tree structure:
// Optimized IR (after ReassociationPass and a subsequent DCE pass)
fn deep_add(a: bits[32], b: bits[32], c: bits[32], d: bits[32]) -> bits[32] {
add.left: bits[32] = add(a, b)
add.right: bits[32] = add(c, d)
ret add.final: bits[32] = add(add.left, add.right)
}
This transformation reduces the maximum depth of the additions from 3 to 2, directly improving potential timing performance.
recv_default - Receive default value simplification
Optimization which removes useless selects between the data value of a conditional or non-blocking receive and the default value of the receive (all zeros).
Note
What follows was generated by the Gemini LLM. Not human verified.
The ReceiveDefaultValueSimplificationPass is a proc-level optimization pass
(OptimizationProcPass) that identifies and eliminates redundant binary
select and priority_select operations choosing between the data output of
a conditional or non-blocking receive and an all-zeros value.
In XLS, when a conditional receive has a false predicate, or when a
non-blocking receive has no data available (its valid bit is 0), its data
output (tuple_index(receive_node, index=1)) is already defined to be all
zeros. Frontends or earlier passes often emit an explicit select or
priority_select that forces the value to zero under those same conditions.
How it Works:
Using StatelessQueryEngine, the pass walks the proc in topological order
and inspects each two-way Select (cases=[on_false, on_true], no default)
and single-case PrioritySelect (cases=[on_true], default=on_false). It
matches MatchUselessSelectAfterReceive when:
on_trueistuple_index(receive, index=1)(the data payload of aReceivenode).on_falseis known to be all zeros (KnownValue(on_false)->IsAllZeros()).- One of the following selector conditions holds:
* Conditional
receive:receiveis predicated and its predicate isselector. * Non-blockingreceive:receiveis non-blocking andselectoris the valid bit (tuple_index(..., index=2)) of a non-blockingreceive.
When matched, the pass replaces the select or priority_select directly
with on_true (tuple_index(receive, index=1)).
Example (Conditional receive with redundant select):
// Original IR snippet
chan in(bits[32], kind=streaming, ops=receive_only, flow_control=ready_valid)
proc p(pred: bits[1], s: bits[32], init={1, 42}) {
tkn: token = literal(value=token)
// Data is already 0 if pred is 0
receive.1: (token, bits[32]) = receive(tkn, predicate=pred, channel=in)
receive_data: bits[32] = tuple_index(receive.1, index=1)
zero: bits[32] = literal(value=0)
select.2: bits[32] = sel(pred, cases=[zero, receive_data])
next (pred, select.2)
}
// Optimized IR snippet
chan in(bits[32], kind=streaming, ops=receive_only, flow_control=ready_valid)
proc p(pred: bits[1], s: bits[32], init={1, 42}) {
tkn: token = literal(value=token)
receive.1: (token, bits[32]) = receive(tkn, predicate=pred, channel=in)
receive_data: bits[32] = tuple_index(receive.1, index=1)
next (pred, receive_data)
}
repopulate_cached_proc_state_info - Recompute and repopulate the cached proc-state element information.
Fully populates the cached proc-state information in the query engines.
This repopulates the givens in PartialInfoQueryEngine and LazyTernaryQueryEngine.
Note
What follows was generated by the Gemini LLM. Not human verified.
RepopulateCachedProcStateInfoPass (repopulate_cached_proc_state_info) is
an analysis-refresh pass for Procs that recomputes inductive proc-state
invariants and updates the shared query engines cached in
OptimizationContext. It does not directly mutate the IR (always returning
false), but enables stronger downstream simplifications in passes that rely
on cached state-element facts.
How it Works:
-
Inductive State Range Analysis: The pass populates a
ProcStateRangeQueryEngine(base_qe) on the targetProc. This analysis examines the initial values andnext_valuetransitions of the proc's state elements to prove inductive value ranges and known-bit invariants onstate_readnodes across all proc ticks. -
Updating Cached Query Engines: Using
CachedStateElementQueryEngine::FromContext, the pass retrieves the sharedPartialInfoQueryEngineandLazyTernaryQueryEngineinstances for theProcfromOptimizationContextand invokesComputeWithStateInfo(base_qe)on each. This injects the newly proven state-element intervals and ternary bits as "givens" into those cached engines so subsequent passes (such asSelectSimplificationPass,SelectRangeSimplificationPass, andNarrowingPass) can exploit them without rerunningProcStateRangeQueryEngine.
Example (Enabling downstream simplification via cached state ranges):
// Proc whose state `cnt` starts at 0 and wraps within [0, 3]:
proc counter(cnt: bits[8], init={0}) {
one: bits[8] = literal(value=1)
inc: bits[8] = add(cnt, one)
three: bits[8] = literal(value=3)
wrap: bits[1] = ugt(cnt, three)
zero: bits[8] = literal(value=0)
next_cnt: bits[8] = sel(wrap, cases=[inc, zero])
next (next_cnt)
}
// After RepopulateCachedProcStateInfoPass populates the cached
// PartialInfoQueryEngine and LazyTernaryQueryEngine with the invariant
// cnt in [0, 3] (upper 6 bits known 0), downstream passes can fold `wrap`
// to 0 and narrow `cnt`.
resource_sharing - Resource Sharing
Note
What follows was generated by the Gemini LLM. Not human verified.
The ResourceSharingPass is a critical optimization pass in XLS that aims to
reduce hardware area by sharing common computational resources (e.g., adders,
multipliers) among different parts of the design. This is achieved by
identifying mutually exclusive operations—operations that are guaranteed not
to execute at the same time—and then transforming the IR to allow them to
share the same physical hardware resource through multiplexing.
The pass is configured with a ProfitabilityGuard enum, which determines the
heuristic used to select which sharing opportunities to exploit:
kInDegree: Prioritizes sharing based on the in-degree of nodes in a conceptual "folding graph." This heuristic favors nodes that are potential "destinations" for folding, especially those with more distinct "source" operations that can be multiplexed into them. This approach is often effective for asymmetric folding scenarios where one complex operation can subsume several simpler ones.kCliques: Selects sharing opportunities based on identifying cliques (groups of mutually exclusive operations) in the folding graph. This approach is particularly suitable for symmetric folding scenarios where multiple operations of similar complexity can all share a single resource.kRandom: Randomly selects a subset of potential folding actions. This is typically used for testing, fuzzing, or exploration purposes rather than for deterministic optimization.kAlways: Attempts to perform all possible resource sharing that is identified as legal. This is generally used for aggressive optimization benchmarking or during specific testing phases.
The core mechanism of ResourceSharingPass involves several stages:
-
Mutual Exclusion Analysis: *
ComputeMutualExclusionAnalysis: This is a central function that identifies pairs or groups of operations that are mutually exclusive. It builds a "mutual exclusivity relation" between nodes, proving that two operations are guaranteed not to be active simultaneously. * It leveragesNodeForwardDependencyAnalysisto trace dataflow dependencies andBddQueryEngine(Binary Decision Diagrams) for precise logical analysis. TheBddQueryEngineis critical for proving that a particular operation's value does not influence another under specific conditions (e.g., when a particular arm of aselectoperation is chosen). * The analysis primarily focuses onPrioritySelectoperations, as these explicitly define conditional execution paths, which naturally create clear mutual exclusivity between their cases. The analysis is conservative and avoids making assumptions throughInvokenodes before function inlining to ensure correctness. -
Folding Graph Construction: Based on the results of the mutual exclusivity analysis, a
FoldingGraphis constructed. This graph represents potential "folding actions," where a "source" operation can be "folded" into a "destination" operation, implying that they can share the same underlying hardware resource. This sharing is controlled by aselectoperation whose condition is derived from the mutual exclusivity proof. -
Profitability Estimation: * The pass utilizes
AreaEstimatorandDelayEstimatortools to assess the profitability of each potential folding action. This involves a cost-benefit analysis. *EstimateAreaForSelectingASingleInput: Calculates the area overhead associated with adding multiplexers (selectlogic) required to steer the inputs to a shared resource. *EstimateAreaForNegatingNode: Estimates the area cost if an operand needs to be negated (e.g., when folding asuboperation into anaddoperation that operates on the negated operand). * Thearea_savedfor a folding action is calculated as the estimated area of the "from" node minus the area overhead of the multiplexers and any additional required logic. *DelayAnalysisis used to consider the impact of sharing on the critical path delay. ThekMaxDelaySpreadconstant defines an acceptable limit for the increase in delay due to multiplexing. -
Selection of Folding Actions: *
SelectFoldingActions: This function, guided by the chosenProfitabilityGuardheuristic, selects a subset of the legal and profitable folding actions to perform. * It prioritizes actions that offer significant area savings while keeping delay impacts within acceptable bounds. * The selected actions are sorted (e.g., by descending area savings) and then "legalized" (LegalizeSequenceOfFolding) to prevent overlapping or conflicting transformations from being applied. -
IR Transformation: Once a final set of
NaryFoldingActions is selected, the IR is transformed to implement the sharing. This involves: * Creating newselectorpriority_selectoperations (or chains of them) to multiplex the inputs of the shared resource based on the conditions derived from the original mutual exclusivity. * Replacing the original "from" operations with the output of the newly created multiplexing structure, which then feeds into the "to" (shared) operation. * Removing the now redundant "from" operations.
Example:
Consider two umul operations, mul0(a, b) and mul1(c, d), which are
mutually exclusive (e.g., they are in different arms of a priority_select).
The ResourceSharingPass might identify this and transform the IR to use a
single shared umul hardware resource:
// Original IR snippet (simplified)
selector: bits[1] = ...
mul0: bits[32] = umul(a, b, width=32)
mul1: bits[32] = umul(c, d, width=32)
ret result: bits[32] = priority_sel(selector, cases=[mul0], default=mul1)
After ResourceSharingPass (conceptual representation, as actual IR is more
complex with explicit multiplexing):
// Optimized IR snippet (simplified)
selector: bits[1] = ...
// Multiplexed inputs to the shared multiplier
input_a_mux: bits[32] = priority_sel(selector, cases=[a], default=c)
input_b_mux: bits[32] = priority_sel(selector, cases=[b], default=d)
// Shared multiplier operation
umul_shared: bits[32] = umul(input_a_mux, input_b_mux, width=32)
ret result: bits[32] = umul_shared // The shared multiplier is now the result
This pass is vital for achieving high-quality hardware designs by efficiently utilizing available hardware resources, particularly in designs with significant conditional logic.
scheduling-opt - scheduling opt passes
Passes performed immediately before starting scheduling.
These optimizations are used to fix up any changes the mutual-exclusion pass & proc-state legalize performs before the initial scheduling.
TODO(allight): We might wish to move these into opt only. sched running optimization passes is an artifact of how these tools evolved which no longer makes too much sense. To do this will require making a decision on how to handle 'mutual-exclusion opt' however.
Options Set
Min opt level: 1
Invoked Passes
select_lifting - Select Lifting
Pass which replace the pattern v = sel (c, array[i], array[j], ...) where all cases of the select reference the same array, to the code z = sel (c, i, j, ...) v = array[z]
Note
What follows was generated by the Gemini LLM. Not human verified.
The SelectLiftingPass is an optimization pass in XLS that restructures
select and priority_select operations to improve hardware efficiency.
It identifies scenarios where a select's cases are all derived from a
common "shared" operation (such as an array_index or a binary arithmetic
operation) and "lifts" that shared operation out of the select. This
transformation effectively moves the multiplexing (the select) from the
output of the shared operation to its input, which often leads to
significant hardware savings and can sometimes improve performance.
This pass is particularly effective in two main scenarios:
-
Lifting
ArrayIndexOperations: When all cases of aselectarearray_indexoperations on the same array, the pass can lift thearray_indexout of theselect. It creates a newselectthat chooses between the indices of the originalarray_indexoperations. The result of this newselect(the chosen index) is then used in a single, sharedarray_indexoperation. This replaces multiple array reads followed by a wide data multiplexer with a smaller index multiplexer followed by a single array read, which is generally much more area-efficient.// Original IR snippet v = sel(c, array[i], array[j]) // Optimized IR (after lifting) z = sel(c, i, j) v = array[z] -
Lifting Binary Operations: When all cases of a
selectare binary operations of the same kind (e.g., alladds,subs, ormuls) and share one common operand, the binary operation can be lifted out of theselect. A newselectis created to choose between the "other" (non-shared) operands. The result of this newselectis then used in a single, shared binary operation with the common operand.// Original IR snippet v = sel(c, x + a, x + b) // Optimized IR (after lifting) z = sel(c, a, b) v = x + z
Profitability and Applicability Guards:
The pass includes several "guards" to ensure that the transformation is both applicable and profitable:
CanLiftSelect: This function checks if aselectis a candidate for lifting. ForArrayIndexlifting, it verifies that all cases are indeedarray_indexoperations on the same array and that their index types are compatible. For binary operation lifting, it identifies a commonshared_nodeacross all cases and ensures the operation type is consistent and supported (e.g.,add,sub,and,or,mul, shifts). It also handles "identity" cases, where one of theselect's cases is the shared operand itself.
ShouldLiftSelect: This function determines if a liftableselectshould actually be transformed, based on profitability heuristics: * Area Estimation: For binary operations, it performs a simple cost-benefit analysis based on the bit-widths of the original and transformed operations. The transformation is generally considered profitable if the total bit-width of the new, narrowerselectand the shared operation is less than or equal to the total bit-width of the originalselectand all the individual binary operations (if they were single-use). * Delay Estimation: If adelay_modelis provided, the pass usesCriticalPathDelayAnalysisto estimate the impact of the transformation on the critical path. Lifting is avoided if it is predicted to increase the latency. This is particularly important for scenarios like converting multiple constant-shifts into a single variable-shift, which is often more expensive in hardware. * Heuristics for High-Latency Operations: For high-latency operations like multiplication, lifting is more cautiously applied, especially if it involves identity cases, to avoid potentially degrading performance.
How it Works:
-
Worklist-based Iteration: The pass maintains a worklist of
selectandpriority_selectnodes that are candidates for optimization. It iterates through this worklist, applying transformations until no more profitable lifting opportunities can be found. -
Applicability and Profitability Checks: For each
selectin the worklist, it callsCanLiftSelectand thenShouldLiftSelectto determine if a valid and beneficial transformation exists. -
IR Transformation: If a transformation is approved: *
LiftSelectForArrayIndex: Rewires the IR forarray_indexlifting by creating a newselectfor the indices and a new sharedarray_index. *LiftSelectForBinaryOperation: Rewires the IR for binary operation lifting by creating a newselectfor the non-shared operands and a new shared binary operation. It correctly handles identity cases by inserting the appropriate identity literal (e.g.,0foradd,-1forand) into the newselect. -
Cleanup: The original
selectnode, now redundant, is marked for deletion, which is typically handled by a subsequentDeadCodeEliminationPass. Any newselectnodes created during the transformation are added to the worklist, allowing for potential further optimizations.
By systematically applying these transformations, SelectLiftingPass plays a
crucial role in optimizing multiplexer-heavy designs, leading to more
efficient use of hardware resources and improved overall performance.
select_merge - Select Merging
Note
What follows was generated by the Gemini LLM. Not human verified.
The SelectMergingPass merges consecutive OneHotSelect or PrioritySelect
operations in a FunctionBase into a single, larger select operation of the
same kind. Flattening cascades of single-use selects into a unified select
simplifies the IR and allows downstream passes (such as select
simplification) and hardware synthesis tools to optimize across all cases at
once.
How it Works:
The pass traverses the IR in topological order (TopoSort) and invokes
MergeSelectNode on each OneHotSelect and PrioritySelect node:
-
Merging
OneHotSelectOperations: * Pattern: An outerOneHotSelectwhere one or more cases are themselves single-useOneHotSelectnodes (users().size() == 1). * Transformation: Constructs a single mergedOneHotSelect: * Contiguous runs of unmerged cases have their corresponding selector slice extracted viabit_slice. * For each caseithat is a single-useOneHotSelect, bitiof the outer selector is extracted (bit_slice), sign-extended to the bit-width of the inner selector (sign_ext), and bitwiseand-ed with the inner selector. Its cases are spliced directly into the merged case list. * All selector pieces are concatenated (from MSB to LSB) viaCreateFlattenedConcat(so nestedConcattrees in selector pieces are flattened immediately) to form the new selector. -
Merging
PrioritySelectOperations: * Selector Inversion for 1-BitPrioritySelects: If a 1-bitPrioritySelecthas a single-usePrioritySelectascases[0]and itsdefault_valueis not a single-usePrioritySelect, the pass first negates the 1-bit selector (not) and swapscases[0]withdefault_value. Merging an innerPrioritySelectfrom thedefault_valueposition is simpler because its default value directly becomes the mergeddefault_valuewithout needing an explicitinner_selector == 0fallback condition. * Case Merging: For any caseithat is a single-usePrioritySelect, bitiof the outer selector is sign-extended andand-ed with the inner selector to guard the inner cases, followed by an additional case for the innerdefault_valueguarded byand(outer_selector[i], eq(inner_selector, 0)). * Default Value Merging: If the outerdefault_valueis a single-usePrioritySelect, its selector and cases are appended at the lowest-priority end of the mergedPrioritySelect, and itsdefault_valuebecomes the new outerdefault_value. * All selector pieces are concatenated viaCreateFlattenedConcatto form the merged selector.
Key Conditions for Merging:
- Single Use: An inner select is only merged if
users().size() == 1, preventing logic duplication. - Matching Select Types:
OneHotSelectnodes are only merged intoOneHotSelect, andPrioritySelectnodes are only merged intoPrioritySelect.
Example (OneHotSelect merging):
// Original IR snippet
fn f(p0: bits[2], p1: bits[2], x: bits[32], y: bits[32],
z: bits[32]) -> bits[32] {
one_hot_sel.1: bits[32] = one_hot_sel(p0, cases=[x, y])
ret one_hot_sel.2: bits[32] = one_hot_sel(p1, cases=[one_hot_sel.1, z])
}
Because one_hot_sel.1 has only one user (one_hot_sel.2),
SelectMergingPass merges them into a single 3-case one_hot_sel:
// Optimized IR
fn f(p0: bits[2], p1: bits[2], x: bits[32], y: bits[32],
z: bits[32]) -> bits[32] {
bit_slice.3: bits[1] = bit_slice(p1, start=0, width=1)
sign_ext.4: bits[2] = sign_ext(bit_slice.3, new_bit_count=2)
and.5: bits[2] = and(sign_ext.4, p0)
bit_slice.6: bits[1] = bit_slice(p1, start=1, width=1)
new_selector: bits[3] = concat(bit_slice.6, and.5)
ret one_hot_sel.7: bits[32] = one_hot_sel(new_selector, cases=[x, y, z])
}
select_range_simp - Select Range Simplification
Pass which simplifies selects and one-hot-selects. Example optimizations include removing dead arms and eliminating selects with constant selectors. Uses range analysis to determine possible values.
Note
What follows was generated by the Gemini LLM. Not human verified.
SelectRangeSimplificationPass (select_range_simp) runs the select
simplification suite (SelectSimplificationPassBase) with
with_range_analysis=true. Instead of LazyTernaryQueryEngine, it combines
StatelessQueryEngine with PartialInfoQueryEngine (wrapped in
CachedStateElementQueryEngine for Procs, plus BitProvenanceAnalysis
when SplitsEnabled) to reason over combined ternary and interval/range
information directly.
Enabling range analysis extends all SelectSimplificationPass optimizations
with interval-aware reasoning:
- Range-Proven Selector Constraints:
PartialInfoQueryEnginecan prove that selector bits are constant, mutually exclusive (AtMostOneBitTrue), exhaustive (AtLeastOneTrue/AtLeastOneBitTrue), or one-hot (ExactlyOneBitTrue) based on value intervals (such as bounded loop indices or arithmetic comparisons) that ternary analysis alone cannot resolve. This unlocks additional dead-arm pruning,PrioritySelectselector narrowing, mask conversion, and comparison hoisting. - Sign-Extension Width Squeezing (
TrySqueezeSelect): WhenSplitsEnabledandwith_range_analysis=true,TrySqueezeSelectqueriesPartialInfoQueryEngine::GetIntervalson each select arm and computesinterval_ops::MinimumSignedBitCountacross all cases. If all arms fit in a narrower signed bit-widthW, the select is narrowed toWbits and sign-extended (sign_ext) back to the original width.
select_simp - Select Simplification
Pass which simplifies selects and one-hot-selects. Example optimizations include removing dead arms and eliminating selects with constant selectors. Uses ternary analysis to determine possible values.
Note
What follows was generated by the Gemini LLM. Not human verified.
SelectSimplificationPass (select_simp) simplifies select,
one_hot_select, priority_select, and one_hot operations in a
FunctionBase by running SelectSimplificationPassBase with
with_range_analysis=false. It uses a UnionQueryEngine combining
StatelessQueryEngine and LazyTernaryQueryEngine (plus
BitProvenanceAnalysis when SplitsEnabled) to evaluate known bits and bit
provenance without the overhead of full interval/range analysis.
Key optimizations performed include:
- Hoisting Comparisons with Literals: Pushes comparisons (
CompareOp) against a literal through a single-useSelect,PrioritySelect, or 1-hotOneHotSelectwhen at most one arm is non-literal. - Constant and Known Selector Elimination: Replaces
Select,PrioritySelect, andOneHotSelectnodes when their selector bits uniquely determine the active case(s) or default value. - Three-Way Comparison Canonicalization: Rewrites nested 2-way
SelectandPrioritySelectthree-way comparisons (<and>) so the second comparison useseq. - Identical Arms & Selector Reordering: Folds selects with identical
arms, reduces identical-arm
OneHotSelects to a 1-bitSelectonselector != 0, and reordersSelectcases when the selector is a unary function of a narrower or equal-width base value. - Tuple Decomposition: Splits tuple-typed
Select,OneHotSelect, andPrioritySelectnodes into per-element selects bundled in aTuple. - Arm Commoning, Pruning, and Gate Lowering: Merges duplicate arms in
OneHotSelect(NarrowingEnabled) and adjacent duplicate arms inPrioritySelect(SimplifyPrioritySelectDuplicateCases), absorbs inverted 1-bit selectors (not), lowers 1-bit muxes with constant/selector arms intoand/or/notgates, converts single-nonzero-arm selects intoandmasks (SplitsEnabled), and prunes dead/zero arms. - Width Squeezing and Consecutive Select Collapsing: Slices off common
known constant or provenance-shared leading/trailing bits across select
arms (
SplitsEnabled), and collapses consecutive 2-waySelects that share a common case or selector. OneHotLowering and Bit-Based Select Splitting: ConvertsOneHotSelect(OneHot(x))intoPrioritySelect, simplifiesOneHoton 1-bit, mutually exclusive, or single-unknown-bit inputs, and splitsOneHotSelect/PrioritySelectnodes (<= 64 bits) along runs of shared vs. distinct bit sources (SplitsEnabled).
select_to_bitwise_ops - Select to Bitwise Ops
Converts a binary select whose two arms provably differ by a fully-known
XOR term (e.g. sel(p, [x, xor(x, c)])) into an XOR with an AND-masked
constant: xor(x, and(sign_ext(p, W), c)), with p complemented when the
XOR arm is the on-false case. The arms need not literally form
xor(base, c): per-piece xor-with-constant differences introduced by
earlier passes (e.g. concat_simp) are also recognized. This is the select
pattern generated by the per-step of an unrolled CRC/shift loop.
This pass is separate from select simplification (and runs at the very end of optimization) by design:
- The rewrite is value-based: it only fires when the query engine can prove the two arms differ by a fully-known constant, unlike the rest of select simplification which reasons about the shape of the select itself.
- It deliberately consumes shapes that
concat_simpproduces (wide xor limbs split into per-slice concats).concat_simpruns inside the fixed-point "simp" compound, and running this rewrite in the same fixed point would leave the two transforms repeatedly reshaping the same IR instead of converging. - It converts the select into an
and-masked xor, which value-based analyses reason through less easily, so it is deferred until after those analyses (e.g. conditional specialization) have already run.
Runs only at optimization levels where split-based rewrites are enabled (SplitsEnabled).
Note
What follows was generated by the Gemini LLM. Not human verified.
How it Works:
-
Eligibility (
GetBinaryMuxArms): The pass only runs whenoptions.splits_enabled()is true. It inspects eachSelectandPrioritySelectwith a 1-bit selector (p) and flat bit-vector type (W >= 1) in topological order, extracting its(on_false, on_true)arms (cases[0]andcases[1]forSelect, ordefault_valueandcases[0]forPrioritySelect). If either arm is already known to be all zeros or all ones (IsZeroOrOnes), the select is skipped so standard select simplification handles it. -
Direct and Recursive XOR Delta Matching: Using a
UnionQueryEnginecombiningStatelessQueryEngineandLazyTernaryQueryEngine, the pass attempts to prove that the two arms differ by a fully known constantdelta(on_true ^ on_false == delta): * Direct Match (MatchXorCase): Checks whether one arm is a binaryxor(base, c)(orxor(c, base)) wherebaseis the other arm andcis fully known (query_engine.IsFullyKnown(c)). * Recursive Structural Match (TryFoldXorDelta): Performs a memoized, depth-bounded (kMaxXorFoldDepth = 1000) structural walk over pairs of nodes(a, b)of equal bit-width: * Ifa == b, the XOR delta is0. * If bothaandbare fully known constants, the delta is*KnownValue(a) ^ *KnownValue(b). * Ifa(orb) is a binaryxorwith a fully known operandcand variable operandx, recurses on(x, b)(or(a, x)) and XORs the resulting delta withc. * Ifa(orb) isnot(x), recurses on(x, b)(or(a, x)) and bitwise-inverts the resulting delta. * If bothaandbareconcattrees whose flattened operands (FlattenConcats) have pairwise matching bit-widths, recurses on each operand pair and concatenates the piece deltas. -
Bitwise Lowering: Once a
basearm and a non-zerodelta(Bits) are determined (with conditioncond = pifbase == on_false, orcond = not(p)ifbase == on_true): * For 1-bit selects (W == 1),deltais1(on_true == not(on_false)), and the pass avoidssign_ext/andby emittingxor(on_false, p)directly (ornot(xor(on_true, p))whenon_falseis thenot/xornode andon_trueis the simpler base). * For wider selects (W > 1), the select is replaced withxor(base, sign_ext(cond, W))whendeltais all-ones, orxor(base, and(sign_ext(cond, W), literal(delta)))otherwise.
Example:
// Original IR
fn crc_step(p: bits[1], x: bits[8]) -> bits[8] {
poly: bits[8] = literal(value=0x07)
x_xor_poly: bits[8] = xor(x, poly)
ret sel.1: bits[8] = sel(p, cases=[x, x_xor_poly])
}
// Optimized IR
fn crc_step(p: bits[1], x: bits[8]) -> bits[8] {
mask: bits[8] = sign_ext(p, new_bit_count=8)
delta: bits[8] = literal(value=0x07)
masked_delta: bits[8] = and(mask, delta)
ret xor.2: bits[8] = xor(x, masked_delta)
}
simp - Simplification
Standard simplification pipeline.
This is run a large number of times and avoids many time-consuming analyses.
Invoked Passes
- ident_remove
- const_fold
- dce
- canon
- dce
- basic_simp
- dce
- arith_simp
- dce
- comparison_simp
- dce
- table_switch
- dce
- recv_default
- dce
- select_simp
- dce
- dataflow
- dce
- bitslice_simp
- dce
- concat_simp
- dce
- reassociation
- dce
- const_fold
- dce
- narrow(Ternary)
- dce
- bitslice_simp
- dce
- concat_simp
- dce
- array_untuple
- dce
- dataflow
- dce
- strength_red
- dce
- array_simp
- dce
- cse
- dce
- basic_simp
- dce
- arith_simp
- dce
- narrow(Ternary)
- dce
- bitwise_simp
- dce
- bool_simp
- dce
- token_simp
- dce
simp(2) - Max-2 Simplification
Standard simplification pipeline.
Opt level is capped at 2
Options Set
Cap opt level: 2
Invoked Passes
simp(3) - Max-3 Simplification
Standard simplification pipeline.
Opt level is capped at 3
Options Set
Cap opt level: 3
Invoked Passes
simp(>=1,<=2) - Min-1 Max-2 Simplification
Standard simplification pipeline.
Opt level is capped at 2 and skipped if less than 1
Options Set
Min opt level: 1
Cap opt level: 2
Invoked Passes
simplify-and-inline - Iteratively inline and simplify
Inlining segment of the pipeline
This is performed to fixedpoint and each run a single layer of the function hierarchy is inlined away.
Options Set
Run to a fixedpoint.
Invoked Passes
sparsify_select - Sparsify Select
The SparsifySelectPass is a type of range analysis-informed dead code elimination that removes cases from selects when range analysis proves that they can never occur. It does this by splitting a select into many selects, each of which covers a single interval from the selector interval set.
Note
What follows was generated by the Gemini LLM. Not human verified.
The SparsifySelectPass uses range analysis to eliminate unreachable cases
from select operations. When the set of possible values that a select's
selector can take covers fewer points than the number of cases in the
select, this pass replaces the original select with a smaller select
(or a chain of selects, one per reachable interval) that only indexes into
the reachable cases.
Here is a detailed breakdown of its operation:
-
Range Analysis: The pass populates a
PartialInfoQueryEngineand queriesGetIntervals(select->selector()).Get({})to obtain theIntervalSetof possible values for the selector of eachSelectnode. -
Sparsity Check: If the total number of values in the
IntervalSet(selector_intervals.Size()) is strictly less thanselect->cases().size(), then at least one case in theselectis provably unreachable. -
Splitting into Per-Interval Selects (
SparsifySelect): *IntervalsSortedBySizesorts the convex intervals inselector_intervalsfrom smallest to largest (breaking ties by interval order). * For each reachableInterval[lower, upper], the pass collects the corresponding slice of cases from the originalselect(usingselect->default_value()for indices>= select->cases().size(), or skipping the interval if it lies entirely past the end ofcases()and nodefault_valueis present). * It constructs an innerselectfor the interval:if_in_range = sel(sub(selector, lower), cases=cases_in_range, default=0). * For the first interval processed (is_leaf == true),if_in_rangeis used directly without a range-check comparator (if the selector falls in no other interval, it must fall in this leaf interval). * For each subsequent interval (is_leaf == false), the pass checks whetherselectorlies in[lower, upper]viaand(uge(selector, lower), ule(selector, upper))and wraps the previously constructed select chain (other) in a 2-wayselect:sel(in_bounds, cases=[other, if_in_range]).
Example:
Consider a select operation where the selector add.3 is a bits[4]
value proven by range analysis to lie in the single interval [8, 11]:
// Original IR snippet
fn func(x: bits[2]) -> bits[4] {
zero_ext.1: bits[4] = zero_ext(x, new_bit_count=4)
literal.2: bits[4] = literal(value=8)
add.3: bits[4] = add(zero_ext.1, literal.2)
// 16 cases (literal.4 through literal.19) for selector values 0..15:
ret sel.20: bits[4] = sel(add.3, cases=[
literal.4, literal.5, literal.6, literal.7, literal.8, literal.9,
literal.10, literal.11, literal.12, literal.13, literal.14,
literal.15, literal.16, literal.17, literal.18, literal.19
])
}
Because add.3 only takes values in [8, 11], SparsifySelectPass replaces
the 16-way sel.20 with a 4-case select offset by the interval lower bound
(8):
// Optimized IR snippet
fn func(x: bits[2]) -> bits[4] {
zero_ext.1: bits[4] = zero_ext(x, new_bit_count=4)
literal.2: bits[4] = literal(value=8)
add.3: bits[4] = add(zero_ext.1, literal.2)
lower_bound: bits[4] = literal(value=8)
offset: bits[4] = sub(add.3, lower_bound)
zero: bits[4] = literal(value=0)
ret sel.21: bits[4] = sel(offset,
cases=[literal.12, literal.13, literal.14, literal.15],
default=zero)
}
If the selector's IntervalSet contains multiple disjoint intervals, the
first (smallest) interval forms the leaf select, and each subsequent
interval wraps it in sel(and(uge(selector, lower), ule(selector, upper)),
cases=[previous_chain, interval_select]).
strength_red - Strength Reduction
Replaces operations with equivalent cheaper operations. For example, an add with no possible carries may be replaced with a bitwise OR.
Note
What follows was generated by the Gemini LLM. Not human verified.
The StrengthReductionPass is an optimization pass in XLS that improves
hardware efficiency by replacing computationally expensive operations with
equivalent, cheaper primitives. This reduces the area, critical-path delay,
and power consumption of the generated hardware by leveraging known constant
operands and bit-level value properties.
The pass traverses the IR in topological order and queries a
UnionQueryEngine combining StatelessQueryEngine and a context-cached
PartialInfoQueryEngine (wrapped in CachedStateElementQueryEngine) to
inspect known bits, leading/trailing zeros, and sign bits.
Key strength reductions performed by this pass include:
-
Replacement of Fully Known Nodes with Literals (
NarrowingEnabled): If theQueryEngineproves that a non-literal node with at least one user always evaluates to a constant value, it is replaced with aliteralnode. -
Sinking Operations into
Selects: If a non-side-effecting, non-invokeoperation has an operand that is asel(Select) whose cases (and default, if present) are all known constants, the operation is sunk into theselcases whenever: * All other operands of the operation are also known constants, or * Theselfeeds the index, start offset, selector, or shift amount of an operation that simplifies when that operand is constant (1Darray_index,array_slice,bit_slice_update,dynamic_bit_slice,sel,priority_sel,shll,shra,shrl), provided doing so does not widen theselvia a cheap widening op (array,array_concat,concat,sign_ext,tuple,zero_ext).// Original IR v1: bits[32] = sel(selector, cases=[const1, const2]) v2: bits[32] = add(v1, const3) // Optimized IR v1_c1: bits[32] = add(const1, const3) v1_c2: bits[32] = add(const2, const3) v2: bits[32] = sel(selector, cases=[v1_c1, v1_c2]) -
Additions (
add): * Addition with Zero:add(x, 0)oradd(0, x)is replaced withx. * Addition to Bitwise OR (No Carry): If at every bit positioni, at least one operand is known to be0, no carry can be generated andadd(a, b)is replaced withor(a, b). * Adding a Value to Itself:add(a, a)is replaced withconcat(bit_slice(a, start=0, width=W-1), 0:bits[1]), which shifts left by 1 bit with zero logic delay. * Narrowing Low Known-Zero Bits (SplitsEnabled): If either operand hask > 0known trailing zeros, only the upperW - kbits are added and concatenated with the lowerkbits of the other operand. * Splitting Adders at Non-Propagating Carries (SplitsEnabled): If both operands are known to be0at biti(i < W - 1), a carry cannot propagate past biti. The adder is split at biti + 1into smaller independent adders whose results are concatenated. -
Subtractions (
sub): * Subtraction of Zero:sub(x, 0)is replaced withx. * Subtracting from All-Ones:sub(all_ones, x)is replaced withnot(x). * Narrowing Low Known Bits (SplitsEnabled): If the LHS haskknown trailing ones (more than the RHS's known trailing zeros), only the upperW - kbits are subtracted and concatenated withnot(bit_slice(rhs, start=0, width=k)). Otherwise, if the RHS hask > 0known trailing zeros, only the upperW - kbits are subtracted and concatenated withbit_slice(lhs, start=0, width=k). * Splitting Subtractors at Non-Propagating Borrows (SplitsEnabled): If at biti(i < W - 1) the LHS bit is known1and the RHS bit is known0, a borrow cannot propagate past biti, so the subtractor is split at biti + 1into smaller independent subtractors concatenated together. -
Bitwise AND with a Contiguous Mask (
and) (NarrowingEnabled): A binaryand(x, mask)wheremaskis known to have a single contiguous run of set bits (e.g.,0b001110) is replaced withconcat(0, bit_slice(x, start=trailing_zeros, width=selected_bits), 0). -
Single-Bit
SelectExpansion and Sign-Extension Detection: * Exploding 1-Bit Muxes (SplitsEnabled): A 1-bitselwith a 1-bit selectorswhere at least one branch is a literal or equalssis expanded intoor(and(s, on_true), and(not(s), on_false)). *SelecttoSignExt: Aselwith a 1-bit selector that chooses between all-zeros and all-ones is replaced withsign_ext(s)(orsign_ext(not(s))if inverted). -
SignExttoZeroExt: If the MSB of the operand ofsign_ext(x)is known to be0, the operation is replaced withzero_ext(x). -
GateSimplification: * Ifconditionis known1,gate(cond, data)is replaced withdata. * Ifconditionis known0ordatais known all-zeros, thegateis replaced with a zeroliteral. -
Single-Bit
Add/Neand Small Comparisons: * 1-bitadd(x, y)andne(x, y)are replaced withxor(x, y). * WhenNarrowingEnabled, unsigned comparisons against a power-of-two constant (uge(x, 2^k)andult(x, 2^k)) are strength-reduced to comparing the upperW - kbits (bit_slice(x, start=k, width=W-k)) against0usingneoreq. * WhenNarrowingEnabled, a 2-bit equality check against zero (eq(x, 0b00)) is replaced withnot(or(bit_slice(x, 0, 1), bit_slice(x, 1, 1))). -
Expensive Arithmetic with a Single Unknown Bit (
NarrowingEnabled): Forsmul,umul,sdiv,udiv,smod, andumodwhere across both operands only a single bit is unknown (all other bits are known constants), the pass evaluates the operation for both possible values of that bit usingInterpretNodeand replaces the arithmetic op with aseldriven by aneqcomparison of the operand containing the unknown bit against one of its two constant completions.
table_switch - Table switch conversion
TableSwitchPass converts chains of Select/PrioritySelect nodes into
ArrayIndex ops. These chains have the form:
sel.(N)(eq.X, literal.A, literal.B)
sel.(N+1)(eq.Y, sel.(N), literal.C)
sel.(N+2)(eq.Z, sel.(N+1), literal.D)
And so on. In these chains, eq.X, eq.Y, and eq.Z must all be eq or ne
comparisons of the same value against constant keys.
Current limitations:
- Chains must contain at least 3 links.
- Keys must fit in uint64_t, and matched values (plus the final
fall-through value if the index space is not fully covered) must be
literals.
- Matched keys must cover either the entire index space or more than half
of [0, min(2^width, max_key + 2)).
- Select ops must be binary, and PrioritySelect selectors must be 1-bit
or a Concat of 1-bit selectors.
Note
What follows was generated by the Gemini LLM. Not human verified.
The TableSwitchPass is an optimization pass in XLS that transforms cascaded
chains of sel and priority_sel nodes into direct array_index table
lookups on an array literal. Replacing a chain of conditional branches
comparing a common index against constant keys with a single constant-array
lookup simplifies control logic and improves hardware area and delay.
How it Works:
-
Chain Matching (
MatchLinks): * The pass traverses nodes in reverse topological order (Use-before-Def, viacontext.ReverseTopoSort(f)) and records interior links in atransformedset so it matches outermost lookup-chain roots first and skips interior links already folded into an outer table. It uses aStatelessQueryEngineto resolve constantuint64_tkeys. * Each link in the chain is either: * A binaryselor 1-bitpriority_selwhose selector compares a commonindexnode against a constantuint64_tkeyusingeqorne, selecting aliteralvalue on match and forwarding to thenextnode on mismatch, or * A multi-casepriority_selwhose selector is aconcatof 1-biteq/necomparisons against the sameindexnode (withneonly permitted on the final case), which contributes multiple consecutive links to the chain. If only a suffix of apriority_sel's cases starts the chain (atfirst_case > 0), the prefix cases are preserved in a truncatedpriority_selwhose default value becomes the newarray_index. * Chains with 2 or fewer links (links.size() <= 2) are skipped as too short to benefit from table conversion. -
Table Construction (
LinksToTable): * The pass walks the chain from outermost to innermost link, recording the firstLiteralvalue associated with eachuint64_tkey (later duplicate keys in the chain are unreachable and ignored). * Full Index Space Coverage: If the index width is< 63bits and the matched keys cover all2^widthpossible index values, the final fall-through (else) value is dead and need not be a literal; the pass emits an array literal of size2^width. * Partial / Sparse Coverage with Saturation: Otherwise, the final fall-through node must be aLiteral(else_value). Leveraging XLSarray_indexout-of-bounds saturation semantics (where any index>= size - 1clamps to the last element), the pass bounds the table size tomin(2^width, max_key + 2). If more than half of the entries in[0, table_size)are explicitly matched (map.size() * 2 > table_size), any missing indices (gaps) and the saturating final slot are filled withelse_value. -
Replacement: The pass creates a
literalarray containing the table entries and replaces the root of the chain witharray_index(array_literal, indices=[index]).
Example:
// Original IR
fn main(index: bits[32]) -> bits[32] {
literal.0: bits[32] = literal(value=0)
literal.1: bits[32] = literal(value=1)
literal.2: bits[32] = literal(value=2)
literal.10: bits[32] = literal(value=10)
literal.20: bits[32] = literal(value=20)
literal.30: bits[32] = literal(value=30)
literal.99: bits[32] = literal(value=99)
eq.4: bits[1] = eq(index, literal.0)
eq.5: bits[1] = eq(index, literal.1)
eq.6: bits[1] = eq(index, literal.2)
sel.7: bits[32] = sel(eq.4, cases=[literal.99, literal.10])
sel.8: bits[32] = sel(eq.5, cases=[sel.7, literal.20])
ret sel.9: bits[32] = sel(eq.6, cases=[sel.8, literal.30])
}
// Optimized IR (after dead code elimination)
fn main(index: bits[32]) -> bits[32] {
array_literal: bits[32][4] = literal(value=[10, 20, 30, 99])
ret array_index.10: bits[32] = array_index(array_literal, indices=[index])
}
token_dependency - Convert data dependencies between effectful operations into token dependencies
Pass which turns data dependencies between certain effectful operations into token dependencies. In particular, transitive data dependencies between receives and other effectful ops are turned into token dependencies whenever no such token dependency already exists.
Note
What follows was generated by the Gemini LLM. Not human verified.
The TokenDependencyPass ensures that ordering constraints implied by data
dependencies between receive operations and downstream side-effecting
token-consuming operations (such as send, receive, or assert) are
explicitly captured in the token dependency graph.
For example, if a send operation consumes a value derived from a receive
operation's payload, but subsequent algebraic optimizations prove that the
expression is independent of the received value (e.g., multiplied by zero or
masked off), later passes could eliminate the data dependency. Without an
explicit token path from the receive to the send, the scheduler could
reorder the two I/O operations and violate program semantics.
How it Works:
- Token Provenance & Transitive Closure: The pass runs
TokenProvenanceAnalysison theFunctionBaseto build the direct token dependency graph over side-effecting operations andafter_allnodes, and computes itsTransitiveClosure. - Data Dependency Search: For each
receiveoperationa, the pass performs a depth-first search over the data dependency graph to find all downstream side-effecting token operationsbthat are not already reachable fromain the token transitive closure. - Transitive Pruning: If operation
cis token-dependent on operationb, and bothbandcare data-dependent onreceivea, the pass prunesafromc's required set (minimal_io_to_data_supplying_io), since adding a token edge fromatobtransitively ordersabeforec. - Token Rewiring: For each remaining pair
(io, supplying_receive), the pass extracts the token output ofsupplying_receiveviatuple_index(supplying_receive, index=0)and combines it withio's existing token operand using a newafter_allnode.
Example:
// Original IR
chan test_channel(
bits[32], id=0, kind=streaming, ops=send_receive,
flow_control=ready_valid)
top proc main(__state: (), init={()}) {
__token: token = literal(value=token, id=1000)
receive.1: (token, bits[32]) = receive(__token, channel=test_channel)
tuple_index.2: token = tuple_index(receive.1, index=0)
tuple_index.3: bits[32] = tuple_index(receive.1, index=1)
send.4: token = send(__token, tuple_index.3, channel=test_channel)
after_all.5: token = after_all(send.4, tuple_index.2)
tuple.6: () = tuple()
next (tuple.6)
}
// Optimized IR
top proc main(__state: (), init={()}) {
__token: token = literal(value=token, id=1000)
receive.1: (token, bits[32]) = receive(__token, channel=test_channel)
tuple_index.2: token = tuple_index(receive.1, index=0)
tuple_index.3: bits[32] = tuple_index(receive.1, index=1)
tuple_index.7: token = tuple_index(receive.1, index=0)
after_all.8: token = after_all(tuple_index.7, __token)
send.4: token = send(after_all.8, tuple_index.3, channel=test_channel)
after_all.5: token = after_all(send.4, tuple_index.2)
tuple.6: () = tuple()
next (tuple.6)
}
token_simp - Simplify token networks
Pass that simplifies token networks. For example, if an AfterAll node has operands where one operand is an ancestor of another in the token graph, then the ancestor can be omitted. Similarly, duplicate operands can be removed and AfterAlls with one operand can be replaced with their operand.
Note
What follows was generated by the Gemini LLM. Not human verified.
The TokenSimplificationPass simplifies the token dependency network within
a function or proc. Token networks enforce ordering constraints between
side-effecting operations (such as send, receive, and assert). By
removing redundant token edges and canonicalizing min_delay annotations,
this pass reduces control complexity and simplifies downstream scheduling.
If any node in the FunctionBase has a type containing more than one token
(e.g., a tuple containing multiple tokens), the pass conservatively bails out
without modifying the IR.
Otherwise, the pass executes a sequence of subpasses on after_all and
min_delay operations:
-
Simplifying
min_delayOperations: * Trivialmin_delay: Amin_delay(tok, delay=0)is replaced withtok. Similarly,min_delay(after_all(), delay=X)on an emptyafter_all()is replaced withafter_all().``` // Original IR min_delay.1: token = min_delay(tok, delay=0) // Optimized IR // Uses of min_delay.1 are replaced directly with tok. ```* Collapsing Nested
min_delays: Consecutivemin_delayoperations are merged by summing their delays:min_delay(min_delay(tok, delay=1), delay=2)becomesmin_delay(tok, delay=3).``` // Original IR min_delay.1: token = min_delay(tok, delay=1) min_delay.2: token = min_delay(min_delay.1, delay=2) // Optimized IR min_delay.3: token = min_delay(tok, delay=3) ```* Pushing
min_delayDown Throughafter_all: If all operands of a non-emptyafter_allaremin_delaynodes with positive delays, the minimum common delayd_minis factored out after theafter_all, leaving residualmin_delay(..., delay=d - d_min)nodes only for operands withd > d_min.``` // Original IR min_delay.1: token = min_delay(tok_a, delay=1) min_delay.2: token = min_delay(tok_b, delay=3) after_all.3: token = after_all(min_delay.1, min_delay.2) // Optimized IR min_delay.4: token = min_delay(tok_b, delay=2) after_all.5: token = after_all(tok_a, min_delay.4) min_delay.6: token = min_delay(after_all.5, delay=1) ``` -
Simplifying
after_allOperations: * Collapsing Nestedafter_alls: In reverse topological order, if anafter_allnode has no implicit uses and all of its users are alsoafter_allnodes, its operands are flattened directly into each userafter_all.``` // Original IR after_all.1: token = after_all(tok_a, tok_b) after_all.2: token = after_all(after_all.1, tok_c) // Optimized IR after_all.3: token = after_all(tok_c, tok_a, tok_b) ```* Pruning Overlapping (Ancestor)
after_allOperands: If anafter_allhas operandsxandywherextransitively depends onythrough token-carrying nodes (conservatively stopping atinvokenodes so the pass is safe before function inlining, and bounding traversal by topological index),yis redundant and replaced by another operand of theafter_all. * Deduplicating Operands: Duplicate operands in anafter_allare removed (with remaining unique operands sorted by node ID). * Single-Operandafter_all: Anafter_all(tok)with a single operand is replaced directly withtok.``` // Original IR send.2: token = send(tok, data, channel=ch) send.3: token = send(send.2, data, channel=ch) after_all.4: token = after_all(tok, send.2, send.3) // Optimized IR // tok and send.2 are ancestors of send.3; after pruning, // deduplication, and single-operand removal, after_all.4 is // replaced directly with send.3. ```
If any simplification modifies the IR, CollapseMinDelay is run one final
time to merge any min_delay operations that became adjacent after
after_all removal.
useless_assert_remove - Remove useless (always true) asserts
Pass which removes asserts that have a literal 1 as the condition, meaning they are never triggered. Rewires tokens to ensure nothing breaks.
Note
What follows was generated by the Gemini LLM. Not human verified.
The UselessAssertRemovalPass eliminates assert operations whose condition
is statically known to be true (1), since such assertions can never fail
at runtime or in simulation.
How it Works:
- Condition Analysis: The pass traverses the IR in topological order
and queries a
StatelessQueryEngine(KnownValueAsBits) on eachassertnode'sconditionoperand. - Token Rewiring and Removal: If the
conditionis known to be1(IsOne()), all uses of theassertnode's output token are replaced directly with theassert's inputtokenoperand, and theassertnode is removed from theFunctionBase.
Example:
// Original IR
fn f(tkn: token) -> token {
literal.1: bits[1] = literal(value=1)
ret assert.2: token = assert(tkn, literal.1, message="always passes")
}
// Optimized IR
fn f(tkn: token) -> token {
ret tkn
}
useless_io_remove - Remove useless send/receive
Pass which removes sends/receives that have literal false as their condition. Also removes the condition from sends/receives that have literal true as their condition.
Note
What follows was generated by the Gemini LLM. Not human verified.
The UselessIORemovalPass simplifies predicated send and receive
operations across all procs in a Package when their predicate operand is
statically known to be 0 (false) or 1 (true) according to a
StatelessQueryEngine.
First, the pass builds a package-wide map (ComputeChannelMaps) tracking
all send and receive operations associated with each ChannelRef. It
then traverses each proc in topological order and applies the following
transformations to predicated I/O nodes:
-
Removal or Simplification of False-Predicated I/O (
predicate == 0): *sendwithpredicate == 0: * If there is at least one othersendremaining on the same channel, the disabledsendis removed and its uses are replaced with its inputtokenoperand. * If it is the lastsendon that channel, removing it would leave the channel without a sender. Instead, thesendis kept and itsdataoperand is replaced with a zero literal (ZeroOfType) so dead upstream data computation can be removed. *receivewithpredicate == 0: * If there is at least one otherreceiveremaining on the same channel, the disabledreceiveis removed and replaced with atuplecontaining(token, zero_data)for blocking receives, or(token, zero_data, 0)(with a0valid bit) for non-blocking receives.// Original IR (assuming another send exists on my_chan) literal.1: bits[1] = literal(value=0) send.2: token = send(tkn, data, predicate=literal.1, channel=my_chan) // Optimized IR // Uses of send.2 are replaced directly with tkn. -
Simplification of True-Predicated I/O (
predicate == 1): If asendorreceivehas a predicate known to be1, the redundantpredicateoperand is stripped, converting the operation into an unpredicatedsendorreceiveon the same channel.// Original IR literal.1: bits[1] = literal(value=1) receive.2: (token, bits[32]) = receive(tkn, predicate=literal.1, channel=my_chan) // Optimized IR receive.3: (token, bits[32]) = receive(tkn, channel=my_chan)