aayupov
aayupov

Reputation: 267

Chisel: How to model a variable incremented in a unrolled loop

Let's say I have a Vec of Bool. I want to fill a new Vec of the same size with values equal to a number of true values I've seen up to this index in the original Vec. I want to do it combinationally.

With my HLS background and coding style settled in my head, I want to write something like this:

  def foo ( in : Vec[UInt] ) = {

    val out = Vec.fill(in.size) {UInt(in.size)}
    val nextInd = Wire(init = 0.U)

    in.zipWithIndex.foreach {case(val, ind) => 
      when(val === true.B) {
        out(ind) := nextInd
        nextInd := Wire(init = nextInd+1.U)
      }
    }
  }

But I understand this is creating a combinational loop, but I can't find a good way to model it. Somehow I need to generate a new variable iteration of the loop and pass it between iterations.

Upvotes: 0

Views: 453

Answers (2)

Chick Markley
Chick Markley

Reputation: 4051

The following seems a little simpler:

  // return is a Vec with each element equal to the sum of bits up to it's index
  def foo(inBits: Vec[Bool]): Vec[UInt] = {
    val counts = Vec(size, UInt(log2Ceil(size + 1).W))
    inBits.zipWithIndex.foldLeft(0.U) { case (lastValue, (bit, index)) =>
      counts(index) := bit + lastValue
      counts(index)
    }
    counts
  }

Upvotes: 2

aayupov
aayupov

Reputation: 267

I believe I figured out how to do it in Chisel. I can use foldLeft and pass a new variable from one iteration to the next:

  def foo ( in : Vec[UInt] ) = {
    val vecSize = in.size
    val out = Vec.fill(vecSize) {UInt(vecSize)}

    in.zipWithIndex.foldLeft (Wire(init = 0.U)) {case(prevInd,(val, ind)) => 
      // val nextInd = Wire(init = prevInd) // this will not work due to bitwidth be not enough to hold an incremented value, so i do the following instead
      val nextInd = Wire(init = UInt(vecSize)) // here i just make sure the width is enough
      nextInd := prevInd
      when(val === true.B) {
        out(ind) := prevInd
        nextInd := Wire(init = prevInd+1.U)
      }
      nextInd
    }
  }

Upvotes: 0

Related Questions