common-subexpression elimination (cse)
Stephen Weeks
MLton@sourcelight.com
Tue, 24 Jul 2001 16:05:55 -0700
--zHkd1lCaSw
Content-Type: text/plain; charset=us-ascii
Content-Description: message body text
Content-Transfer-Encoding: 7bit
> But that (just replacing latter occurances with the name bound to the first
> result) isn't always correct.
Let me be more precise. The later occurrences are replaced if the primitive is
functional (or may overflow) and the first occurrence dominates them in the
intraprocedural control-flow graph. I believe this is safe.
> There is, of course, side effect things which
> have to be duplicated, but the more serious example I was talking about was
> the delay due to lambda.
>
> Consider something like
>
> let val magic: (unit -> int) option ref = ref NONE
> fun f x =
> (magic := SOME (fn () => 1 div x);
> 1 div x)
> in f 0
> handle _ => 0;
> valOf (! magic) ()
> end
>
> You have to raise the exception twice.
Agreed. MLton simplifies this quite nicely. Just to show off my fine new
control-flow graph feature, here is the control-flow graph that MLton produces
(not suitable for printing, just for viewing). The important stuff is near the
top, starting at L_38.
--zHkd1lCaSw
Content-Type: application/octet-stream
Content-Disposition: attachment;
filename="z.sml.main_0.dot"
Content-Transfer-Encoding: base64
ZGlncmFwaCAibWFpbl8wIiB7CmxhYmVsID0gIm1haW5fMCI7IHsgcmFuayAgPSAibWluIjsgbjAg
fQpuMSBbbGFiZWwgPSAiTF81KHhfNTEpIFtMXzVdXGxIYW5kbGVyUG9wXGx4XzUzID0gU3RkaW9f
cHJpbnQgKFwiVG9wbGV2ZWwgaGFuZGxlciByYWlzZWQgZXhjZXB0aW9uLlxuXCIpXGx4XzUyID0g
TUx0b25faGFsdCAoMSlcbHJldHVybiAoKVxsIiwgc2hhcGUgPSAiYm94Il0KbjIgW2xhYmVsID0g
IkxfOCgpIFtdXGxMXzQgKFwiT3ZlcmZsb3dcIilcbCIsIHNoYXBlID0gImJveCJdCm4yIC0+IG4z
IFtsYWJlbCA9ICIiLCBzdHlsZSA9ICJzb2xpZCJdCm40IFtsYWJlbCA9ICJMXzEwKCkgW11cbExf
NCAoXCJEaXZcIilcbCIsIHNoYXBlID0gImJveCJdCm40IC0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