[llvm] [InstCombineCompares] Replace the sqrt in if-condition (PR #91707)

Matt Arsenault via llvm-commits llvm-commits at lists.llvm.org
Fri May 10 04:18:51 PDT 2024


================
@@ -8068,6 +8073,50 @@ Instruction *InstCombinerImpl::visitFCmpInst(FCmpInst &I) {
         return new FCmpInst(I.getSwappedPredicate(), X, NegC, "", &I);
   }
 
+  /// Try to sink the sqrt in this following case:
+  /// \code
+  /// tmp = sqrt(input)
+  /// if (tmp > cond)
+  ///   branch_without_tmp
+  /// else
+  ///   branch_with_tmp
+  /// ...
+  /// \endcode
+  /// Is optimized to:
+  /// \code
+  /// if (input > copysign(cond*cond, cond))
+  ///   branch_without_tmp
+  /// else
+  ///   tmp = sqrt(input)
+  ///   branch_with_tmp
+  /// ...
+  /// \endcode
+  /// Only call sqrt in the branch that needs the sqrt result,
+  /// not if it is not needed, reducing the number of calls to sqrt.
+  if (I.isFast() && ReplaceSqrtInIfCondition) {
+    // fcmp sqrt(X), sqrt(Y) => fcmp X, Y
----------------
arsenm wrote:

This doesn't require fast. The tricky case is the negative X or Y case. You can check nnan, or if the inputs are known-non-negative

https://github.com/llvm/llvm-project/pull/91707


More information about the llvm-commits mailing list