package projet.op

import chisel3._
import chisel3.util.switch
import projet.CUInterface
import projet.AluOpCode
import chisel3.util.is
import projet.DMemSize
import projet.OpType

object OpLoad {
    // Implements functions for all instruction of the OpLoad kind
    def opLoad(io: CUInterface) = {
        val funct3 = io.instruction(14, 12);

        // Meaning of Funct3 in the context of an OpLoad instruction
        object Funct3 extends ChiselEnum {
            // Zero extend
            val LB = "b000".U
            val LH = "b001".U
            val LW = "b010".U

            // Sign extend
            val LBU = "b100".U
            val LHU = "b101".U
            val LWU = "b110".U

            // Arch width
            val LD = "b011".U
        }

        io.optype := OpType.I
        io.alu_opcode := AluOpCode.Add
        io.mux_alu_imm := true.B
        io.mux_rega_pc := true.B
        io.mux_regb_imm := false.B
        io.mux_writeback_pc := true.B;
        io.mux_executeout_dout := false.B;
        io.reg_file_we := true.B
        io.memory_en := true.B
        io.memory_we := false.B
        io.memory_sign_extend := false.B;
        switch(funct3) {
            // Byte load
            is(Funct3.LB) {
                io.memory_size := DMemSize.Byte
                io.memory_sign_extend := true.B;
            }
            is(Funct3.LBU) {
                io.memory_size := DMemSize.Byte
            }

            // Half load
            is(Funct3.LH) {
                io.memory_size := DMemSize.Half
                io.memory_sign_extend := true.B;
            }
            is(Funct3.LHU) {
                io.memory_size := DMemSize.Half
            }

            // Word load
            is(Funct3.LW) {
                io.memory_size := DMemSize.Word
                io.memory_sign_extend := true.B;
            }
            is(Funct3.LWU) {
                io.memory_size := DMemSize.Word
            }

            // Long load
            is(Funct3.LD) {
                io.memory_size := DMemSize.Long
            }
        }
    }

}
