summaryrefslogtreecommitdiff
path: root/src/test/scala/chiselTests/Util.scala
blob: d2f8bd9b7d1b92019d741b58c2ab9a313fc0d0e7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// SPDX-License-Identifier: Apache-2.0

// Useful utilities for tests

package chiselTests

import chisel3._
import chisel3.experimental.Interval
import chisel3.internal.firrtl.{IntervalRange, KnownBinaryPoint, Width}
import _root_.firrtl.{ir => firrtlir}

class PassthroughModuleIO extends Bundle {
  val in = Input(UInt(32.W))
  val out = Output(UInt(32.W))
}

trait AbstractPassthroughModule extends RawModule {
  val io = IO(new PassthroughModuleIO)
  io.out := io.in
}

class PassthroughModule extends Module with AbstractPassthroughModule
class PassthroughMultiIOModule extends Module with AbstractPassthroughModule
class PassthroughRawModule extends RawModule with AbstractPassthroughModule

case class ScalaIntervalSimulator(intervalRange: IntervalRange) {
  val binaryPoint: Int = intervalRange.binaryPoint.asInstanceOf[KnownBinaryPoint].value
  val epsilon:     Double = 1.0 / math.pow(2.0, binaryPoint.toDouble)

  val (lower, upper) = (intervalRange.lowerBound, intervalRange.upperBound) match {

    case (firrtlir.Closed(lower1), firrtlir.Closed(upper1)) => (lower1, upper1)
    case (firrtlir.Closed(lower1), firrtlir.Open(upper1))   => (lower1, upper1 - epsilon)
    case (firrtlir.Open(lower1), firrtlir.Closed(upper1))   => (lower1 + epsilon, upper1)
    case (firrtlir.Open(lower1), firrtlir.Open(upper1))     => (lower1 + epsilon, upper1 - epsilon)
    case _ =>
      throw new Exception(s"lower and upper bounds must be defined, range here is $intervalRange")
  }

  def clip(value: BigDecimal): BigDecimal = {

    if (value < lower) {
      lower
    } else if (value > upper) {
      upper
    } else {
      value
    }
  }

  def wrap(value: BigDecimal): BigDecimal = {

    if (value < lower) {
      upper + (value - lower) + epsilon
    } else if (value > upper) {
      ((value - upper) - epsilon) + lower
    } else {
      value
    }
  }

  def allValues: Iterator[BigDecimal] = {
    (lower to upper by epsilon).toIterator
  }

  def makeLit(value: BigDecimal): Interval = {
    Interval.fromDouble(value.toDouble, width = Width(), binaryPoint = binaryPoint.BP)
  }
}