Ported Optimize from NCloak.