Skip to content

Optimize std::max(X, 1u) and save one instruction #60374

@kazutakahirata

Description

@kazutakahirata

It looks like std::max(X, 1u) can be optimized a little bit.

Compile the following with clang++ -O2 on x86:

#include <algorithm>

unsigned foo();

unsigned UnsignedMaxOneA() {
  unsigned X = foo();
  return std::max(X, 1u);
}

unsigned UnsignedMaxOneB() {
  unsigned X = foo();
  return X + (X == 0);
}

I get:

        testl   %eax, %eax
        movl    $1, %ecx
        cmovel  %ecx, %eax
        cmpl    $1, %eax
        adcl    $0, %eax

I'm using foo() so that we can use %eax as the starting point (as opposed to %edi for a parameter).

Both sequences have dependency tree height of 2. They are encoded with 10 bytes and 6 bytes, respectively.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions