Skip to content

Commit

Permalink
Make Counter emit valid FIRRTL (#1408)
Browse files Browse the repository at this point in the history
Remove var from object Counter.apply, using a Wire instead. Also improve
some ScalaDoc and the class Counter require message.
  • Loading branch information
jackkoenig authored Apr 10, 2020
1 parent 2b71a50 commit a39d0e1
Showing 1 changed file with 9 additions and 13 deletions.
22 changes: 9 additions & 13 deletions src/main/scala/chisel3/util/Counter.scala
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,17 @@ import chisel3.internal.naming.chiselName // can't use chisel3_ version because
*/
@chiselName
class Counter(val n: Int) {
require(n >= 0)
require(n >= 0, s"Counter value must be nonnegative, got: $n")
val value = if (n > 1) RegInit(0.U(log2Ceil(n).W)) else 0.U

/** Increment the counter, returning whether the counter currently is at the
* maximum and will wrap. The incremented value is registered and will be
* visible on the next cycle.
/** Increment the counter
*
* @note The incremented value is registered and will be visible on the next clock cycle
* @return whether the counter will wrap to zero on the next cycle
*/
def inc(): Bool = {
if (n > 1) {
val wrap = value === (n-1).asUInt
val wrap = value === (n-1).U
value := value + 1.U
if (!isPow2(n)) {
when (wrap) { value := 0.U }
Expand Down Expand Up @@ -62,13 +63,8 @@ object Counter
@chiselName
def apply(cond: Bool, n: Int): (UInt, Bool) = {
val c = new Counter(n)
// Note this use of var is generally frowned upon! Don't use this as an example.
// This is done because we wanted the hardware generated by c.inc() to be wrapped
// in a when statement, but still needed to refer to the final value returned by
// c.inc() so we could return cond && wrap. Unless you really, really know what
// you are doing, IGNORE THIS CODE!!!!!
var wrap: Bool = null
when (cond) { wrap = c.inc() }
(c.value, cond && wrap)
val wrap = WireInit(false.B)
when (cond) { wrap := c.inc() }
(c.value, wrap)
}
}

0 comments on commit a39d0e1

Please sign in to comment.