when-otherwise 语句与 Mux 语句
when-otherwise Statement vs. Mux Statement
我想知道使用 Mux 语句与使用 when-otherwise 语句之间是否存在任何根本区别?
例如:
when(read){
dataReg := inValue
}.otherwise{
dataReg := 0.U
}
或
dataReg := Mux (read, inValue, 0.U)
是否应该对其中之一有任何偏好?
您可以将 when-otherwise
视为一个更高级别的构造,它被降低为一个或多个 Muxes
。 Mux
对于简单的情况很有用(特别是当您希望代码适合 1 行时),但是有很多东西用 when-otherwise
.[=25= 来表达更方便]
例如,when-otherwise
可以用Mux
不允许的方便的方式来表示双向连接。
val producer_1 = IO(Flipped(Decoupled(UInt(8.W))))
val producer_2 = IO(Flipped(Decoupled(UInt(8.W))))
val select = IO(Input(Bool()))
val consumer = IO(Decoupled(UInt(8.W)))
when(select) {
consumer <> producer_1
producer_2.ready := false.B
} .otherwise {
consumer <> producer_2
producer_1.ready := false.B
}
这会生成:
assign producer_1_ready = select & consumer_ready;
assign producer_2_ready = select ? 1'h0 : consumer_ready;
assign consumer_valid = select ? producer_1_valid : producer_2_valid;
assign consumer_bits = select ? producer_1_bits : producer_2_bits;
(可执行示例 link:https://scastie.scala-lang.org/GVH1zA2MTQ2fhm4yENijbg)
此外,when-otherwise
可用于同时连接多个事物:
val a = IO(Input(Bool()))
val b = IO(Input(Bool()))
val foo = IO(Input(UInt(8.W)))
val bar = IO(Input(UInt(8.W)))
val out = IO(Output(UInt(8.W)))
val reg1 = RegInit(0.U(8.W))
val reg2 = RegInit(0.U(8.W))
out := reg1
when (a) {
reg1 := foo
} .elsewhen (b) {
reg1 := bar
reg2 := foo
} .otherwise {
out := reg2
}
(可执行示例 link:https://scastie.scala-lang.org/q9WNZVDoSpufRCyBeukCEg)
请注意,reg1
、reg2
和 out
在不同的路径上存在连接,并且 none 甚至出现在每条路径中。
我想知道使用 Mux 语句与使用 when-otherwise 语句之间是否存在任何根本区别?
例如:
when(read){
dataReg := inValue
}.otherwise{
dataReg := 0.U
}
或
dataReg := Mux (read, inValue, 0.U)
是否应该对其中之一有任何偏好?
您可以将 when-otherwise
视为一个更高级别的构造,它被降低为一个或多个 Muxes
。 Mux
对于简单的情况很有用(特别是当您希望代码适合 1 行时),但是有很多东西用 when-otherwise
.[=25= 来表达更方便]
例如,when-otherwise
可以用Mux
不允许的方便的方式来表示双向连接。
val producer_1 = IO(Flipped(Decoupled(UInt(8.W))))
val producer_2 = IO(Flipped(Decoupled(UInt(8.W))))
val select = IO(Input(Bool()))
val consumer = IO(Decoupled(UInt(8.W)))
when(select) {
consumer <> producer_1
producer_2.ready := false.B
} .otherwise {
consumer <> producer_2
producer_1.ready := false.B
}
这会生成:
assign producer_1_ready = select & consumer_ready;
assign producer_2_ready = select ? 1'h0 : consumer_ready;
assign consumer_valid = select ? producer_1_valid : producer_2_valid;
assign consumer_bits = select ? producer_1_bits : producer_2_bits;
(可执行示例 link:https://scastie.scala-lang.org/GVH1zA2MTQ2fhm4yENijbg)
此外,when-otherwise
可用于同时连接多个事物:
val a = IO(Input(Bool()))
val b = IO(Input(Bool()))
val foo = IO(Input(UInt(8.W)))
val bar = IO(Input(UInt(8.W)))
val out = IO(Output(UInt(8.W)))
val reg1 = RegInit(0.U(8.W))
val reg2 = RegInit(0.U(8.W))
out := reg1
when (a) {
reg1 := foo
} .elsewhen (b) {
reg1 := bar
reg2 := foo
} .otherwise {
out := reg2
}
(可执行示例 link:https://scastie.scala-lang.org/q9WNZVDoSpufRCyBeukCEg)
请注意,reg1
、reg2
和 out
在不同的路径上存在连接,并且 none 甚至出现在每条路径中。