CSR decoding
[rv32.git] / cpu_alu.v
1 /*
2 * Copyright 2018 Jacob Lifshay
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a copy
5 * of this software and associated documentation files (the "Software"), to deal
6 * in the Software without restriction, including without limitation the rights
7 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 * copies of the Software, and to permit persons to whom the Software is
9 * furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included in all
12 * copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 * SOFTWARE.
21 *
22 */
23 `timescale 1ns / 1ps
24 `include "riscv.vh"
25
26 module cpu_alu(
27 input [6:0] funct7,
28 input [2:0] funct3,
29 input [6:0] opcode,
30 input [31:0] a,
31 input [31:0] b,
32 output [31:0] result
33 );
34
35 wire is_sub = funct7[5] & opcode[5];
36 wire [31:0] add_sub_result = a + (is_sub ? ~b : b) + is_sub;
37 wire [31:0] shift_left_result = a << b[4:0];
38 wire [31:0] shift_right_result = funct7[5] ? $unsigned($signed(a) >>> b[4:0]) : a >> b[4:0];
39 wire [31:0] xor_result = a ^ b;
40 wire [31:0] or_result = a | b;
41 wire [31:0] and_result = a & b;
42 wire [31:0] lt_arg_flip = {~funct3[0], 31'b0};
43 wire [31:0] lt_result = ((a ^ lt_arg_flip) < (b ^ lt_arg_flip)) ? 32'b1 : 32'b0;
44
45 function [31:0] mux8(
46 input [2:0] select,
47 input [31:0] v0,
48 input [31:0] v1,
49 input [31:0] v2,
50 input [31:0] v3,
51 input [31:0] v4,
52 input [31:0] v5,
53 input [31:0] v6,
54 input [31:0] v7);
55 begin
56 case(select)
57 0: mux8 = v0;
58 1: mux8 = v1;
59 2: mux8 = v2;
60 3: mux8 = v3;
61 4: mux8 = v4;
62 5: mux8 = v5;
63 6: mux8 = v6;
64 7: mux8 = v7;
65 default: mux8 = 32'hXXXXXXXX;
66 endcase
67 end
68 endfunction
69
70 assign result = mux8(funct3,
71 add_sub_result,
72 shift_left_result,
73 lt_result,
74 lt_result,
75 xor_result,
76 shift_right_result,
77 or_result,
78 and_result);
79
80 endmodule