# 02-chisel-tutorial代码学习之组合逻辑

2021/8/20 22:33:32 浏览：

• wire类型变量的声明
• 1-bit全加器
• 位宽推断

# wire类型变量的声明

Constructing combinational logic blocks in Chisel is fairly straightforward; when you declare a val in Scala, it creates a node that represents the data that it is assigned to. As long as the value is not assigned to be a register type (explained later), this tells the Chisel compiler to treat the value as wire. Thus any number of these values can be connected and manipulated to produce the value that we want.

# 1-bit全加器

1-bit全加器是一个非常经典的组合逻辑电路，如下图所示，

``````package examples

import chisel3._

val io = IO(new Bundle {
val a    = Input(UInt(1.W))
val b    = Input(UInt(1.W))
val cin  = Input(UInt(1.W))
val sum  = Output(UInt(1.W))
val cout = Output(UInt(1.W))
})

// Generate the sum
val a_xor_b = io.a ^ io.b
io.sum := a_xor_b ^ io.cin
// Generate the carry
val a_and_b = io.a & io.b
val b_and_cin = io.b & io.cin
val a_and_cin = io.a & io.cin
io.cout := a_and_b | b_and_cin | a_and_cin
}
``````

# 位宽推断

``````module FullAdder(
input   clock,
input   reset,
input   io_a,
input   io_b,
input   io_cin,
output  io_sum,
output  io_cout
);
wire  a_xor_b = io_a ^ io_b; // @[FullAdder.scala 16:22]
wire  a_and_b = io_a & io_b; // @[FullAdder.scala 19:22]
wire  b_and_cin = io_b & io_cin; // @[FullAdder.scala 20:24]
wire  a_and_cin = io_a & io_cin; // @[FullAdder.scala 21:24]
wire  _T_1 = a_and_b | b_and_cin; // @[FullAdder.scala 22:22]
assign io_sum = a_xor_b ^ io_cin; // @[FullAdder.scala 17:10]
assign io_cout = _T_1 | a_and_cin; // @[FullAdder.scala 22:11]
endmodule
``````

``````package examples

import chisel3._

val io = IO(new Bundle {
val a    = Input(UInt(2.W))
val b    = Input(UInt(2.W))
val cin  = Input(UInt(2.W))
val sum  = Output(UInt(2.W))
val cout = Output(UInt(2.W))
})

// Generate the sum
val a_xor_b = io.a ^ io.b
io.sum := a_xor_b ^ io.cin
// Generate the carry
val a_and_b = io.a & io.b
val b_and_cin = io.b & io.cin
val a_and_cin = io.a & io.cin
io.cout := a_and_b | b_and_cin | a_and_cin
}
``````

``````module FullAdder(
input        clock,
input        reset,
input  [1:0] io_a,
input  [1:0] io_b,
input  [1:0] io_cin,
output [1:0] io_sum,
output [1:0] io_cout
);
wire [1:0] a_xor_b = io_a ^ io_b; // @[FullAdder.scala 16:22]
wire [1:0] a_and_b = io_a & io_b; // @[FullAdder.scala 19:22]
wire [1:0] b_and_cin = io_b & io_cin; // @[FullAdder.scala 20:24]
wire [1:0] a_and_cin = io_a & io_cin; // @[FullAdder.scala 21:24]
wire [1:0] _T_1 = a_and_b | b_and_cin; // @[FullAdder.scala 22:22]
assign io_sum = a_xor_b ^ io_cin; // @[FullAdder.scala 17:10]
assign io_cout = _T_1 | a_and_cin; // @[FullAdder.scala 22:11]
endmodule
``````