diff options
| author | Palmer Dabbelt | 2015-11-02 13:29:15 -0800 |
|---|---|---|
| committer | Palmer Dabbelt | 2015-11-02 13:29:15 -0800 |
| commit | 3ccc3d5728e17fae6fe41a396479a9114d3af7d5 (patch) | |
| tree | b4bcdd586123b571a2f53b6726e501003dd46119 /src/main/scala/Chisel/util/OneHot.scala | |
| parent | 178f5c564e9ab0594656185e2e0a5bcc029d5743 (diff) | |
| parent | 6c34949c45cf7ddfdabafb749de2cb9e439b381e (diff) | |
Merge pull request #37 from ucb-bar/utilsplit
Break out Utils.scala into smaller portions
Diffstat (limited to 'src/main/scala/Chisel/util/OneHot.scala')
| -rw-r--r-- | src/main/scala/Chisel/util/OneHot.scala | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/src/main/scala/Chisel/util/OneHot.scala b/src/main/scala/Chisel/util/OneHot.scala new file mode 100644 index 00000000..38b96511 --- /dev/null +++ b/src/main/scala/Chisel/util/OneHot.scala @@ -0,0 +1,62 @@ +// See LICENSE for license details. + +/** Circuit generators for working with one-hot representations. + */ + +package Chisel + +/** Converts from One Hot Encoding to a UInt indicating which bit is active + * This is the inverse of [[Chisel.UIntToOH UIntToOH]]*/ +object OHToUInt { + def apply(in: Seq[Bool]): UInt = apply(Vec(in)) + def apply(in: Vec[Bool]): UInt = apply(in.toBits, in.size) + def apply(in: Bits): UInt = apply(in, in.getWidth) + + def apply(in: Bits, width: Int): UInt = { + if (width <= 2) { + Log2(in, width) + } else { + val mid = 1 << (log2Up(width)-1) + val hi = in(width-1, mid) + val lo = in(mid-1, 0) + Cat(hi.orR, apply(hi | lo, mid)) + } + } +} + +/** @return the bit position of the trailing 1 in the input vector + * with the assumption that multiple bits of the input bit vector can be set + * @example {{{ data_out := PriorityEncoder(data_in) }}} + */ +object PriorityEncoder { + def apply(in: Seq[Bool]): UInt = PriorityMux(in, (0 until in.size).map(UInt(_))) + def apply(in: Bits): UInt = apply(in.toBools) +} + +/** Returns the one hot encoding of the input UInt. + */ +object UIntToOH +{ + def apply(in: UInt, width: Int = -1): UInt = + if (width == -1) { + UInt(1) << in + } else { + (UInt(1) << in(log2Up(width)-1,0))(width-1,0) + } +} + +/** Returns a bit vector in which only the least-significant 1 bit in + the input vector, if any, is set. + */ +object PriorityEncoderOH +{ + private def encode(in: Seq[Bool]): UInt = { + val outs = Vec.tabulate(in.size)(i => UInt(BigInt(1) << i, in.size)) + PriorityMux(in :+ Bool(true), outs :+ UInt(0, in.size)) + } + def apply(in: Seq[Bool]): Vec[Bool] = { + val enc = encode(in) + Vec.tabulate(in.size)(enc(_)) + } + def apply(in: Bits): UInt = encode((0 until in.getWidth).map(i => in(i))) +} |
