My 99 740IL had a broke engine with 137K on it and I was not so fortune to get it for free.
What happen with your engine? Timing chain broke because of the excessive sludge/gunk?
I'm just curious. That was my case and it was not worth to rebuild.
You can fit an M5 engine there, but with the M5 needs to come with the computer too. And that computer has a different software for the transmission and related sensors. Transmission and additional parts might need an upgrade too. And you car is much heavier than an M5 and I don't know if you really can enjoy100% the beast of an M5. $5000 for that conversion I think is not enough. This is just my opinion though...
For $5000 you can buy a nice engine with low miles for a reasonable warranty(90days?). Or you can buy for less ($1500?) a junk one and have that rebuild. And you are good for many miles.
My case : I did all the work by myself. spent $2500 for an engine with 90K. Changed water pump many seals and gaskets.Engine after 15K runs very good, only problem with it is that does have a Vanos tapping which many out there have, and it might need an valve seals replacement in the future. Without doubt this engine will last another 100K the way it is.
Anyway , shop around and see what you can find. Use car-part.com to find used parts.