xref: /XiangShan/src/main/scala/xiangshan/backend/fu/util/CSA.scala (revision f320e0f01bd645f0a3045a8a740e60dd770734a9)
1/***************************************************************************************
2* Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences
3* Copyright (c) 2020-2021 Peng Cheng Laboratory
4*
5* XiangShan is licensed under Mulan PSL v2.
6* You can use this software according to the terms and conditions of the Mulan PSL v2.
7* You may obtain a copy of Mulan PSL v2 at:
8*          http://license.coscl.org.cn/MulanPSL2
9*
10* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
11* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
12* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
13*
14* See the Mulan PSL v2 for more details.
15***************************************************************************************/
16
17package xiangshan.backend.fu.util
18
19import chisel3._
20import chisel3.util._
21
22abstract class CarrySaveAdderMToN(m: Int, n: Int)(len: Int) extends Module{
23  val io = IO(new Bundle() {
24    val in = Input(Vec(m, UInt(len.W)))
25    val out = Output(Vec(n, UInt(len.W)))
26  })
27}
28
29class CSA2_2(len: Int) extends CarrySaveAdderMToN(2, 2)(len) {
30  val temp = Wire(Vec(len, UInt(2.W)))
31  for((t, i) <- temp.zipWithIndex){
32    val (a, b) = (io.in(0)(i), io.in(1)(i))
33    val sum = a ^ b
34    val cout = a & b
35    t := Cat(cout, sum)
36  }
37  io.out.zipWithIndex.foreach({case(x, i) => x := Cat(temp.reverse map(_(i)))})
38}
39
40class CSA3_2(len: Int) extends CarrySaveAdderMToN(3, 2)(len){
41  val temp = Wire(Vec(len, UInt(2.W)))
42  for((t, i) <- temp.zipWithIndex){
43    val (a, b, cin) = (io.in(0)(i), io.in(1)(i), io.in(2)(i))
44    val a_xor_b = a ^ b
45    val a_and_b = a & b
46    val sum = a_xor_b ^ cin
47    val cout = a_and_b | (a_xor_b & cin)
48    t := Cat(cout, sum)
49  }
50  io.out.zipWithIndex.foreach({case(x, i) => x := Cat(temp.reverse map(_(i)))})
51}
52
53class CSA5_3(len: Int)extends CarrySaveAdderMToN(5, 3)(len){
54  val FAs = Array.fill(2)(Module(new CSA3_2(len)))
55  FAs(0).io.in := io.in.take(3)
56  FAs(1).io.in := VecInit(FAs(0).io.out(0), io.in(3), io.in(4))
57  io.out := VecInit(FAs(1).io.out(0), FAs(0).io.out(1), FAs(1).io.out(1))
58}
59
60class C22 extends CSA2_2(1)
61class C32 extends CSA3_2(1)
62class C53 extends CSA5_3(1)
63
64