我有以下程序将6位ASCII格式转换为二进制格式。
ascii2bin :: Char -> B.ByteString
ascii2bin = B.reverse . fst . B.unfoldrN 6 decomp . to6BitASCII -- replace to6BitASCII with ord if you want to compile this
where decomp n = case quotRem n 2 of (q,r) -> Just (chr r,q)
bs2bin :: B.ByteString -> B.ByteString
bs2bin = B.concatMap ascii2bin
这会产生以下核心段:
Rec {
$wa
$wa =
\ ww ww1 ww2 w ->
case ww2 of wild {
__DEFAULT ->
let {
wild2
wild2 = remInt# ww1 2 } in
case leWord# (int2Word# wild2) (__word 1114111) of _ {
False -> (lvl2 wild2) `cast` ...;
True ->
case writeWord8OffAddr#
ww 0 (narrow8Word# (int2Word# (ord# (chr# wild2)))) w
of s2 { __DEFAULT ->
$wa (plusAddr# ww 1) (quotInt# ww1 2) (+# wild 1) s2
}
};
6 -> (# w, (lvl, lvl1, Just (I# ww1)) #)
}
end Rec }
注意ord . chr == id
,因此这里有一个冗余操作:narrow8Word# (int2Word# (ord# (chr# wild2)))
有没有理由GHC不必要地转换为Int - > Char - > Int,或者这是一个代码生成不良的例子?这可以优化吗?
编辑:这是使用GHC 7.4.2,我没有尝试编译任何其他版本。我发现问题仍然存在于GHC 7.6.2中,但是在github上的当前HEAD分支中删除了冗余操作。答案 0 :(得分:19)
有没有理由GHC不必要地从
Int -> Char -> Int
转换,或者这是一个代码生成不良的例子?这可以优化吗?
不是真的(对两者而言)。从-ddump-simpl
获得的核心不是结束。在通往汇编代码的途中,仍然有一些优化和转换。但是在这里删除冗余转换实际上并不是一种优化。
它们可以在核心和组件之间移除。关键在于这些原始 - 除了缩小 - 都是无操作,它们只存在于核心,因为它是键入的。由于它们是无操作,因此核心中是否存在冗余链并不重要。
7.6.1从代码生成的程序集[它比7.4.2产生的更可读,所以我接受了] - 使用ord
代替to6BitASCII
- 是
ASCII.$wa_info:
_cXT:
addq $64,%r12
cmpq 144(%r13),%r12
ja _cXX
movq %rdi,%rcx
cmpq $6,%rdi
jne _cXZ
movq $GHC.Types.I#_con_info,-56(%r12)
movq %rsi,-48(%r12)
movq $Data.Maybe.Just_con_info,-40(%r12)
leaq -55(%r12),%rax
movq %rax,-32(%r12)
movq $(,,)_con_info,-24(%r12)
movq $lvl1_rVq_closure+1,-16(%r12)
movq $lvl_rVp_closure+1,-8(%r12)
leaq -38(%r12),%rax
movq %rax,0(%r12)
leaq -23(%r12),%rbx
jmp *0(%rbp)
_cXX:
movq $64,192(%r13)
_cXV:
movl $ASCII.$wa_closure,%ebx
jmp *-8(%r13)
_cXZ:
movl $2,%ebx
movq %rsi,%rax
cqto
idivq %rbx
movq %rax,%rsi
cmpq $1114111,%rdx
jbe _cY2
movq %rdx,%r14
addq $-64,%r12
jmp GHC.Char.chr2_info
_cY2:
movb %dl,(%r14)
incq %r14
leaq 1(%rcx),%rdi
addq $-64,%r12
jmp ASCII.$wa_info
.size ASCII.$wa_info, .-ASCII.$wa_info
narrow8Word# (int2Word# (ord# (chr# wild2)))
出现在核心中的部分位于cmpq $1114111, %rdx
之后。如果商不超出范围,则代码将跳转到_cY2
,不再包含此类转换。一个字节写入数组,一些指针/计数器递增,就是这样,跳回到顶部。
我认为可以从GHC目前产生更好的代码,但冗余的无操作转换已经消失。