Skip to content

Missed optimization: inadequate float range propagation #70985

Open
@bbarenblat

Description

@bbarenblat

At 604eff6, clang++ -target x86_64-linux-gnu -O3 compiles

// Copyright 2023 Google LLC
// SPDX-License-Identifier: Apache-2.0
int ga, gb;
void F(double x) {
  if (x > 5) ++ga;
  if (x > 10) ++gb;
}

to

.LCPI0_0:
        .quad   0x4014000000000000              # double 5
.LCPI0_1:
        .quad   0x4024000000000000              # double 10
_Z1Fd:  ucomisd xmm0, qword ptr [rip + .LCPI0_0]
        ja      .LBB0_1
        ucomisd xmm0, qword ptr [rip + .LCPI0_1]  # ***
        ja      .LBB0_3                           # ***
.LBB0_4:
        ret
.LBB0_1:
        inc     dword ptr [rip + ga]
        ucomisd xmm0, qword ptr [rip + .LCPI0_1]
        jbe     .LBB0_4
.LBB0_3:
        inc     dword ptr [rip + gb]
        ret
ga:     .long   0
gb:     .long   0

The conditional branch marked with # *** will never be taken – in the domain of doubles, !(x > 5) always implies !(x > 10). Telling the compiler this explicitly –

// Copyright 2023 Google LLC
// SPDX-License-Identifier: Apache-2.0
int ga, gb;
void F(double x) {
  if (x > 5) {
    ++ga;
    if (x > 10) ++gb;
  }
}

– produces

.LCPI0_0:
        .quad   0x4014000000000000              # double 5
.LCPI0_1:
        .quad   0x4024000000000000              # double 10
_Z1Fd:  ucomisd xmm0, qword ptr [rip + .LCPI0_0]
        jbe     .LBB0_3
        inc     dword ptr [rip + ga]
        ucomisd xmm0, qword ptr [rip + .LCPI0_1]
        jbe     .LBB0_3
        inc     dword ptr [rip + gb]
.LBB0_3:
        ret
ga:     .long   0
gb:     .long   0

The tautological comparison gets emitted at -O1 through -O3 and -Og, though not at -Os or -Oz. -ffast-math doesn’t change the behavior.

GCC tip-of-tree emits assembly close to the second case in both cases.

Compiler Explorer for experimentation.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions