package util
The util package provides extensions to core chisel for common hardware components and utility functions
- Source
- util.scala
- Alphabetic
- By Inheritance
- util
- AnyRef
- Any
- Hide All
- Show All
- Public
- Protected
Type Members
- class Arbiter[T <: Data] extends Module
Hardware module that is used to sequence n producers into 1 consumer.
Hardware module that is used to sequence n producers into 1 consumer. Priority is given to lower producer.
val arb = Module(new Arbiter(UInt(), 2)) arb.io.in(0) <> producer0.io.out arb.io.in(1) <> producer1.io.out consumer.io.in <> arb.io.out
Example: - class ArbiterIO[T <: Data] extends Bundle
IO bundle definition for an Arbiter, which takes some number of ready-valid inputs and outputs (selects) at most one.
- case class BinaryMemoryFile(path: String) extends MemoryFile with Product with Serializable
A binary memory file to preload an SRAM with, represented by a filesystem path.
A binary memory file to preload an SRAM with, represented by a filesystem path. This will annotate the inner SyncReadMem with
loadMemoryFromFile
usingMemoryLoadFileType.Binary
as the file type.- path
The path to the binary file
- sealed class BitPat extends BitSet with SourceInfoDoc
Bit patterns are literals with masks, used to represent values with don't care bits.
Bit patterns are literals with masks, used to represent values with don't care bits. Equality comparisons will ignore don't care bits.
"b10101".U === BitPat("b101??") // evaluates to true.B "b10111".U === BitPat("b101??") // evaluates to true.B "b10001".U === BitPat("b101??") // evaluates to false.B
Example: - class Counter extends AffectsChiselPrefix
Used to generate an inline (logic directly in the containing Module, no internal Module is created) hardware counter.
Used to generate an inline (logic directly in the containing Module, no internal Module is created) hardware counter.
Typically instantiated with apply methods in object Counter
Does not create a new Chisel Module
val countOn = true.B // increment counter every clock cycle val (counterValue, counterWrap) = Counter(countOn, 4) when (counterValue === 3.U) { ... }
, // Using Scala Range API val (counterValue, counterWrap) = Counter(0 until 10 by 2) when (counterValue === 4.U) { ... }
Examples: - class DecoupledIO[+T <: Data] extends ReadyValidIO[T]
A concrete subclass of ReadyValidIO signaling that the user expects a "decoupled" interface: 'valid' indicates that the producer has put valid data in 'bits', and 'ready' indicates that the consumer is ready to accept the data this cycle.
A concrete subclass of ReadyValidIO signaling that the user expects a "decoupled" interface: 'valid' indicates that the producer has put valid data in 'bits', and 'ready' indicates that the consumer is ready to accept the data this cycle. No requirements are placed on the signaling of ready or valid.
- trait Enum extends AnyRef
Defines a set of unique UInt constants
Defines a set of unique UInt constants
Unpack with a list to specify an enumeration. Usually used with switch to describe a finite state machine.
val state_on :: state_off :: Nil = Enum(2) val current_state = WireDefault(state_off) switch (current_state) { is (state_on) { ... } is (state_off) { ... } }
Example: - trait HasBlackBoxInline extends BlackBox
- trait HasBlackBoxPath extends BlackBox
- trait HasBlackBoxResource extends BlackBox
- trait HasExtModuleInline extends ExtModule
- trait HasExtModulePath extends ExtModule
- trait HasExtModuleResource extends ExtModule
- case class HexMemoryFile(path: String) extends MemoryFile with Product with Serializable
A hex memory file to preload an SRAM with, represented by a filesystem path.
A hex memory file to preload an SRAM with, represented by a filesystem path. This will annotate the inner SyncReadMem with
loadMemoryFromFile
usingMemoryLoadFileType.Hex
as the file type.- path
The path to the hex file
- class IrrevocableIO[+T <: Data] extends ReadyValidIO[T]
A concrete subclass of ReadyValidIO that promises to not change the value of 'bits' after a cycle where 'valid' is high and 'ready' is low.
A concrete subclass of ReadyValidIO that promises to not change the value of 'bits' after a cycle where 'valid' is high and 'ready' is low. Additionally, once 'valid' is raised it will never be lowered until after 'ready' has also been raised.
- class LockingArbiter[T <: Data] extends LockingArbiterLike[T]
- abstract class LockingArbiterLike[T <: Data] extends Module
- class LockingRRArbiter[T <: Data] extends LockingArbiterLike[T]
- sealed abstract class MemoryFile extends AnyRef
A memory file with which to preload an SRAM
A memory file with which to preload an SRAM
See concrete subclasses BinaryMemoryFile and HexMemoryFile
- class MemoryReadPort[T <: Data] extends Bundle
A bundle of signals representing a memory read port.
- class MemoryReadWritePort[T <: Data] extends Bundle
A bundle of signals representing a memory read/write port.
A bundle of signals representing a memory read/write port.
- Note
masked
is only valid if tpe is a Vec; if this is not the case no mask will be initialized regardless of the value ofmasked
.
- class MemoryWritePort[T <: Data] extends Bundle
A bundle of signals representing a memory write port.
A bundle of signals representing a memory write port.
- Note
masked
is only valid if tpe is a Vec; if this is not the case no mask will be initialized regardless of the value ofmasked
.
- final class MixedVec[T <: Data] extends Record with IndexedSeq[T]
A hardware array of elements that can hold values of different types/widths, unlike Vec which can only hold elements of the same type/width.
A hardware array of elements that can hold values of different types/widths, unlike Vec which can only hold elements of the same type/width.
val v = Wire(MixedVec(Seq(UInt(8.W), UInt(16.W), UInt(32.W)))) v(0) := 100.U(8.W) v(1) := 10000.U(16.W) v(2) := 101.U(32.W)
Example: - class Pipe[T <: Data] extends Module
Pipeline module generator parameterized by data type and latency.
Pipeline module generator parameterized by data type and latency.
This defines a module with one input,
enq
, and one output,deq
. The input and output are Valid interfaces that wrap some Chisel type, e.g., a UInt or a Bundle. This generator will then chain together a number of pipeline stages that all advance when the input Validenq
fires. The outputdeq
Valid will fire only when valid data has made it all the way through the pipeline.As an example, to construct a 4-stage pipe of 8-bit UInts and connect it to a producer and consumer, you can use the following:
val foo = Module(new Pipe(UInt(8.W)), 4) pipe.io.enq := producer.io consumer.io := pipe.io.deq
If you already have the Valid input or the components of a Valid interface, it may be simpler to use the Pipe factory companion object. This, which Pipe internally utilizes, will automatically connect the input for you.
- See also
Pipe factory for an alternative API
Valid interface
Queue and the Queue factory for actual queues
The ShiftRegister factory to generate a pipe without a Valid interface
- class Queue[T <: Data] extends Module
A hardware module implementing a Queue
A hardware module implementing a Queue
val q = Module(new Queue(UInt(), 16)) q.io.enq <> producer.io.out consumer.io.in <> q.io.deq
Example: - class QueueIO[T <: Data] extends Bundle
An I/O Bundle for Queues
- class RRArbiter[T <: Data] extends LockingRRArbiter[T]
Hardware module that is used to sequence n producers into 1 consumer.
Hardware module that is used to sequence n producers into 1 consumer. Producers are chosen in round robin order.
val arb = Module(new RRArbiter(UInt(), 2)) arb.io.in(0) <> producer0.io.out arb.io.in(1) <> producer1.io.out consumer.io.in <> arb.io.out
Example: - abstract class ReadyValidIO[+T <: Data] extends Bundle
An I/O Bundle containing 'valid' and 'ready' signals that handshake the transfer of data stored in the 'bits' subfield.
An I/O Bundle containing 'valid' and 'ready' signals that handshake the transfer of data stored in the 'bits' subfield. The base protocol implied by the directionality is that the producer uses the interface as-is (outputs bits) while the consumer uses the flipped interface (inputs bits). The actual semantics of ready/valid are enforced via the use of concrete subclasses.
- class SRAMInterface[T <: Data] extends Bundle
A IO bundle of signals connecting to the ports of a wrapped
SyncReadMem
, as requested bySRAMInterface.apply
. - class SparseVec[A <: Data] extends Record
A sparse vector.
A sparse vector. Under the hood, this is a Record that can be dynamically indexed as if it were a dense Vec.
SparseVec has the usual trappings of a Vec. It has a
size
and agen
type. However, it also has anindices
argument. This indicates the indices at which the SparseVec is allowed to have data. Additionally, the behavior of a SparseVec around what happens if a value is read from a value not in theindices
:-
defaultValue
sets the default value that is read from an index between the zeroth index and the largest value inindices
that is not in theindices
. -outOfBoundsValue
sets the behavior when reading a value larger than the largest value inindices
.The reason for this configurability is to enable exact compatibility with an equivalent dense Vec of the same size and initialized to a given value. Specifically, use SparseVec.DefaultValueBehavior.DynamicIndexEquivalent and SparseVec.OutOfBoundsBehavior.First to make this behave as such:
1. The SparseVec has a default value of how a FIRRTL compiler compiles DontCare for a dynamic index.
2. The SparseVec out-of-bounds behavior returns the zeroth element if a zeroth element exists. Otherwise, it returns a DontCare.
Note that this DontCare is likely not a true "don't care" that will be optimized to any value. Instead, it is a value equal to how a FIRRTL compiler chooses to optimize a dynamic index into a wire vector initialized with a DontCare. This has historically been zero.
Once created, a SparseVec can be written or read from as a Record. It may also be read from using a dynamic index, but not written to. Neither the default value nor the out-of-bounds value may be written to. The dynamic index type is conifgurable and may be one of:
- SparseVec.Lookup.Binary to convert the SparseVec index into a binary index into a dense vector. - SparseVec.Lookup.OneHot to convert the SparseVec index into a one-hot encoded index into a dense vector using Mux1H. - SparseVec.Lookup.IfElse to use a sequence of when statements.
A SparseVec will take up storage equal to the size of the provided mapping argument with one additional slot for the default value, if one is needed.
- class SwitchContext[T <: Element] extends AnyRef
Implementation details for switch.
- class Valid[+T <: Data] extends Bundle
A Bundle that adds a
valid
bit to some data.A Bundle that adds a
valid
bit to some data. This indicates that the user expects a "valid" interface between a producer and a consumer. Here, the producer asserts thevalid
bit when data on thebits
line contains valid data. This differs from DecoupledIO or IrrevocableIO as there is noready
line that the consumer can use to put back pressure on the producer.In most scenarios, the
Valid
class will not be used directly. Instead, users will createValid
interfaces using the Valid factory.- T
the type of the data
- See also
Valid factory for concrete examples
- type ValidIO[+T <: Data] = Valid[T]
Synonyms, moved from main package object - maintain scope.
Value Members
- val DecoupledIO: Decoupled.type
- val ValidIO: Valid.type
- object BinaryToGray
- object BitPat
- object Cat
Concatenates elements of the input, in order, together.
Concatenates elements of the input, in order, together.
Cat("b101".U, "b11".U) // equivalent to "b101 11".U Cat(myUIntWire0, myUIntWire1) Cat(Seq("b101".U, "b11".U)) // equivalent to "b101 11".U Cat(mySeqOfBits)
Example: - object Counter
- object Decoupled
This factory adds a decoupled handshaking protocol to a data bundle.
- object DeqIO
Consumer - drives (outputs) ready, inputs valid and bits.
- object EnqIO
Producer - drives (outputs) valid and bits, inputs ready.
- object Enum extends Enum
- object Fill
Create repetitions of the input using a tree fanout topology.
Create repetitions of the input using a tree fanout topology.
Fill(2, "b1000".U) // equivalent to "b1000 1000".U Fill(2, "b1001".U) // equivalent to "b1001 1001".U Fill(2, myUIntWire) // dynamic fill
Example: - object FillInterleaved
Creates repetitions of each bit of the input in order.
Creates repetitions of each bit of the input in order.
FillInterleaved(2, "b1 0 0 0".U) // equivalent to "b11 00 00 00".U FillInterleaved(2, "b1 0 0 1".U) // equivalent to "b11 00 00 11".U FillInterleaved(2, myUIntWire) // dynamic interleaved fill FillInterleaved(2, Seq(false.B, false.B, false.B, true.B)) // equivalent to "b11 00 00 00".U FillInterleaved(2, Seq(true.B, false.B, false.B, true.B)) // equivalent to "b11 00 00 11".U
Example: - object GrayToBinary
- object ImplicitConversions
Implicit conversions to automatically convert scala.Boolean and scala.Int to Bool and UInt respectively
- object Irrevocable
Factory adds an irrevocable handshaking protocol to a data bundle.
- object ListLookup
For each element in a list, muxes (looks up) between cases (one per list element) based on a common address.
For each element in a list, muxes (looks up) between cases (one per list element) based on a common address.
ListLookup(2.U, // address for comparison List(10.U, 11.U, 12.U), // default "row" if none of the following cases match Array(BitPat(2.U) -> List(20.U, 21.U, 22.U), // this "row" hardware-selected based off address 2.U BitPat(3.U) -> List(30.U, 31.U, 32.U)) ) // hardware-evaluates to List(20.U, 21.U, 22.U) // Note: if given address 0.U, the above would hardware evaluate to List(10.U, 11.U, 12.U)
- Note
This appears to be an odd, specialized operator that we haven't seen used much, and seems to be a holdover from chisel2. This may be deprecated and removed, usage is not recommended.
Example: - object Log2
Returns the base-2 integer logarithm of an UInt.
Returns the base-2 integer logarithm of an UInt.
Log2(8.U) // evaluates to 3.U Log2(13.U) // evaluates to 3.U (truncation) Log2(myUIntWire)
- Note
The result is truncated, so e.g. Log2(13.U) === 3.U
Example: - object Lookup
Muxes between cases based on whether an address matches any pattern for a case.
Muxes between cases based on whether an address matches any pattern for a case. Similar to MuxLookup, but uses BitPat for address comparison.
- Note
This appears to be an odd, specialized operator that we haven't seen used much, and seems to be a holdover from chisel2. This may be deprecated and removed, usage is not recommended.
- object MixedVec
Create a MixedVec type, given element types.
Create a MixedVec type, given element types. Inputs must be Chisel types which have no value (not hardware types).
- returns
MixedVec with the given types.
- object MixedVecInit
Create a MixedVec wire with default values as specified, and type of each element inferred from those default values.
Create a MixedVec wire with default values as specified, and type of each element inferred from those default values.
This is analogous to VecInit.
- returns
MixedVec with given values assigned
MixedVecInit(Seq(100.U(8.W), 10000.U(16.W), 101.U(32.W)))
Example: - object Mux1H
Builds a Mux tree out of the input signal vector using a one hot encoded select signal.
Builds a Mux tree out of the input signal vector using a one hot encoded select signal. Returns the output of the Mux tree.
val hotValue = chisel3.util.Mux1H(Seq( io.selector(0) -> 2.U, io.selector(1) -> 4.U, io.selector(2) -> 8.U, io.selector(4) -> 11.U, ))
- Note
results unspecified unless exactly one select signal is high
Example: - object MuxCase
Given an association of values to enable signals, returns the first value with an associated high enable signal.
Given an association of values to enable signals, returns the first value with an associated high enable signal.
MuxCase(default, Array(c1 -> a, c2 -> b))
Example: - object MuxLookup extends SourceInfoDoc
Creates a cascade of n Muxs to search for a key value.
Creates a cascade of n Muxs to search for a key value. The Selector may be a UInt or an EnumType.
MuxLookup(idx, default)(Seq(0.U -> a, 1.U -> b)) MuxLookup(myEnum, default)(Seq(MyEnum.a -> 1.U, MyEnum.b -> 2.U, MyEnum.c -> 3.U))
Example: - object OHToUInt
Returns the bit position of the sole high bit of the input bitvector.
Returns the bit position of the sole high bit of the input bitvector.
Inverse operation of UIntToOH.
OHToUInt("b0100".U) // results in 2.U
- Note
assumes exactly one high bit, results undefined otherwise
Example: - object Pipe
A factory to generate a hardware pipe.
A factory to generate a hardware pipe. This can be used to delay Valid data by a design-time configurable number of cycles.
Here, we construct three different pipes using the different provided
apply
methods and hook them up together. The types are explicitly specified to show that these all communicate using Valid interfaces:val in: Valid[UInt] = Wire(Valid(UInt(2.W))) /* A zero latency (combinational) pipe is connected to 'in' */ val foo: Valid[UInt] = Pipe(in.valid, in.bits, 0) /* A one-cycle pipe is connected to the output of 'foo' */ val bar: Valid[UInt] = Pipe(foo.valid, foo.bits) /* A two-cycle pipe is connected to the output of 'bar' */ val baz: Valid[UInt] = Pipe(bar, 2)
- See also
Pipe class for an alternative API
Valid interface
Queue and the Queue factory for actual queues
The ShiftRegister factory to generate a pipe without a Valid interface
- object PopCount
Returns the number of bits set (value is 1 or true) in the input signal.
Returns the number of bits set (value is 1 or true) in the input signal.
PopCount(Seq(true.B, false.B, true.B, true.B)) // evaluates to 3.U PopCount(Seq(false.B, false.B, true.B, false.B)) // evaluates to 1.U PopCount("b1011".U) // evaluates to 3.U PopCount("b0010".U) // evaluates to 1.U PopCount(myUIntWire) // dynamic count
Example: - object PriorityEncoder
Returns the bit position of the least-significant high bit of the input bitvector.
Returns the bit position of the least-significant high bit of the input bitvector.
PriorityEncoder("b0110".U) // results in 1.U
- Note
Multiple bits may be high in the input.
,If no bits are high, the result is undefined.
Example: - object PriorityEncoderOH
Returns a bit vector in which only the least-significant 1 bit in the input vector, if any, is set.
Returns a bit vector in which only the least-significant 1 bit in the input vector, if any, is set.
PriorityEncoderOH(Seq(false.B, true.B, true.B, false.B)) // results in Seq(false.B, true.B, false.B, false.B)
Example: - object PriorityMux
Builds a Mux tree under the assumption that multiple select signals can be enabled.
Builds a Mux tree under the assumption that multiple select signals can be enabled. Priority is given to the first select signal.
val hotValue = chisel3.util.PriorityMux(Seq( io.selector(0) -> 2.U, io.selector(1) -> 4.U, io.selector(2) -> 8.U, io.selector(4) -> 11.U, ))
Returns the output of the Mux tree.
Example: - object Queue
Factory for a generic hardware queue.
- object ReadyValidIO
- object RegEnable
- object Reverse
Returns the input in bit-reversed order.
Returns the input in bit-reversed order. Useful for little/big-endian conversion.
Reverse("b1101".U) // equivalent to "b1011".U Reverse("b1101".U(8.W)) // equivalent to "b10110000".U Reverse(myUIntWire) // dynamic reverse
Example: - object SRAM
- object ShiftRegister
- object ShiftRegisters
- object SparseVec
Utilities related to SparseVec.
- object UIntToOH
Returns the one hot encoding of the input UInt.
Returns the one hot encoding of the input UInt.
UIntToOH(2.U) // results in "b0100".U
Example: - object Valid
Factory for generating "valid" interfaces.
Factory for generating "valid" interfaces. A "valid" interface is a data-communicating interface between a producer and a consumer where the producer does not wait for the consumer. Concretely, this means that one additional bit is added to the data indicating its validity.
As an example, consider the following Bundle,
MyBundle
:class MyBundle extends Bundle { val foo = Output(UInt(8.W)) }
To convert this to a
valid
interface, you wrap it with a call to theValid
companion object's apply method:val bar = Valid(new MyBundle)
The resulting interface is structurally equivalent to the following:
class MyValidBundle extends Bundle { val valid = Output(Bool()) val bits = Output(new MyBundle) }
In addition to adding the
valid
bit, aValid.fire
method is also added that returns thevalid
bit. Thisprovides a similarly named interface to DecoupledIO's fire.
- object is
Use to specify cases in a switch block, equivalent to a when block comparing to the condition variable.
- object isPow2
Returns whether a Scala integer is a power of two.
Returns whether a Scala integer is a power of two.
isPow2(1) // returns true isPow2(2) // returns true isPow2(3) // returns false isPow2(4) // returns true
Example: - object log2Ceil
Compute the log2 of a Scala integer, rounded up.
Compute the log2 of a Scala integer, rounded up. Useful for getting the number of bits needed to represent some number of states (in - 1). To get the number of bits needed to represent some number n, use log2Ceil(n + 1).
Note: can return zero, and should not be used in cases where it may generate unsupported zero-width wires.
log2Ceil(1) // returns 0 log2Ceil(2) // returns 1 log2Ceil(3) // returns 2 log2Ceil(4) // returns 2
Example: - object log2Down
Compute the log2 of a Scala integer, rounded down, with min value of 1.
Compute the log2 of a Scala integer, rounded down, with min value of 1.
log2Down(1) // returns 1 log2Down(2) // returns 1 log2Down(3) // returns 1 log2Down(4) // returns 2
Example: - object log2Floor
Compute the log2 of a Scala integer, rounded down.
Compute the log2 of a Scala integer, rounded down.
Can be useful in computing the next-smallest power of two.
log2Floor(1) // returns 0 log2Floor(2) // returns 1 log2Floor(3) // returns 1 log2Floor(4) // returns 2
Example: - object log2Up
Compute the log2 of a Scala integer, rounded up, with min value of 1.
Compute the log2 of a Scala integer, rounded up, with min value of 1. Useful for getting the number of bits needed to represent some number of states (in - 1), To get the number of bits needed to represent some number n, use log2Up(n + 1). with the minimum value preventing the creation of currently-unsupported zero-width wires.
Note: prefer to use log2Ceil when in is known to be > 1 (where log2Ceil(in) > 0). This will be deprecated when zero-width wires is supported.
log2Up(1) // returns 1 log2Up(2) // returns 1 log2Up(3) // returns 2 log2Up(4) // returns 2
Example: - object pla
- object scanLeftOr
Map each bit to the logical OR of itself and all bits with lower index
Map each bit to the logical OR of itself and all bits with lower index
Here
scanLeft
means "start from the left and iterate to the right, where left is the lowest index", a common operation on arrays and lists.scanLeftOr("b00001000".U(8.W)) // Returns "b11111000".U scanLeftOr("b00010100".U(8.W)) // Returns "b11111100".U scanLeftOr("b00000000".U(8.W)) // Returns "b00000000".U
Example: - object scanRightOr
Map each bit to the logical OR of itself and all bits with higher index
Map each bit to the logical OR of itself and all bits with higher index
Here
scanRight
means "start from the right and iterate to the left, where right is the highest index", a common operation on arrays and lists.scanRightOr("b00001000".U) // Returns "b00001111".U scanRightOr("b00010100".U) // Returns "b00011111".U scanRightOr("b00000000".U) // Returns "b00000000".U
Example: - object signedBitLength
- object simpleClassName
- object switch
Conditional logic to form a switch block.
Conditional logic to form a switch block. See is for the case API.
switch (myState) { is (state1) { // some logic here that runs when myState === state1 } is (state2) { // some logic here that runs when myState === state2 } }
Example: - object unsignedBitLength