diff --git a/gcc/ChangeLog b/gcc/ChangeLog
index 9659fbf7f5d16ad7c61b662f43a6a14b17e7f031..02a286806ee79d3ecbb6909a2b62ea6bf391cf68 100644
--- a/gcc/ChangeLog
+++ b/gcc/ChangeLog
@@ -1,3 +1,11 @@
+2016-10-09  Jakub Jelinek  <jakub@redhat.com>
+
+	PR tree-optimization/77901
+	* tree-ssa-reassoc.c (optimize_range_tests_var_bound): Only optimize
+	if ranges[i].exp is SSA_NAME when looking for >= and only when
+	ranges[i].exp is NULL or SSA_NAME when looking for the other
+	comparison.
+
 2016-10-09  Prathamesh Kulkarni  <prathamesh.kulkarni@linaro.org>
 
 	* ipa-cp.c (ipcp_alignment_lattice): Remove.
diff --git a/gcc/testsuite/ChangeLog b/gcc/testsuite/ChangeLog
index 4e69c4dddf595cf63d8dfc6c10e7f3d7e11219d2..ec2825978a3bc72cbac579dda1f3445d9d4fddd1 100644
--- a/gcc/testsuite/ChangeLog
+++ b/gcc/testsuite/ChangeLog
@@ -1,3 +1,8 @@
+2016-10-09  Jakub Jelinek  <jakub@redhat.com>
+
+	PR tree-optimization/77901
+	* gcc.c-torture/compile/pr77901.c: New test.
+
 2016-10-09  Prathamesh Kulkarni  <prathamesh.kulkarni@linaro.org>
 
 	* gcc.dg/ipa/propalign-1.c: Adjust scan-ipa-dump.
diff --git a/gcc/testsuite/gcc.c-torture/compile/pr77901.c b/gcc/testsuite/gcc.c-torture/compile/pr77901.c
new file mode 100644
index 0000000000000000000000000000000000000000..5c3936af65ad3c91bb68d6f3cd5912d1ccf7d50e
--- /dev/null
+++ b/gcc/testsuite/gcc.c-torture/compile/pr77901.c
@@ -0,0 +1,10 @@
+/* PR tree-optimization/77901 */
+
+void bar (void);
+
+void
+foo (int *x, long *y)
+{
+  if (*y && *x != 10 && *x != 12 && *y >= 0)
+    bar ();
+}
diff --git a/gcc/tree-ssa-reassoc.c b/gcc/tree-ssa-reassoc.c
index c5b36ef2cede468ff5bde32a71a68fd74c8d7807..76663654815bc4132d06d77c9e4e478b9e692632 100644
--- a/gcc/tree-ssa-reassoc.c
+++ b/gcc/tree-ssa-reassoc.c
@@ -2846,7 +2846,9 @@ optimize_range_tests_var_bound (enum tree_code opcode, int first, int length,
 
   for (i = first; i < length; i++)
     {
-      if (ranges[i].exp == NULL_TREE || !ranges[i].in_p)
+      if (ranges[i].exp == NULL_TREE
+	  || TREE_CODE (ranges[i].exp) != SSA_NAME
+	  || !ranges[i].in_p)
 	continue;
 
       tree type = TREE_TYPE (ranges[i].exp);
@@ -2878,6 +2880,8 @@ optimize_range_tests_var_bound (enum tree_code opcode, int first, int length,
       tree rhs1, rhs2;
       if (ranges[i].exp)
 	{
+	  if (TREE_CODE (ranges[i].exp) != SSA_NAME)
+	    continue;
 	  stmt = SSA_NAME_DEF_STMT (ranges[i].exp);
 	  if (!is_gimple_assign (stmt))
 	    continue;