Skip to content

Commit

Permalink
[InstCombine] Prevent infinite loop with two shifts
Browse files Browse the repository at this point in the history
The following pattern: `(C2 << X) << C1` will usually be
transformed into `(C2 << C1) << X`, essentially swapping `X` and `C1`.

However, this should not only done when `C1` is an immediate constant, otherwise this
can lead to both constants being swapped forever

This fixes llvm#118798
  • Loading branch information
momo5502 committed Dec 5, 2024
1 parent ff78cd5 commit ddd039e
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
3 changes: 2 additions & 1 deletion llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -427,7 +427,8 @@ Instruction *InstCombinerImpl::commonShiftTransforms(BinaryOperator &I) {
if (Instruction *R = FoldOpIntoSelect(I, SI))
return R;

if (Constant *CUI = dyn_cast<Constant>(Op1))
Constant *CUI;
if (match(Op1, m_ImmConstant(CUI)))
if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
return Res;

Expand Down
16 changes: 16 additions & 0 deletions llvm/test/Transforms/InstCombine/shl-twice-constant.ll
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
; NOTE: Assertions have been autogenerated by utils/update_test_checks.py
; RUN: opt < %s -passes=instcombine -S | FileCheck %s

@c = external constant i8
@c2 = external constant i8

define i64 @testfunc() {
; CHECK-LABEL: @testfunc(
; CHECK-NEXT: [[SHL1:%.*]] = shl nuw i64 1, ptrtoint (ptr @c2 to i64)
; CHECK-NEXT: [[SHL2:%.*]] = shl i64 [[SHL1]], ptrtoint (ptr @c to i64)
; CHECK-NEXT: ret i64 [[SHL2]]
;
%shl1 = shl i64 1, ptrtoint (ptr @c2 to i64)
%shl2 = shl i64 %shl1, ptrtoint (ptr @c to i64)
ret i64 %shl2
}

0 comments on commit ddd039e

Please sign in to comment.