Skip to content

Commit

Permalink
got it mostly working now
Browse files Browse the repository at this point in the history
  • Loading branch information
AntonLydike committed Oct 9, 2023
1 parent 4481e0d commit 20637ee
Show file tree
Hide file tree
Showing 18 changed files with 648 additions and 597 deletions.
2 changes: 1 addition & 1 deletion examples/estimate-cpu-freq.asm
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ measure_loop:
fcvt.s.w ft1, t0 // ft1 = 1k
fdiv.s ft2, ft2, ft1 // ft2 = kins/sec

printf "executed {} instructions in {:.4f} seconds ({:.2f}ki/s)", s0, ft0, ft2
printf "executed {} instructions in {:.4f32} seconds ({:.2f32}ki/s)", s0, ft0, ft2
mv ra, s4
ret

Expand Down
2 changes: 1 addition & 1 deletion riscemu/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class RunConfig:
verbosity: int = 0
slowdown: float = 1
unlimited_registers: bool = False
flen: int = 32
flen: int = 64
# runtime config
use_libc: bool = False
ignore_exit_code: bool = False
Expand Down
78 changes: 39 additions & 39 deletions riscemu/core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,43 +47,43 @@
from .usermode_cpu import UserModeCPU

__all__ = [
T_RelativeAddress,
T_AbsoluteAddress,
T_ParserOpts,
NUMBER_SYMBOL_PATTERN,
ParseException,
NumberFormatException,
MemoryAccessException,
OutOfMemoryException,
LinkerException,
LaunchDebuggerException,
RiscemuBaseException,
InvalidRegisterException,
InvalidAllocationException,
InvalidSyscallException,
UnimplementedInstruction,
INS_NOT_IMPLEMENTED,
MemoryFlags,
UInt32,
Int32,
BaseFloat,
Float32,
Float64,
RTClock,
Instruction,
Immediate,
InstructionWithEncoding,
InstructionContext,
MemorySection,
Program,
ProgramLoader,
PrivModes,
MMU,
CSR,
Registers,
CPU,
SimpleInstruction,
InstructionMemorySection,
BinaryDataMemorySection,
UserModeCPU,
"T_RelativeAddress",
"T_AbsoluteAddress",
"T_ParserOpts",
"NUMBER_SYMBOL_PATTERN",
"ParseException",
"NumberFormatException",
"MemoryAccessException",
"OutOfMemoryException",
"LinkerException",
"LaunchDebuggerException",
"RiscemuBaseException",
"InvalidRegisterException",
"InvalidAllocationException",
"InvalidSyscallException",
"UnimplementedInstruction",
"INS_NOT_IMPLEMENTED",
"MemoryFlags",
"UInt32",
"Int32",
"BaseFloat",
"Float32",
"Float64",
"RTClock",
"Instruction",
"Immediate",
"InstructionWithEncoding",
"InstructionContext",
"MemorySection",
"Program",
"ProgramLoader",
"PrivModes",
"MMU",
"CSR",
"Registers",
"CPU",
"SimpleInstruction",
"InstructionMemorySection",
"BinaryDataMemorySection",
"UserModeCPU",
]
29 changes: 18 additions & 11 deletions riscemu/core/float.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def bytes(self) -> bytes:

@classmethod
def from_bytes(cls, val: Union[bytes_t, bytearray]):
return BaseFloat(val)
return cls(val)

def __init__(
self, val: Union[float, c_float, "BaseFloat", bytes_t, bytearray, int] = 0
Expand All @@ -41,8 +41,7 @@ def __init__(
self._val = self._type(val.value)
elif isinstance(val, (bytes, bytearray)):
self._val = self._type(struct.unpack("<" + self._struct_fmt_str, val)[0])
self._val = self._type(struct.unpack("<" + self._struct_fmt_str, val)[0])
elif isinstance(val, BaseFloat):
elif isinstance(val, self.__class__):
self._val = val._val
else:
raise ValueError(
Expand Down Expand Up @@ -105,9 +104,6 @@ def __repr__(self):
def __str__(self):
return str(self.value)

def __format__(self, format_spec: str):
return self.value.__format__(format_spec)

def __hash__(self):
return hash(self.value)

Expand All @@ -134,6 +130,12 @@ def __ge__(self, other: Any):
def __bool__(self):
return bool(self.value)

def __int__(self):
return int(self.value)

def __float__(self):
return self.value

def __pow__(self, power, modulo=None):
if modulo is not None:
raise ValueError("Float32 pow with modulo unsupported")
Expand Down Expand Up @@ -163,9 +165,12 @@ def __rmod__(self, other: Any):
def bitcast(cls, f: "BaseFloat") -> "BaseFloat":
"""
bitcast the struct up or down to another type.
Fills upper bits with zero.
Use Float64.bitcast(Float32(...)) to bitcast a f32 to f64
"""
if isinstance(f, cls):
return f
return cls.from_bytes((b"\x00\x00\x00\x00\x00\x00\x00\x00" + f.bytes)[-struct.calcsize(cls._struct_fmt_str):])

@classmethod
Expand All @@ -176,16 +181,18 @@ def flen_to_cls(cls, bits: int) -> type['BaseFloat']:
return Float64
raise ValueError(f"Unsupported flen: {bits}")

def __format__(self, spec: str):
if spec[-2:] == '32':
return Float32.bitcast(self).__format__(spec[:-2])
if spec[-2:] == '64':
return Float64.bitcast(self).__format__(spec[:-2])
return format(self.value, spec)


class Float32(BaseFloat):
_type = c_float
_struct_fmt_str = 'f'

@classmethod
def bitcast(cls, f: "BaseFloat") -> "BaseFloat":
if isinstance(f, Float32):
return f


class Float64(BaseFloat):
_type = c_double
Expand Down
2 changes: 1 addition & 1 deletion riscemu/core/registers.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ def get_f(self, reg: str, mark_read: bool = True) -> BaseFloat:
def set_f(self, reg: str, val: Union[float, BaseFloat]):
if not self.infinite_regs and reg not in self.float_regs:
raise RuntimeError("Invalid float register: {}".format(reg))
self.float_vals[reg] = self._float_type(val)
self.float_vals[reg] = self._float_type.bitcast(val)

@staticmethod
def named_registers():
Expand Down
2 changes: 1 addition & 1 deletion riscemu/debug.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def cont(verbose=False):

def step():
try:
cpu.step()
cpu.step(verbose=True)
except LaunchDebuggerException:
return

Expand Down
20 changes: 20 additions & 0 deletions riscemu/instructions/RV32D.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
"""
RiscEmu (c) 2023 Anton Lydike
SPDX-License-Identifier: MIT
This file contains copious amounts of docstrings that were all taken
from https://msyksphinz-self.github.io/riscv-isadoc/html/rvfd.html
(all the docstrings on the instruction methods documenting the opcodes
and their function)
"""
from typing import Tuple

from .instruction_set import InstructionSet, Instruction
from .float_base import FloatArithBase
from riscemu.core import INS_NOT_IMPLEMENTED, Float32, Int32, UInt32, Float64


class RV32D(FloatArithBase[Float64]):
flen = 64
_float_cls = Float64
Loading

0 comments on commit 20637ee

Please sign in to comment.