Unless the lease is worth more than the residual at the end of the lease, the two processes can be completely unrelated.
You simply turn in the lease, and go about buying the M4 as you would in any other circumstance.
If the lease car is worth MORE than the residual, you can shop the lease around and see if anyone will buy it from you for a few K more. If you can find some buyers you can either sell it, or use the equity against an M4 purchase if the dealer will play ball.
In most cases though once you turn in the car your obligation and dealings with that undertaking are over, and you go about buying or leasing something else separately.