[5.2] SILCombine: fix a miscompile in the alloc_stack optimization which causes a use-after-free. #29890
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This is a cherry-pick from #29882
Explanation: This fixes a miscompile in the SILCombine optimization. When trying to remove a "dead" alloc_stack, the optimization didn't take into account that release-instructions could be moved over copy-instructions. This makes the alloc_stack the only instance which keeps an object alive. Removing the alloc_stack resulted in a release of an object, followed by a retain: exactly in the wrong order. The compiled code crashed.
Scope: It's difficult to scope. The bug is in the compiler since a very long time. The fact that we didn't see it earlier indicates that this miscompile is unlikely to actually happen. On the other hand it can really be almost any kind of swift source code which can trigger this bug.
Risk: Low. It's basically an additional bail-out condition for the optimization.
Issue: rdar://problem/59496027
Testing: I added a regression test.
Reviewer: @aschwaighofer