一、什么是Chisel
Chisel是一个用于高级硬件设计的Scala语言接口。它允许设计人员以高性能、类型安全的方式构造参数化的数字电路。Chisel采用Scala的可扩展性和强制性类型,可以用于描述高速、低功耗现场可编程门阵列(FPGA)硬件、低延迟、高并发性能芯片,甚至是动态重构的硬件。
与传统的硬件描述语言不同,Chisel是一种基于工程的概念的语言。它内置了许多工具和库,可以用于简化设计流程,并提供高层次的软件抽象层次和等效性,进一步提高用户的可移植性。事实上,Chisel非常适合用于构建可重用的芯片设计库。
二、Chisel特征
1. Chisel是一种基于硬件生成器的语言
硬件生成器可以使用Scala的函数、类和模块来定义,从而生成具有丰富性质的数字电路。通过使用硬件生成器,设计人员可以通过Chisel生成各种设计,例如组合逻辑、时序逻辑、状态机和流水线等。
2. Chisel支持代码重用性
Chisel融合了硬件生成器的特性,使用户能够轻松地将代码重用于不同的硬件系统。这种模块化方法与软件开发类似,并具有与高级编程语言相同的语义和结构,使得硬件设计更加直观、健壮和可扩展。
3. Chisel提供了类型安全
Chisel采用Scala的强制性类型,使得设计人员能够更好地发现、检测和纠正错误。在硬件语言中,错误会导致芯片的故障或不可预测的行为,因此Chisel的类型安全和可验证性非常重要。
4. Chisel提供了高性能和低延迟
Chisel使用Scala的函数式编程原则,因此具有高并发性和低延迟特性。硬件代码可以在Scala中生成,然后通过优化流水线来提高硬件系统的性能和加速。
5. Chisel提供了高层次的抽象功能
Chisel可以用于定义和构建高级别抽象,例如高层次语境、数据结构和算法。这一特性有利于将软件开发者转化为硬件系统设计人员,并极大地促进了硬件和软件之间的交互。
三、Scala + Chisel示例
Chisel中的图像处理示例
import Chisel._
class ImageProcessing(width: Int, height: Int) extends Module {
val input = UInt(INPUT, width * height * 3)
val output = UInt(OUTPUT, width * height * 3)
val hsobel = Vec(Seq(-1, -2, -1, 0, 0, 0, 1, 2, 1).map(SInt(_))) // horizontal Sobel filter
val vsobel = Vec(Seq(-1, 0, 1, -2, 0, 2, -1, 0, 1).map(SInt(_))) // vertical Sobel filter
val img = Vec(Seq.fill(width * height)(Vec(Seq.fill(3)(Bits(0, width = 8))))).flatten
val img_w = Reg(init=Bits(0, width = width * 3))
val img_row = img_w(width - 1, 0)
val img_data = Reg(init=UInt(0, width = 24))
val h_sums = Vec(Seq.fill(height)(Reg(init=SInt(0, width = 8))))
val v_sums = Vec(Seq.fill(width)(Reg(init=SInt(0, width = 8))))
val mag_ img row = Vec(Seq.fill(width * height)(Bits(0, width = 8)))
val angle_row = Vec(Seq.fill(width * height)(Bits(0, width = 9)))
for (i <- 0 until width height) {
h_sums(i) := Mux(img_row === UInt(0), SInt(0), hsobel.zip(img.slice(i, i + 9)).map{case(k, v) => k * v}.reduce(_+_));
v_sums(i) := Mux(img_row === UInt(0), SInt(0), vsobel.zip(((0 until height) map (j => img(i + width * j)))).map{case(k, v) => k * v}.reduce(_+_));
mag_row(i) := math.sqrt(h_sums(i) * h_sums(i) + v_sums(i) * v_sums(i)).toBit()
angle_row(i) := (((math.atan2(v_sums(i), h_sums(i)) + math.Pi) / (2 * math.Pi)) * 512 + 0.5).floor.toUInt()
}
when (img_row === UInt(0)) {
img_w := input
} .otherwise {
img_w := img_w(width * 3 - 1, 0) ## input
}
img_data := img_w(23, 0)
for (i <- 0 until width) {
for (j <- 0 until height) {
do {
img(i + j * width)(2, 0) := img_data(2, 0)
img(i + j * width)(5, 3) := img_data(5, 3)
img(i + j * width)(8, 6) := img_data(8, 6)
img_data := Mux(img_data === Bits(255), UInt(0), img_data + UInt(1))
} while (!img_data(7))
}
}
output := Cat(mag_row)
}
object ImageProcessingMain {
def main(args: Array[String]): Unit = {
chiselMain.run(args :+, () => Module(new ImageProcessing(256, 256)))
}
}
四、总结
Chisel是一个高度可扩展的硬件构建语言,可以与Scala的模块化和函数式编程结合使用。它提供了许多特性,例如硬件生成器、代码重用性、类型安全、高性能/低延迟和高级抽象功能,可以让设计人员更加直观、健壮和可扩展的构建数字电路。同时,Scala的可扩展性和强制性类型使得Chisel非常适合进行高速、低功耗现场可编程门阵列(FPGA)硬件、低延迟、高并发性能芯片,甚至是动态重构的硬件等领域的构建。