[MustExec][LICM] Handle latch being part of an inner cycle (PR57780)
authorNikita Popov <npopov@redhat.com>
Tue, 20 Sep 2022 11:04:27 +0000 (13:04 +0200)
committerNikita Popov <npopov@redhat.com>
Tue, 11 Oct 2022 07:30:13 +0000 (09:30 +0200)
The algorithm in allLoopPathsLeadToBlock() does not handle the case
where the loop latch is part of the predecessor set correctly: In
this case, we may take the backedge (escaping to a different loop
iteration) and not execute other latch successors. This can happen
if the latch is part of an inner cycle.

Fixes https://github.com/llvm/llvm-project/issues/57780.

Differential Revision: https://reviews.llvm.org/D134279

llvm/lib/Analysis/MustExecute.cpp
llvm/test/Analysis/MustExecute/pr57780.ll
llvm/test/Transforms/LICM/pr57780.ll

index 6296f58..8a6318e 100644 (file)
@@ -201,6 +201,15 @@ bool LoopSafetyInfo::allLoopPathsLeadToBlock(const Loop *CurLoop,
   SmallPtrSet<const BasicBlock *, 4> Predecessors;
   collectTransitivePredecessors(CurLoop, BB, Predecessors);
 
+  // Bail out if a latch block is part of the predecessor set. In this case
+  // we may take the backedge to the header and not execute other latch
+  // successors.
+  for (const BasicBlock *Pred : predecessors(CurLoop->getHeader()))
+    // Predecessors only contains loop blocks, so we don't have to worry about
+    // preheader predecessors here.
+    if (Predecessors.contains(Pred))
+      return false;
+
   // Make sure that all successors of, all predecessors of BB which are not
   // dominated by BB, are either:
   // 1) BB,
index a7b47a1..b044408 100644 (file)
@@ -2,9 +2,8 @@
 
 @c = global i16 0, align 2
 
-; FIXME: miscompile
 ; CHECK-LABEL: define void @latch_cycle_irreducible
-; CHECK: store i16 5, ptr @c, align 2 ; (mustexec in: loop)
+; CHECK: store i16 5, ptr @c, align 2{{$}}
 define void @latch_cycle_irreducible() {
 entry:
   br label %loop
@@ -28,9 +27,8 @@ loop.exit:                                        ; preds = %loop
   ret void
 }
 
-; FIXME: miscompile
 ; CHECK-LABEL: define void @latch_cycle_reducible
-; CHECK: store i16 5, ptr @c, align 2 ; (mustexec in: loop)
+; CHECK: store i16 5, ptr @c, align 2{{$}}
 define void @latch_cycle_reducible() {
 entry:
   br label %loop
index 89f48ed..2c075e9 100644 (file)
@@ -7,7 +7,6 @@
 define void @test() {
 ; CHECK-LABEL: @test(
 ; CHECK-NEXT:  entry:
-; CHECK-NEXT:    store i16 5, ptr @c, align 2
 ; CHECK-NEXT:    br label [[LOOP:%.*]]
 ; CHECK:       loop:
 ; CHECK-NEXT:    [[V:%.*]] = phi i32 [ 10, [[ENTRY:%.*]] ], [ 0, [[LOOP_LATCH:%.*]] ]
@@ -16,6 +15,7 @@ define void @test() {
 ; CHECK:       loop.cont:
 ; CHECK-NEXT:    br i1 false, label [[LOOP_IRREDUCIBLE:%.*]], label [[LOOP_LATCH]]
 ; CHECK:       loop.irreducible:
+; CHECK-NEXT:    store i16 5, ptr @c, align 2
 ; CHECK-NEXT:    br label [[LOOP_LATCH]]
 ; CHECK:       loop.latch:
 ; CHECK-NEXT:    br i1 false, label [[LOOP_IRREDUCIBLE]], label [[LOOP]]