Skip to content

Commit

Permalink
Fix endless loop in optimizePhiConst with integer constant switch con…
Browse files Browse the repository at this point in the history
…dition

Avoid endless loop in degenerate case with an integer constant as switch
condition as reported in https://reviews.llvm.org/D124552
  • Loading branch information
MatzeB committed May 11, 2022
1 parent e663537 commit de9ad98
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
6 changes: 5 additions & 1 deletion llvm/lib/CodeGen/CodeGenPrepare.cpp
Expand Up @@ -7037,9 +7037,13 @@ bool CodeGenPrepare::optimizeSwitchPhiConstants(SwitchInst *SI) {
// change the code to:
// switch(x) { case 42: phi(x, ...) }

Value *Condition = SI->getCondition();
// Avoid endless loop in degenerate case.
if (isa<ConstantInt>(*Condition))
return false;

bool Changed = false;
BasicBlock *SwitchBB = SI->getParent();
Value *Condition = SI->getCondition();
Type *ConditionType = Condition->getType();

for (const SwitchInst::CaseHandle &Case : SI->cases()) {
Expand Down
29 changes: 29 additions & 0 deletions llvm/test/Transforms/CodeGenPrepare/X86/switch-phi-const.ll
Expand Up @@ -126,3 +126,32 @@ case_13:
default:
ret void
}

define void @switch_phi_const_degenerate() {
; CHECK-LABEL: @switch_phi_const_degenerate(
; CHECK-NEXT: bb0:
; CHECK-NEXT: br i1 undef, label [[CASE_42:%.*]], label [[BB1:%.*]]
; CHECK: bb1:
; CHECK-NEXT: br label [[CASE_42]]
; CHECK: case_42:
; CHECK-NEXT: [[X:%.*]] = phi i32 [ 0, [[BB0:%.*]] ], [ 42, [[BB1]] ]
; CHECK-NEXT: store volatile i32 [[X]], i32* @effect, align 4
; CHECK-NEXT: ret void
;
bb0:
br i1 undef, label %case_42, label %bb1

bb1:
switch i32 42, label %unreachable [
i32 42, label %case_42
]

case_42:
; We should not end up in an endless loop 42 with the switch condition 42.
%x = phi i32 [0, %bb0], [42, %bb1]
store volatile i32 %x, i32* @effect, align 4
ret void

unreachable:
unreachable
}

0 comments on commit de9ad98

Please sign in to comment.