我使用Forth进行交互式调试和基于FPGA的硬件的自动初始化(请参见https://github.com/wzab/AFCK_J1B_FORTH)。 上一次我开始在可通过IPbus或Wishbone总线访问的寄存器中添加对位域的支持。 以下是我对用于读取和写入位域的单词的实现:
\ This file implements bitfield operations
\ It assumes, that we have the bus access
\ words:
\ wb@ ( address -- val )
\ wb! ( val address -- )
\ The bitfield is defined by its mask
\ (the ones correspond to the bits used by the field)
\ and by its shift (position of the LSB in the cell)
: bf@ ( address mask shift -- val )
rot ( mask shift address )
wb@ ( mask shift val )
rot ( shift val mask )
and ( shift val )
swap ( val shift )
rshift ( val )
;
: bf! ( val address mask shift -- )
rot ( val mask shift address )
>r ( val mask shift ) ( R: address )
rot ( mask shift val ) ( R: address )
swap ( mask val shift ) ( R: address )
lshift ( mask val ) ( R: address )
over ( mask val mask ) ( R: address )
and ( mask val ) ( R: address )
swap invert ( val ^mask ) ( R: address )
r@ ( val ^mask address ) ( R: address )
wb@ ( val ^mask oldval ) ( R: address )
and ( val oldval-masked) ( R: address )
or ( val ) ( R: address )
r> ( val address )
wb!
;
上述实现似乎可行,但是恐怕不是最佳选择。 可以用更聪明的方式编写它们吗?但是,要求实现必须与Swapforth running on J1B CPU兼容。
答案 0 :(得分:3)
我不确定您希望获得什么样的改进。尽管可能更快,但是您对bf!
的定义过于单一,以至于不能像我一样维护。
从这些假设开始:
@
和!
的环境,您需要将它们替换为wb@
和wb!
我到达了以下代码:
\ duplicate existing bitfield information on stack
: bf_dup ( n1 n2 n3 -- n1 n2 n3 n1 n2 n3)
2dup 2>r ( n1 n2 n3 R: n2 n3)
rot dup >r -rot ( n1 n2 n3 R: n2 n3 n1)
r> 2r> ;
: bf@ ( address mask shift -- val) 2>r @ r> rshift r> and ;
: (mask-old-value) ( addr mask shift -- val) lshift invert swap @ and ;
: (trim-shift-new) ( val addr mask shift -- addr new-value )
2>r swap 2r> ( addr val mask shift)
-rot and ( addr shift val_masked)
swap lshift ;
: bf! ( val address mask shift -- ) bf_dup (mask-old-value) >r
(trim-shift-new)
r> or swap ! ;
使用以下定义,测试和实际应用这些词要容易得多
\ store address mask shift (zero-based) in this sequence
: bitfield create rot , swap , , does> dup @ swap cell+ dup @ swap cell+ @ ;
hex 2018 7 3 ( address mask shift) bitfield mybitfield