Skip to content

Suboptimal code generated for simple case statement

For the following code:

data DD = A1 | A2 | A3 | A4 | A5 

f2 :: DD -> Bool
f2 A1 = False
f2 A2 = True
f2 A3 = True
f2 A4 = True
f2 A5 = True

ghc 8.8.4 (at -O2) generates the following assembly code:

.Lc1dy_info:
.Lc1dy:
	andl $7,%ebx
	cmpq $5,%rbx     <<<  superfluous
	jae .Lc1dD       <<<  superfluous
.Lu1e0:
	cmpq $2,%rbx
	jae .Lc1dD
.Lc1dC:
	movl $ghczmprim_GHCziTypes_False_closure+1,%ebx
	addq $8,%rbp
	jmp *(%rbp)
.Lc1dD:
	movl $ghczmprim_GHCziTypes_True_closure+2,%ebx
	addq $8,%rbp
	jmp *(%rbp)
.Lc1dJ:
	movl $ZZZZ_f2_closure,%ebx
	jmp *-8(%r13)

The 2nd and 3rd instructions are superfluous. All we need here is the test against 2 and if we are greater or equal to 2 we can return True. Comparing against 5 does nothing.

Edited by Neo
To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information