Import optimization technique from new core.
Fix an issue with fast-forward in last commit.
Apply more of the last optimization technique.