Opened 5 years ago

Closed 5 years ago

#7286 closed bug (fixed)

GHC doesn't optimise away primitive identity conversions

Reported by: rl Owned by: igloo
Priority: high Milestone: 7.8.1
Component: Compiler Version: 7.7
Keywords: Cc: dterei
Operating System: Unknown/Multiple Architecture: Unknown/Multiple
Type of failure: Compile-time performance bug Test Case:
Blocked By: Blocking:
Related Tickets: Differential Rev(s):
Wiki Page:


Here is a small example:

import Data.Char (ord)
import GHC.Base (unsafeChr)
import GHC.Word

foo :: Word8 -> Word8
foo = fromIntegral . ord . unsafeChr . fromIntegral

bar :: Word8 -> Word8
bar = baz . baz
    baz = fromIntegral . (fromIntegral :: Word8 -> Word)

GHC produces the following code:

foo =
  \ (x_arR :: Word8) ->
    case x_arR of _ { W8# x#_avQ ->
    W8# (narrow8Word# (int2Word# (ord# (chr# (word2Int# x#_avQ)))))

bar =
  \ (x_arR :: Word8) ->
    case x_arR of _ { W8# x#_avQ ->
    W8# (narrow8Word# (narrow8Word# x#_avQ))

This could be optimised if GHC knew that:

  • ord# (chr# x) = x
  • int2Word# (word2Int# x) = x
  • narrow8Word# (narrow8Word# x) = narrow8Word# x

There are a lot of similar rules so I'm not sure if enumerating them all in base is the way to go.

I assume the backend(s) will optimise all of this away but this is quite a lot of unnecessary intermediate code. This is taken from vector-bytestring so it actually happens in the wild.

Change History (5)

comment:1 Changed 5 years ago by dterei

Cc: dterei added

comment:2 Changed 5 years ago by simonpj

difficulty: Unknown
Owner: set to igloo

comment:3 Changed 5 years ago by simonpj

Milestone: 7.8.1
Priority: normalhigh

comment:4 Changed 5 years ago by ian@…

commit e3d78899ce336e8637ae231550c04f0f68bca2aa

Author: Ian Lynagh <>
Date:   Sun Oct 21 13:48:09 2012 +0100

    Add some more primop rules; fixes #7286
    As well as the rules mentioned in the ticket, I've also gone through
    and added some more rules that might be useful in other cases.

 compiler/prelude/PrelRules.lhs |   56 ++++++++++++++++++++++++++++++++--------
 1 files changed, 45 insertions(+), 11 deletions(-)

comment:5 Changed 5 years ago by igloo

Resolution: fixed
Status: newclosed

Thanks for the report; fixed.

Note: See TracTickets for help on using tickets.