Chisel:如何模拟在展开循环中递增的变量

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

假设我有一个 Bool Vec。我想填充一个相同大小的新 Vec,其值等于我在原始 Vec 中看到的这个索引的真实值的数量。我想结合起来做。

有了我的 HLS 背景和编码风格,我想写这样的东西:

  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)
      }
    }
  }

但我知道这是在创建组合循环,但我找不到对其建模的好方法。我需要以某种方式生成循环的新变量迭代并在迭代之间传递它。

我相信我知道如何在 Chisel 中做到这一点。我可以使用 foldLeft 并将一个新变量从一个迭代传递到下一个迭代:

  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
    }
  }

下面的好像比较简单:

  // 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
  }