From 8de3e8ee91dd3a31d5b71b4b001a1ca5ed4cd9bd Mon Sep 17 00:00:00 2001
From: Navid Rahimi <navidrahimi@microsoft.com>
Date: Wed, 1 Dec 2021 00:00:54 -0800
Subject: [PATCH] tree-optimization/103514 Missing XOR-EQ-AND Optimization

	* match.pd (a & b) == (a ^ b) -> !(a | b): New optimization.
	* match.pd (a & b) ^ (a == b) -> !(a | b): New optimization.

	* gcc.dg/tree-ssa/pr102232.c: Testcase for this optimization.
---
 gcc/match.pd                             | 10 +++++
 gcc/testsuite/gcc.dg/tree-ssa/pr103514.c | 56 ++++++++++++++++++++++++
 2 files changed, 66 insertions(+)
 create mode 100644 gcc/testsuite/gcc.dg/tree-ssa/pr103514.c

diff --git a/gcc/match.pd b/gcc/match.pd
index d467a1c4e45..2e2958f608e 100644
--- a/gcc/match.pd
+++ b/gcc/match.pd
@@ -1768,6 +1768,16 @@ DEFINE_INT_AND_FLOAT_ROUND_FN (RINT)
  (negate (nop_convert? (bit_not @0)))
  (plus (view_convert @0) { build_each_one_cst (type); }))
 
+/* (a & b) ^ (a == b) -> !(a | b) */
+/* (a & b) == (a ^ b) -> !(a | b) */
+(for first_op (bit_xor eq)
+     second_op (eq bit_xor)
+ (simplify
+  (first_op:c (bit_and:c @0 @1) (second_op:c @0 @1))
+   (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
+        && types_match (TREE_TYPE (@0), TREE_TYPE (@1)))
+    (convert (bit_not (bit_ior @0 @1))))))
+
 /* Convert ~ (A - 1) or ~ (A + -1) to -A.  */
 (simplify
  (bit_not (convert? (minus @0 integer_each_onep)))
diff --git a/gcc/testsuite/gcc.dg/tree-ssa/pr103514.c b/gcc/testsuite/gcc.dg/tree-ssa/pr103514.c
new file mode 100644
index 00000000000..b46d033a36c
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/tree-ssa/pr103514.c
@@ -0,0 +1,56 @@
+/* { dg-do compile } */
+/* { dg-options "-O -fdump-tree-optimized" } */
+#include <stdbool.h>
+
+bool
+b (bool a, bool b)
+{
+    return (a && b) == (a ^ b);
+}
+
+bool
+b_reverse (bool a, bool b)
+{
+     return (a && b) ^ (a == b);
+}
+
+int
+i (int a, int b)
+{
+     return (a & b) ^ (a == b);
+}
+
+int
+i_reverse (int a, int b)
+{
+     return (a & b) == (a ^ b);
+}
+
+long
+l (long a, long b)
+{
+     return (a & b) ^ (a == b);
+}
+
+long
+l_reverse (long a, long b)
+{
+     return (a & b) == (a ^ b);
+}
+
+unsigned int
+ui (unsigned int a, unsigned int b)
+{
+     return (a & b) ^ (a == b);
+}
+
+unsigned int
+ui_reverse (unsigned int a, unsigned int b)
+{
+     return (a & b) == (a ^ b);
+}
+
+/* Make sure we have removed "==" and "^" and "&". */
+/* { dg-final { scan-tree-dump-not "&" "optimized"} } */
+/* { dg-final { scan-tree-dump-not "\\^"  "optimized"} } */
+/* { dg-final { scan-tree-dump-not "==" "optimized"} } */
\ No newline at end of file
-- 
2.25.1

