Note: This is a corrected version of an approach previously reviewed in http://reviews.llvm.org/D13070, landed, and reverted due to a problem with control dependence and nsw flags.
The main change in this patch over the previous approach is to explicitly check for possible control dependent flags in the BB we're considering flattening which might influence the condition of the second branch. I believe this is sufficient to prevent the problematic case, but it does end up making the transform less powerful.
I also had to add a bit of logic to the implies reasoning to handle the simpler test cases I want to introduce. This logic could arguable by separated, but I kept it together to show the motivation.
- Original Review Comments --
If we have a series of branches which are all unlikely to fail, we can possibly combine them into a single check on the fastpath combined with a bit of dispatch logic on the slowpath. We don't want to do this unconditionally since it requires speculating instructions past a branch, but if the profiling metadata on the branch indicates profitability, this can reduce the number of checks needed along the fast path.
The canonical example this is trying to handle is removing the second bounds check implied by the Java code: a[i] + a[i+1]. Note that it can currently only do so for really simple conditions and the values of a[i] can't be used anywhere except in the addition. (i.e. the load has to have been sunk already and not prevent speculation.)
Should these two conditions swapped in this example or change > to < ?