Skip to content

Loop invariant is not deduced in C++-iterator-style loop over pointers #101372

Open
@davidben

Description

@davidben

In the following loop, the compiler should be able to optimize out the assert.

struct SpanAsPointers {
    int *begin, *end;
};

int sum_span_as_pointers(SpanAsPointers s) {
    int *begin = s.begin;
    int *end = s.end;
    __builtin_assume(begin <= end);

    int sum = 0;
    int *iter = begin;
    while (iter != end) {
        assert(iter < end);
        sum += *iter;
        iter++;
    }
    return sum;
}

See this link for a runnable example, and a longer discussion on why the invariant is true: https://godbolt.org/z/ad5P4d5M5

Also in that link is something interesting: Clang does figure out the invariant when we use integers instead of pointers! It just doesn't apply the same analysis to pointers for some reason.

This is the missing compiler piece needed to solve #101370.

(CC @ldionne @var-const @danakj)

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