From bb16c311ef921b6d3525d6c81afb38a853a5cfa9 Mon Sep 17 00:00:00 2001 From: Juneyoung Lee Date: Tue, 30 Mar 2021 20:03:50 +0900 Subject: [PATCH] [LoopUnswitch] Simplify branch condition if it is select with constant operands This fixes the miscompilation reported in https://reviews.llvm.org/rG5bb38e84d3d0#986154 . `select _, true, false` matches both m_LogicalAnd and m_LogicalOr, making later transformations confused. Simplify the branch condition to not have the form. --- lib/Transforms/Scalar/SimpleLoopUnswitch.cpp | 7 +++++++ test/Transforms/SimpleLoopUnswitch/nontrivial-unswitch.ll | 4 ++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp b/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp index cf77cf70e32..2e1c0dee32d 100644 --- a/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp +++ b/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp @@ -2645,6 +2645,13 @@ unswitchBestCondition(Loop &L, DominatorTree &DT, LoopInfo &LI, BI->getSuccessor(0) == BI->getSuccessor(1)) continue; + // If BI's condition is 'select _, true, false', simplify it to confuse + // matchers + Value *Cond = BI->getCondition(), *CondNext; + while (match(Cond, m_Select(m_Value(CondNext), m_One(), m_Zero()))) + Cond = CondNext; + BI->setCondition(Cond); + if (L.isLoopInvariant(BI->getCondition())) { UnswitchCandidates.push_back({BI, {BI->getCondition()}}); continue; diff --git a/test/Transforms/SimpleLoopUnswitch/nontrivial-unswitch.ll b/test/Transforms/SimpleLoopUnswitch/nontrivial-unswitch.ll index bfbe3e65daa..58950835d58 100644 --- a/test/Transforms/SimpleLoopUnswitch/nontrivial-unswitch.ll +++ b/test/Transforms/SimpleLoopUnswitch/nontrivial-unswitch.ll @@ -4248,7 +4248,7 @@ loop_begin: ; CHECK-NEXT: %[[V2:.*]] = load i1, i1* %ptr2 ; CHECK-NEXT: %[[AND1:.*]] = select i1 %[[V1]], i1 true, i1 false ; CHECK-NEXT: %[[AND2:.*]] = select i1 %[[AND1]], i1 true, i1 false -; CHECK-NEXT: br i1 %[[AND2]], label %loop_a, label %loop_b +; CHECK-NEXT: br i1 %[[V1]], label %loop_a, label %loop_b loop_a: call i32 @a() @@ -4326,7 +4326,7 @@ loop_begin: ; CHECK-NEXT: %[[V2:.*]] = load i1, i1* %ptr2 ; CHECK-NEXT: %[[AND1:.*]] = select i1 %[[V1]], i1 true, i1 false ; CHECK-NEXT: %[[AND2:.*]] = select i1 %[[AND1]], i1 true, i1 false -; CHECK-NEXT: br i1 %[[AND2]], label %loop_b, label %loop_a +; CHECK-NEXT: br i1 %[[V1]], label %loop_b, label %loop_a loop_a: call i32 @a()