InsertBinop tries to find an appropriate instruction instead of
creating a new instruction. When it checks whether instruction is
the same as we need to create it ignores nuw/nsw/exact flags.
It leads to invalid behavior when poison instruction can be used
when it was not expected. Specifically, for example Expander
expands the SCEV built for instruction
%a = add i32 %v, 1
It is possible that InsertBinop can find an instruction
% b = add nuw nsw i32 %v, 1
and will use it instead of version w/o nuw nsw.
It is incorrect.
The patch conservatively ignores all instructions with any of
poison flags installed.
Good catch!
I think you also need to check for I having the exact bit set since it looks like InsertBinop is used for shifts and divisions as well.
Finally, please also add a TODO that we can be more aggressive here by piping in the flags for the SCEV expression whose expansion we want to insert (nsw/nuw/exact).