Similar to GVN in D14004: While processing instructions in InstCombine, mark global variables and alloca instructions corresponding to each encountered invariant intrinsic call as indicating 'writeonce' memory locations that either have been written into or can be written into again (once). Then, while scanning instructions backwards looking for available loads for a given memory location, be sure to temporarily disable or reset the markings, as appropriate.
This patch is a break-down of (corrected) D13606.
Why bother? We're guaranteed to visit the invariant.start and the invariant.end, right? Just handle invariant_start by replacing it with an undef, and let the generic "EraseInstFromFunction" call (below on line 1975) handle the invariant.end?
I think the other case is an invariant applying to a bitcast instead of to the original object. Does this function work in that case? (Does it even pass isAllocSiteRemovable?)