Skip to content

LLVM does not eliminate or hoist redundant bounds checks for std::vector and std::string #90119

Open
@ldionne

Description

Given the following code:

#include <vector>
#include <span>
#include <string>

template <class T>
void use(T const&);

template <class Container>
void f(Container container) {
  for (int i = 0; i != container.size(); ++i) {
    use(container[i]);
  }
}

template void f(std::string);
template void f(std::vector<int>);
template void f(std::span<int>);

Godbolt: https://godbolt.org/z/x8fdv8s63

When we compile with hardening enabled, there is a bounds check inside operator[]. That check is basically equivalent to index < size(). However, it doesn't get elided even though the loop condition should guarantee that the condition always holds. It seems to be elided when iterating over a span, but not a string or a vector, which makes me think the optimizer could be improved.

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions