Common subexpressions are not optimized to single one?

Simon Marlow simonmar at
Tue Dec 9 09:22:49 EST 2003

> I'm wondering about the optimization of ghc. I thought that since
> functions are pure in haskell, compiler can/do factorize common
> subexpressions when it optimizes a code.  But the result of 
> the following
> experiment looks negative; "g 10 100" is caluculated twice. 
> Am I missing something?  If not, 
> What prevents ghc from performing that optimization?
> Should I always factorize common subexpressions 
> manually(using let or where)? 

GHC *does* do common sub-expression elimination.  However it only
considers simple applicative subexpressions as candidates for commoning
up, and in your example it turns out that by the time the CSE pass runs,
various inlinings and transformations have happened which means that the
candidate expressions are quite large.

Perhaps we could run the CSE pass at an earlier stage, or perhaps it
should run twice - that's one of those tradeoffs between compilation
time and runtime.  Perhaps the extra pass should be done for -O2 only.
We'll look into it.

Thanks for the example, anyhow.


More information about the Haskell-Cafe mailing list