Exemple #1
1
 def __init__(self, memory):
     super().__init__()
     self.memory = memory  # Not part of CPU; what we really have is a connection
     self.registers = [
         ZeroRegister(),
         Register(),
         Register(),
         Register(),
         Register(),
         Register(),
         Register(),
         Register(),
         Register(),
         Register(),
         Register(),
         Register(),
         Register(),
         Register(),
         Register(),
         Register()
     ]
     self.condition = CondFlag.ALWAYS
     self.halted = False
     self.alu = ALU()
     # Convenient aliases
     self.pc = self.registers[15]
Exemple #2
0
 def __init__(self, out_size, reg_size, model, insts, mem_size=1000):
     self.registers = RegisterBank("Registers", reg_size)
     self.registers.write(0, 20)
     self.registers.write(1, 10)
     self.registers.write(2, 0)
     self.registers.write(4, 40)
     self.insts = MemoryBank("insts", len(insts))
     for index, encoding in enumerate(insts):
         self.insts.write(index, encoding)
     self.ir = 0
     self.memory = MemoryBank("main", mem_size)
     self.memory.write(40, 1000)
     self.memory.write(10, 10)
     self.memory.write(20, 3)
     # 0 : Inst,1:cond, 2:r0, 3:r1, 4:r2
     self.ops = [0 for i in range(out_size)]
     self.model = model
     self.ALU = ALU()
     self.functions = {}
     self.functions["READ"] = self.read
     self.functions["WRITE"] = self.write
     self.functions["ALU"] = self.alu
     self.functions["SET"] = self.sub_and_set
     self.functions["NO"] = self.noop
     self.functions["INCIN"] = self.inc_in
     self.functions["SETIN"] = self.set_in
     self.flag = 0
     self.encoding = self.insts.read_gauss(self.ir)
Exemple #3
0
def register_file_test():
    rg = RegisterFile()
    rg.set_register_write(True)
    i = 0
    for k in rg.data.keys():

        if i >= 10:
            rg.set_register_write(False)

        rg.set_read_r1(k)
        rg.set_read_r2(k)

        old_d1 = rg.read_d1
        old_d2 = rg.read_d2

        rg.set_write_r(k)
        rg.set_write_data(ALU.int_to_n_bit_binary(i))

        assert rg.read_d1 == rg.read_d2

        if i < 10:
            assert rg.read_d1 == ALU.int_to_n_bit_binary(i)
        else:
            assert rg.read_d1 == old_d1

        i += 1
Exemple #4
0
    def __init__(self, memory):
        super().__init__()

        self.memory = memory
        self.registers = [
            ZeroRegister(),
            Register(),
            Register(),
            Register(),
            Register(),
            Register(),
            Register(),
            Register(),
            Register(),
            Register(),
            Register(),
            Register(),
            Register(),
            Register(),
            Register(),
            Register()
        ]
        self.cond_flag = CondFlag.ALWAYS
        self.halted = False
        self.program_pointer = self.registers[15]
        self.alu = ALU()
    def __init__(self):
        """Construct a new CPU."""
        # Clear Registers
        self.reg = [0] * 8
        
        # set internal registers to 0
        self.pc = 0
        self.ir = 0
        self.fl = 0
        self.mar = 0
        self.mdr = 0

        # initialize stack pointer
        self.sp = 0xF4

        # RAM is cleared to zero
        self.ram = [0] * 256

        # R7 is set to keyboard interupt
        self.reg[7] = self.ram[0xF4]

        # set halt flag
        self.halt = False

        # initialize branchtable
        self.branchtable = Branchtable(self)

        # initialize ALU
        self.alu_ops = ALU(self)
    def __init__(self):
        self.pc = 0
        self.jump_target = ALU.int_to_n_bit_binary(0)
        self.alu_zero_flag = True
        self.alu_result = ALU.int_to_n_bit_binary(0)
        self.rd2 = ALU.int_to_n_bit_binary(0)
        self.reg_dest = ALU.int_to_n_bit_binary(0, 5)

        self.wb_control = WB_CONTROL()
        self.mem_control = MEM_CONTROL()
Exemple #7
0
def test_alu():
    alu = ALU()
    _str = alu.__str__()

    #create input power switches and connect up ripple carry adder
    inputs_a = get_eight_bit_switch(alu.input_a)
    inputs_b = get_eight_bit_switch(alu.input_b)

    op = Power()
    op.connect(alu.operator)

    #do some random tests
    no_tests = 100
    for i in range(no_tests):
        #turn on random bits
        for in_bit in inputs_a:
            in_bit.off()
            if randint(0, 2) == 2:
                in_bit.on()

        for in_bit in inputs_b:
            in_bit.off()
            if randint(0, 2) == 2:
                in_bit.on()

        #random op
        op.off()
        if randint(0, 1) == 1:
            op.on()

        #subtract
        if op.value:
            #if no overflow did it calculate correctly
            if alu.carry.value:
                assert alu.input_a.int_value - alu.input_b.int_value == alu.sum.int_value
                assert not alu.overflow.value
                assert not alu.negative.value
            #was there an overflow? if so was the result less than 0
            if not alu.carry.value:
                assert alu.input_a.int_value - alu.input_b.int_value < 0
                assert alu.overflow.value
                assert alu.negative.value
        #addition
        else:
            #was there an overflow? if so was the result over 255
            if alu.carry.value:
                assert alu.input_a.int_value + alu.input_b.int_value > 255
                assert alu.overflow.value
                assert not alu.negative.value
            #if no overflow did it calculate correctly
            if not alu.carry.value:
                assert alu.input_a.int_value + alu.input_b.int_value == alu.sum.int_value
                assert not alu.overflow.value
                assert not alu.negative.value
Exemple #8
0
def search_for_model_number(instructions: list) -> int:
    alu = ALU(instructions)
    max_valid_model_no = None
    curr_model_no = [9]*14
    while max_valid_model_no is None:
        model_no = int(''.join([str(x) for x in curr_model_no]))
        if not 0 in curr_model_no:
            if alu.MONAD(curr_model_no):
                max_valid_model_no = model_no
        model_no -= 1
        curr_model_no = [int(x) for x in str(model_no)]
    return max_valid_model_no  
Exemple #9
0
	def __init__(self, memoryFile):
		self.nCycles = 0 # Used to hold number of clock cycles spent executing instructions

		# Fetch
		self.PCMux	  = Mux()
		self.ProgramC   = PC(long(0xbfc00200))
		self.InstMem	= InstructionMemory(memoryFile)
		self.IFadder	= Add()
		self.JMux	   = Mux()
		self.IFaddconst = Constant(4)
		self.IF_ID_Wall = Wall()
		self.fetchgroup = {}

		# Decode
		self.register   = RegisterFile()
		self.signext	= SignExtender()
		self.control	= ControlElement()
		self.jmpCalc	= JumpCalc()
		self.ID_EX_Wall = Wall()

		# Execute
		self.EXadder	= Add()
		self.shiftL	 = LeftShifter()
		self.ALogicUnit = ALU()
		self.ALUSrcMux  = Mux()
		self.RegDstMux  = Mux()
		self.ALUctrl	= AluControl()
		self.EX_MEM_Wall= Wall()

		# Memory
		self.storage	= DataMemory(memoryFile)
		self.brnch	  = Branch()
		self.MEM_WB_Wall= Wall()

		# Write Back
		self.WBmux = Mux()

		self.ProgramC
		self.elements1 = [self.InstMem, self.IFaddconst, self.IFadder, self.PCMux, self.JMux]
		self.elements2 = [self.control, self.register, self.signext, self.jmpCalc]
		self.elements3 = [self.shiftL, self.ALUSrcMux, self.RegDstMux, self.ALUctrl, self.ALogicUnit, self.EXadder]
		self.elements4 = [self.brnch, self.storage]
		self.elementsboot = [self.IFaddconst, self.IFadder, self.InstMem,
							 self.IF_ID_Wall, self.register, self.signext, self.control, self.jmpCalc,
							 self.ID_EX_Wall, self.RegDstMux, self.shiftL, self.EXadder, self.ALUSrcMux, self.ALUctrl, self.ALogicUnit,
							 self.EX_MEM_Wall, self.brnch, self.storage,
							 self.MEM_WB_Wall, self.WBmux, self.PCMux, self.JMux]
		self.walls = [self.MEM_WB_Wall, self.EX_MEM_Wall, self.ID_EX_Wall, self.IF_ID_Wall]


		self._connectCPUElements()
Exemple #10
0
    def fetch(self):
        instruction = self._load_w(self._instruction_memory, self._pc)
        self._pc = ALU.n_bit_binary_to_decimal(self._pc) + 4
        self._pc = ALU.int_to_n_bit_binary(self._pc)

        # end of program
        if instruction == list(ALU.int_to_n_bit_binary(-1)):
            self._end = True

        if self._end:
            instruction = NOOP
            self._if_id_tmp.set_inst(tuple(instruction))
        else:
            self._if_id_tmp.set_pc(self._pc)
            self._if_id_tmp.set_inst(tuple(instruction))
    def __init__(self, block, layers, num_classes=10, r=16):
        self.inplanes = 16
        super(ResNetCIFAR, self).__init__()
        self.conv1 = nn.Conv2d(3,
                               16,
                               kernel_size=3,
                               stride=1,
                               padding=1,
                               bias=False)
        self.bn1 = nn.BatchNorm2d(16)
        # self.relu = nn.ReLU(inplace=True)
        self.alu = ALU(16, 4)
        self.layer1 = self._make_layer(block, 16, layers[0], r=4)
        self.layer2 = self._make_layer(block, 32, layers[1], stride=2, r=8)
        self.layer3 = self._make_layer(block, 64, layers[2], stride=2, r=16)
        self.avgpool = nn.AvgPool2d(8, stride=1)
        self.fc = nn.Linear(64 * block.expansion, num_classes)

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
                m.weight.data.normal_(0, math.sqrt(2. / n))
            elif isinstance(m, nn.BatchNorm2d):
                if m.affine:
                    m.weight.data.fill_(1)
                    m.bias.data.zero_()
            elif isinstance(m, nn.BatchNorm1d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()
Exemple #12
0
    def __init__(self):
        """Construct a new CPU."""
        # memory or RAM, 256 bytes (1 byte = 8 bits)
        self.running = True
        self.ram = [0] * 256
        self.reg = [0] * 8  # register
        self.sp = 7
        self.reg[self.sp] = 0xf4
        self.pc = 0   # program counter (pc)
        self.alu = ALU(self.running, self.ram, self.reg)
        self.function_table = {}  # * AKA jump table or branch table
        self.function_table[0b01000111] = self.prn
        self.function_table[0b00000001] = self.hlt
        self.function_table[0b01000101] = self.push
        self.function_table[0b01000110] = self.pop
        # * Register functions
        self.function_table[0b10000010] = self.ldi
        self.function_table[0b01010100] = self.jmp
        self.function_table[0b01010000] = self.call
        self.function_table[0b00010001] = self.ret

        self.function_table[0b10100000] = self.alu.add
        self.function_table[0b10100011] = self.alu.div
        self.function_table[0b01100110] = self.alu.dec
        self.function_table[0b01100101] = self.alu.inc
        self.function_table[0b10100100] = self.alu.mod
        self.function_table[0b10100010] = self.alu.mul
        self.function_table[0b10101010] = self.alu.or_bitwise
        self.function_table[0b10101011] = self.alu.xor
        self.function_table[0b10101100] = self.alu.shl
        self.function_table[0b10101101] = self.alu.shr
        self.function_table[0b10100001] = self.alu.sub
Exemple #13
0
    def _load_w(self, mem, base_addr, memRead=True):

        if not memRead:
            return ALU.int_to_n_bit_binary(0)

        n = 4
        self._alu.set_input_1(base_addr)
        self._alu.set_op('00')

        word = []

        for i in range(n):
            self._alu.set_input_2(ALU.int_to_n_bit_binary(i))
            addr = self._alu.result
            word += list(mem.at(addr))

        return word
Exemple #14
0
    def __init__(self, out_size, reg_size, model, insts,consts,mem_size=1000):
        self.num_regs = reg_size
        self.registers = RegisterBank("Registers", reg_size)
        # self.registers.write(0, 10)
        # self.registers.write(1, 5)
        # #self.registers.write(2, 1)
        # self.registers.write(3, 0)
        # #self.registers.write(10, 0)
        # #self.registers.write(13, 17)
        # #self.registers.write(6, 4)

        self.insts = MemoryBank("insts",len(insts))
        self.consts = MemoryBank("consts",len(consts))

        for index,encoding in enumerate(insts):
            self.insts.write(index,encoding)

        for index,constant in enumerate(consts):
            self.consts.write(index,constant)

        self.ir = 0
        self.cache =CacheBank()
        self.cache.memory.write(10, 2)
        self.cache.memory.write(11, 1)
        self.cache.memory.write(12, 9)
        self.cache.memory.write(13, 12)
        self.cache.memory.write(14, 4)
        self.operations = ["add","sub","b","mul","mov","cmp","str","ldr"]
        # 0 : Inst,1:cond, 2:r0, 3:r1, 4:r2
        self.ops = [0 for i in range(out_size)]
        self.model = model
        self.ALU = ALU()
        self.functions = {}
        self.functions["READ"] = self.read
        self.functions["WRITE"] = self.write
        self.functions["ALU"] = self.alu
        self.functions["SET"] = self.sub_and_set
        self.functions["NO"] = self.noop
        self.functions["INCIN"] = self.inc_in
        self.functions["SETIN"] = self.set_in
        self.flag = 0
        self.pc_dist = np.array([0]*(self.num_regs-2)+[1,0])
        self.encoding = self.insts.read_gauss(self.ir)
        self.inc = True
Exemple #15
0
def mem_test():

    def mem_result_decimal(mem):
        return ALU.n_bit_binary_to_decimal(mem.read_result)

    mem = Memory(10, byte_size=BYTE_SIZE)

    mem.set_write_addr(ALU.int_to_n_bit_binary(0))
    mem.set_write_data(ALU.int_to_n_bit_binary(5, BYTE_SIZE))

    mem.set_mem_read(True)
    mem.set_address(ALU.int_to_n_bit_binary(0))

    assert mem_result_decimal(mem) == 0
    mem.set_mem_read(False)
    mem.set_mem_write(True)
    assert mem_result_decimal(mem) == 0
    mem.set_mem_read(True)
    assert mem_result_decimal(mem) == 5
    def __init__(self):
        self.pc = ALU.int_to_n_bit_binary(0)
        self.rd1 = ALU.int_to_n_bit_binary(0)
        self.rd2 = ALU.int_to_n_bit_binary(0)
        self.rs = ALU.int_to_n_bit_binary(0, 5)
        self.rt = ALU.int_to_n_bit_binary(0, 5)
        self.inst_imm = ALU.int_to_n_bit_binary(0, 16)
        self.inst_20_16 = ALU.int_to_n_bit_binary(0, 5)
        self.inst_rd = ALU.int_to_n_bit_binary(0, 5)

        self.wb_control = WB_CONTROL()
        self.mem_control = MEM_CONTROL()
        self.ex_control = EX_CONTROL()
    def __init__(self, inplanes, planes, stride=1, downsample=None, r=16):
        super(BasicBlock, self).__init__()
        self.conv1 = conv3x3(inplanes, planes, stride)
        self.bn1 = nn.BatchNorm2d(planes)
        self.alu = ALU(planes, r)
        # self.sc = ScaleLayer(planes)
        self.conv2 = conv3x3(planes, planes)
        self.bn2 = nn.BatchNorm2d(planes)

        self.downsample = downsample
        self.stride = stride
Exemple #18
0
 def __init__(self, dataBus, addressBus, controlBus):
     #Defining registers
     self.PC = PC()
     self.MAR = MAR()
     self.MDR = MDR()
     self.CIR = CIR()
     self.ACC = ACC()
     self.ALU = ALU(self.ACC)
     #Defining buses
     self.dataBus = dataBus
     self.addressBus = addressBus
     self.controlBus = controlBus
     self.opcode = {
         "add": self.add, 
         "store": self.storeACC, 
         "copy": self.copy,
         "input": self.input,
         "print": self.print,
         "load": self.load
     }
Exemple #19
0
def execute(words: List[int]):
    """In place of a full CPU model, execute the ALU on a
    sequence of instructions encoded as integers.
    """
    # We don't have the Register objects yet, so ...
    regs = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    alu = ALU()
    for word in words:
        log.debug("Decoding instruction word {}".format(word))
        instr = instr_format.decode(word)
        log.debug("Decoded to {}".format(instr))
        op = instr.op
        to_reg = instr.reg_target
        src_1 = instr.reg_src1
        src_2 = instr.reg_src2
        offset = instr.offset
        log.info("Executing {}".format(instr))
        result, condition = alu.exec(op, regs[src_1], regs[src_2] + offset)
        regs[to_reg] = result
        log.info("Computed value {}".format(result))
Exemple #20
0
    def __init__(self):
        self.used_ram = 0
        self.ram_size = 256
        self.ram = [0] * self.ram_size

        self.registers = [-1] * 8
        self.registers[interrupt_mask] = 0
        self.registers[interrupt_status] = 0
        self.registers[stack_pointer] = stack_start

        self.interupting = False
        self.last_timer = datetime.now()

        self.flags = {'E': 0, 'L': 0, 'G': 0}
        self.program_counter = -1

        alu = ALU(self)

        self.operations = {}
        self.operations[0b00000000] = self.NOP
        self.operations[0b00000001] = self.HLT
        self.operations[0b00010001] = self.RET
        self.operations[0b00010011] = self.IRET
        self.operations[0b01000101] = self.PUSH
        self.operations[0b01000110] = self.POP
        self.operations[0b01000111] = self.PRN
        self.operations[0b01001000] = self.PRA
        self.operations[0b01010000] = self.CALL
        self.operations[0b01010010] = self.INT
        self.operations[0b01010100] = self.JMP
        self.operations[0b01010101] = self.JEQ
        self.operations[0b01010110] = self.JNE
        self.operations[0b01010111] = self.JGT
        self.operations[0b01011000] = self.JLT
        self.operations[0b01011001] = self.JLE
        self.operations[0b01011010] = self.JGE
        self.operations[0b10000010] = self.LDI
        self.operations[0b10000011] = self.LD
        self.operations[0b10000100] = self.ST
        self.operations[0b10100000] = alu.ADD
        self.operations[0b10100001] = alu.SUB
        self.operations[0b10100010] = alu.MUL
        self.operations[0b10100011] = alu.DIV
        self.operations[0b10100100] = alu.MOD
        self.operations[0b10100101] = alu.INC
        self.operations[0b10100110] = alu.DEC
        self.operations[0b10100111] = alu.CMP
        self.operations[0b10101000] = alu.AND
        self.operations[0b10101001] = alu.NOT
        self.operations[0b10101010] = alu.OR
        self.operations[0b10101011] = alu.XOR
        self.operations[0b10101100] = alu.SHL
        self.operations[0b10101101] = alu.SHR
Exemple #21
0
    def __init__(self):
        self._instruction_memory = Memory(1024, byte_size=BYTE_SIZE)
        self._data_memory = Memory(32, byte_size=BYTE_SIZE)
        self._register_file = RegisterFile(32)
        self._alu = ALU()
        self._pc = ALU.int_to_n_bit_binary(0)

        self._end = False

        # pipe line registers
        self._if_id = IF_ID()
        self._if_id_tmp = IF_ID()

        self._id_ex = ID_EX()
        self._id_ex_tmp = ID_EX()

        self._ex_mem = EX_MEM()
        self._ex_mem_tmp = EX_MEM()

        self._mem_wb = MEM_WB()
        self._mem_wb_tmp = MEM_WB()
Exemple #22
0
    def _store_w(self, base_addr, word, memWrite=True):

        if not memWrite:
            return
        self._alu.set_input_1(base_addr)
        self._alu.set_op('00')

        for i in range(4):
            self._alu.set_input_2(ALU.int_to_n_bit_binary(i))
            addr = self._alu.result

            byte = tuple(word[i * 8: 8 * (i + 1)])
            self._data_memory.put(addr, byte)
Exemple #23
0
    def __init__(self, instructions, opcode, opcodeStr, arg1, arg1Str, arg2,
                 arg2Str, arg3, arg3Str, dataval, address, numInstructs,
                 destReg, src1Reg, src2Reg):
        self.instructions = instructions
        self.opcode = opcode
        self.dataval = dataval
        self.address = address
        self.numInstructs = numInstructs
        self.arg1 = arg1
        self.arg2 = arg2
        self.arg3 = arg3
        self.opcodeStr = opcodeStr
        self.arg1Str = arg1Str
        self.arg2Str = arg2Str
        self.arg3Str = arg3Str
        self.destReg = destReg
        self.src1Reg = src1Reg
        self.src2Reg = src2Reg
        self.specialMask = Masks.specialMask
        self.PC = 96
        self.cycle = 1
        self.R = [
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0
        ]
        self.postMEMbuff = [-1, -1]
        self.postALUbuff = [-1, -1]
        self.preMEMbuff = [-1, -1]
        self.preALUbuff = [-1, -1]
        self.preIssueBuff = [-1, -1, -1, -1]

        self.WB = WriteBack(self)
        self.mem = MEM(self)
        self.alu = ALU(self)
        self.cache = Cache(self.numInstructs, self.instructions, self.dataval,
                           self.address)
        self.issue = ISSUE(self)
        self.fetch = IF(self)
Exemple #24
0
    def __init__(self, n, byte_size=WORD, addr_size=WORD):
        """
        :param
            n: size of memory in bytes
        """
        self.data = {}
        self.size = n
        self.byte_size = byte_size
        self.addr_size = addr_size

        # initialize an array of memory with addresses starting from 0 to n - 1
        for i in range(n):
            self.data[ALU.int_to_n_bit_binary(
                i, addr_size)] = ALU.int_to_n_bit_binary(0, byte_size)

        # read write addresses
        self._address = ALU.int_to_n_bit_binary(0, addr_size)

        self.read_result = ALU.int_to_n_bit_binary(0, byte_size)
        self._write_data = ALU.int_to_n_bit_binary(0, byte_size)

        self._mem_read = False
        self._mem_write = False
Exemple #25
0
    def __init__(self):

        # 32 bit wide buses
        self.A = Bus("A", 32)
        self.B = Bus("B", 32)
        self.C = Bus("C", 32)

        # mir is a special 36 bit register
        self.mir = Register("MIR", 36, None, None, None)

        # arithmetic logic unit
        # creates its own shifter unit
        self.alu = ALU(self.A, self.B, self.C, self.mir)

        # registers
        self.registers = {"MAR" : Register("MAR", 32, None  , self.C, self.mir), # Memory Adress Register
                          "MDR" : Register("MDR", 32, self.B, self.C, self.mir), # Memory Data Register
                          "PC"  : Register("PC" , 32, self.B, self.C, self.mir), # Program Counter
                          "MBR" : Register("MBR",  8, self.B, None  , self.mir), # Memory Byte Register
                          "SP"  : Register("SP" , 32, self.B, self.C, self.mir), # Stack Pointer
                          "LV"  : Register("LV" , 32, self.B, self.C, self.mir), # Local Variable
                          "CPP" : Register("CPP", 32, self.B, self.C, self.mir), # Constant Pool Pointer
                          "TOS" : Register("TOS", 32, self.B, self.C, self.mir), # Top Of Stack
                          "OPC" : Register("OPC", 32, self.B, self.C, self.mir), # OPCode
                          "H"   : Register("H"  , 32, self.A, self.C, self.mir)}



        # control unit
        self.control = Control(self.registers["MBR"], self.mir, self.alu)

        # 2KB RAM
        self.ram = RAM(self.registers["MAR"],
                       self.registers["MDR"],
                       self.registers["PC"],
                       self.registers["MBR"],
                       self.mir)
Exemple #26
0
    def forwarding_unit(self):

        result = {
            'ForwardA': '00',
            'ForwardB': '00',
        }

        # EX Hazard
        if (self._ex_mem.wb_control.RegWrite
                and (self._ex_mem.reg_dest != ALU.int_to_n_bit_binary(0, 5))
                and (self._ex_mem.reg_dest == self._id_ex.rs)):
            result['ForwardA'] = '10'

        if (self._ex_mem.wb_control.RegWrite
                and (self._ex_mem.reg_dest != ALU.int_to_n_bit_binary(0, 5))
                and (self._ex_mem.reg_dest == self._id_ex.rt)):
            result['ForwardB'] = '10'

        # memory hazard
        if (
                self._mem_wb.wb_control.RegWrite
                and self._mem_wb.reg_dest != ALU.int_to_n_bit_binary(0, 5)
                and not (
                self._ex_mem.wb_control.RegWrite and (self._ex_mem.reg_dest != ALU.int_to_n_bit_binary(0, 5))
                and (self._ex_mem.reg_dest == self._id_ex.rs)
        )
                and (self._mem_wb.reg_dest == self._id_ex.rs)):
            result['ForwardA'] = '01'

        if (self._mem_wb.wb_control.RegWrite
                and (self._mem_wb.reg_dest != ALU.int_to_n_bit_binary(0, 5))
                and not (self._ex_mem.wb_control.RegWrite and (self._ex_mem.reg_dest != ALU.int_to_n_bit_binary(0, 5))
                         and (self._ex_mem.reg_dest == self._id_ex.rt))
                and (self._mem_wb.reg_dest == self._id_ex.rt)):
            result['ForwardB'] = '01'

        return result
Exemple #27
0
  def __init__(self, memoryFile):
    self.nCycles = 0 # Used to hold number of clock cycles spent executing instructions
    
    self.dataMemory = DataMemory(memoryFile)
    self.instructionMemory = InstructionMemory(memoryFile)
    self.registerFile = RegisterFile()
    self.alu = ALU()
    self.mainControl = MainControl()
    self.splitter = Splitter()
    self.signExtender = SignExtender()
    self.andGate = AndGate()
    self.breaker = Breaker()

    self.constant4 = Constant(4)
    # self.randomControl = RandomControl()
    self.pcMux1 = Mux()
    self.pcMux2 = Mux()
    self.regMux = Mux()
    self.aluMux = Mux()
    self.resultMux = Mux()
    self.luiMux = Mux()

    self.adder = Add()
    self.branchAdder = Add()

    self.jumpAddress = JMPAddress()
    self.shiftBranch = LeftShiftTwo()
    self.shiftJump = LeftShiftTwo()

    self.pc = PC(hex(0xbfc00000))  # hard coded "boot" address
    
    self.elements = [self.constant4, self.adder, self.instructionMemory, self.breaker, self.splitter,
                     self.shiftJump, self.mainControl, self.regMux, self.signExtender, self.luiMux, self.registerFile,
                     self.jumpAddress, self.shiftBranch, self.branchAdder, self.aluMux, self.alu, self.dataMemory,
                     self.andGate, self.pcMux1, self.pcMux2, self.resultMux, self.registerFile, self.pc]
    
    self._connectCPUElements()
Exemple #28
0
    def load_instructions(self, instructions):
        """
        load instructions from an array read from a file
        this is a helper function to initialize the instruction memory
        :param instructions:
        :return:
        """

        memory_cell_size = self._instruction_memory.byte_size

        # times needed to access the memory to fetch one word
        n = 4

        # start putting instruction into memory from address 0
        base_addr = ALU.int_to_n_bit_binary(0)

        self._instruction_memory.set_mem_write(True)

        for j in range(len(instructions)):
            instruction = instructions[j]
            inst = [int(c) for c in instruction.replace('\n', '').replace(' ', '').split(';')[0]]

            for i in range(n):
                # calculate write addr
                self._alu.set_input_1(base_addr)
                self._alu.set_input_2(ALU.int_to_n_bit_binary(i + j * n))
                self._alu.set_op('00')
                addr = self._alu.result

                # write data
                unit_data = tuple(inst[i * memory_cell_size: (i + 1) * memory_cell_size])

                self._instruction_memory.set_write_addr(addr)
                self._instruction_memory.set_write_data(unit_data)

        self._instruction_memory.set_mem_write(False)
Exemple #29
0
    def elaborate(self, platform: Platform) -> Module:
        m = Module()

        m.submodules.alu = self.alu = ALU()

        """Fetch the opcode, common for all instr"""
        m.d.sync += self.opcode.eq(Mux(self.cycle == 1, self.dout, self.opcode))

        with m.Switch(Mux(self.cycle == 1, self.dout, self.opcode)):
            for i in implemented.implemented:
                with m.Case(i.opcode):
                    i.synth(self, m)
            with m.Default():
                m.d.comb += core.alu.oper.eq(Operation.NOP)
                m.d.sync += [
                    core.reg.PC.eq(add16(core.reg.PC, 1)),
                    core.enable.eq(1),
                    core.addr.eq(add16(core.reg.PC, 1)),
                    core.RWB.eq(1),
                    core.cycle.eq(1),
                ]

        if self.verification is not None:
            self.verify(m)

            with m.If(Initial()):
                m.d.sync += [
                    self.reg.A.eq(AnyConst(8)),
                    self.reg.X.eq(AnyConst(8)),
                    self.reg.Y.eq(AnyConst(8)),
                    self.reg.SP.eq(AnyConst(16)),
                    self.reg.PC.eq(AnyConst(16)),
                ]
                m.d.sync += [
                    self.reg.PSW.N.eq(AnyConst(1)),
                    self.reg.PSW.V.eq(AnyConst(1)),
                    self.reg.PSW.P.eq(AnyConst(1)),
                    self.reg.PSW.B.eq(AnyConst(1)),
                    self.reg.PSW.H.eq(AnyConst(1)),
                    self.reg.PSW.I.eq(AnyConst(1)),
                    self.reg.PSW.Z.eq(AnyConst(1)),
                    self.reg.PSW.C.eq(AnyConst(1)),
                ]

        return m
Exemple #30
0
    def write_back(self, ex=True):
        pipeline_data = self._mem_wb

        if pipeline_data.wb_control.MemToReg:
            write_data = pipeline_data.read_data
        else:
            write_data = pipeline_data.alu_result

        # to be forwarded
        if not ex:
            return write_data

        # set register signals

        if pipeline_data.wb_control.RegWrite:
            if pipeline_data.reg_dest == (0, 0, 0, 1, 0):
                print("the: ", ALU.n_bit_binary_to_decimal(pipeline_data.pc))
            self._register_file.put(pipeline_data.reg_dest, write_data)
class Controller:
    def __init__(self):
        """Model of a standard contoller unit demonstrating the Texas 4-step (fetch,decode,execute,store) with methods for each."""
        self.R1 = 0  # General purpose register to store final result.
        self.R2 = 0  # General purpose register to store file length.
        self.R3 = ""  # Storage register to store mnemonic from memory.
        self.IR = 0  # Instruction register
        self.PC = 0  # Program counter/accumulator
        self.running = False  # Machine state
        self.clock = time.time()  # Start system clock
        self.ALU = ALU()  # Arithmetic-logic units
        self.MEM = Memory()  # System memory

    def loader(self, cfile):
        """Load file data into memory prior 4-step and store it into gp register R2."""
        io("Loading " + cfile + "...")
        self.R2 = self.MEM.loader(cfile)
        io("Processed: " + str(self.R2) + " lines.")
        io("Machine is running...")
        self.running = True

    def fetch(self):
        """Fetch next instruction stored in memory using PC address and store it into storage register R3."""
        self.R3 = self.MEM.read(self.PC)
        io("|FETCH|--> address(" + str(self.PC) + ")")
        io(">read(" + str(self.PC) + "->" + self.R3 + ")")

    def decode(self):
        """Decode data fetched. Determine if valid value or instruction, bump accumulator, and store in inst register IR."""
        self.PC += 1
        try:
            self.IR = int(self.R3)
            self.R3 = "push"
            io("\t|DECODE|--> decoding(" + str(self.IR) + ")...")
            io("\t>found operand(" + str(self.IR) + ")")
            io("\t>valid instruction")
        except ValueError:
            self.IR = self.R3
            io("\t|DECODE|--> decoding(" + self.IR + ")...")
            io("\t>found operator(" + self.IR + ")")
            io("\t>valid instruction")

    def execute(self):
        """Execute instruction fetched from memory and operate/manage stack memory."""
        op = self.R3
        if op == "push":
            io("\t\t|EXECUTE|--> " + op)
            io("\t\t>pushed(" + str(self.IR) + ")")
            self.MEM.push(self.IR)
        else:
            op1, op2 = self.MEM.pop()
            io("\t\t|EXECUTE|--> " + op + "(" + str(op1) + "," + str(op2) + ")")
            io("\t\t>pop  <-(" + str(op1) + ")")
            io("\t\t>pop  <-(" + str(op2) + ")")
            self.R1 = self.ALU.operate(op, op1, op2)
            io("\t\t>push ->(" + str(self.R1) + ")")
            self.MEM.push(self.R1)

    def store(self):
        """Store resulting data, output value that is stored in register."""
        io("\t\t\t|STORE|--> storing(" + str(self.R1) + ")")

    def run(self):
        """Start steppin. Begin the Texas 4-step, calculate/display the total processing time, and display final result."""
        while self.running and self.PC < self.R2:
            io("=" * 62)
            self.fetch()
            self.decode()
            self.execute()
            self.store()
        io(
            "=" * 62
            + "\nResult:\t"
            + str(self.R1)
            + "\nTime  :\t"
            + str(round(time.time() - self.clock, 4))
            + " s\n"
            + "=" * 62
        )
 def __init__(self):
     """Model of a standard contoller unit demonstrating the Texas 4-step (fetch,decode,execute,store) with methods for each."""
     self.R1 = 0  # General purpose register to store final result.
     self.R2 = 0  # General purpose register to store file length.
     self.R3 = ""  # Storage register to store mnemonic from memory.
     self.IR = 0  # Instruction register
     self.PC = 0  # Program counter/accumulator
     self.running = False  # Machine state
     self.clock = time.time()  # Start system clock
     self.ALU = ALU()  # Arithmetic-logic units
     self.MEM = Memory()  # System memory