https://gcc.gnu.org/bugzilla/show_bug.cgi?id=103536

            Bug ID: 103536
           Summary: Suboptimal codegen for && and || combination.
           Product: gcc
           Version: unknown
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: tree-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: navidr at gcc dot gnu.org
  Target Milestone: ---

We do have suboptimal codegen for this pattern:

https://compiler-explorer.com/z/dszaK49WT

bool
src_1 (bool a, bool b)
{
    return (a || b) && (a && b);
}

bool
src_2 (bool a, bool b) // no problem here
{
    return (a && b) && (a || b);
}

bool
tgt (bool a, bool b) // what we want
{
    return (a && b);
}


In the case of src_2, it is the "ethread" pass which will remove the extra
basicblock. But in case of src_1 since the operation is spread over multiple
basicblocks, the match.pd is not able to detect and solve this.

1) In limited situations, it is possible to detect pattern in GENERIC and fix
this:

As proof of concept, I tried with something like this and was able to fix this
in GENERIC:
(for firstAnd (truth_and truth_andif)
 (for secondAnd (truth_and truth_andif)
  (for firstOr (truth_or truth_orif)
   (simplify
    (firstAnd (firstOr @0 @1) (secondAnd truth_valued_p@0 truth_valued_p@1))
    (truth_and @0 @1)))))

Because of GENERIC limitation, this is not going to work on something like
this:
bool src_12 (bool a, bool b)
{
    int z = a || b;
    return z && (a && b);
}



2) A better approach which I haven't looked at, is not to spread this over
multiple basic blocks.

Reply via email to