Skip to content

Redundant pointer comparisons after arithmetic not deleted #78784

Closed
@davidben

Description

@davidben

I noticed this as I was exploring the compiler output for some of our (Chromium's) checked iterators. To be honest, I'm not sure this check makes sense, since we should just assume the container is self-consistent. But, nonetheless, I think Clang could have deleted this check, so I'm filing this as a missed optimization.

Reproducer: https://godbolt.org/z/EzoWqGEEK

This code ends up performing a few variations on checking that data_ <= data_ + size_, where size_ is a size_t. Of course, the real reason this is always valid is that [data_, data_ + size_) describes a span, but the compiler doesn't a priori know that. However, I believe it can infer this because:

  1. size_ is unsigned, so we're not adding a negative number to data_
  2. Pointer arithmetic is required to stay in bounds, and is not defined to cast to ptrdiff_t first: https://eel.is/c++draft/expr.add#4.2
  3. Therefore, the addition cannot have overflowed and data_ <= data_ + size_ is always true in all defined cases

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