Related to bugzilla 33731 https://bugs.llvm.org/show_bug.cgi?id=33731
This is caused by a a PRE insertion when the predecessor block hasn't yet been through Value Numbering (due to a back-edge).
The PRE insertion adds a duplicate instruction at the end of the block, but the already-existing instruction is already used in the predecessor block, like so:
L.LB1_346: ; preds = %L.LB1_423
%7 = sext i32 %2 to i64 %8 = mul i64 %7, 4
- %.pre = sext i32 %1 to i64** ; inserted by GVN::performScalarPREInsertion
When we then iterate over this block (later in the pass), GVN chooses to delete the first instance of the instruction as it is duplicated (instead of the later one which was created before). This is because "GVN::performScalarPREInsertion" will number the instruction as it is created (so it is in the leader-list).
The attached patch moves the "%.pre" instruction up so that the replacement is valid.
I am not sure this is a valid fix, but I couldn't figure out another solution.
I though about stoping "GVN::performScalarPREInsertion" from inserting the instruction by numbering the BasicBlock, but that might lead to infinite loops. I also tried to stop PREInsertion from running if the BasicBlock had not been numbered yet (by keeping a list of numbered blocks) but that wouldn't work since GVN only does one pass over the function (so this case would never be optimised out).
The patch does fix the bug though, without adding regressions.