<table border="1" cellspacing="0" cellpadding="8">
    <tr>
        <th>Issue</th>
        <td>
            <a href=https://github.com/llvm/llvm-project/issues/90785>90785</a>
        </td>
    </tr>

    <tr>
        <th>Summary</th>
        <td>
            [libc++] Code generation for bounds checks seem unoptimal
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            libc++,
            performance,
            hardening
      </td>
    </tr>

    <tr>
      <th>Assignees</th>
      <td>
      </td>
    </tr>

    <tr>
      <th>Reporter</th>
      <td>
          ldionne
      </td>
    </tr>
</table>

<pre>
    In `std::vector`, we currently do

```c++
template <class _Tp, class _Allocator>
reference vector<_Tp, _Allocator>::operator[](size_type __n) _NOEXCEPT {
  _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(__n < size(), "vector[] index out of bounds");
  return this->__begin_[__n];
}
```

However, this requires computing `end - begin` and comparing it to `__n`. Since we already need to compute `__begin + __n` (since we do `__begin[__n]`), we could probably express the condition differently to improve code generation:

```c++
template <class _Tp, class _Allocator>
reference vector<_Tp, _Allocator>::operator[](size_type __n) _NOEXCEPT {
  auto* __p = vec.__begin_ + __n;
 _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(__p < vec.__end_, "vector[] index out of bounds");
  return *__p;
}
```

This seems to generate better code indeed, see https://godbolt.org/z/dzPvMcdfE.

However, I wonder if there's some kind of tradeoff where this would be less easily optimized by the compiler. I just don't have a good intuition for which one is going to be better in the general case.

CC @fhahn @var-const 
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJzUlc9u4zYQxp-Gvgxi0JRkywcfHNlGA-xugyYoehMocWRxlyJVkrLXefpiJCWbLFBggZ4KCP5DDueb-eZHSIagzxZxx7J7lh0Wcoit8zujtLMWF5VTt92DBbbmISqW7Fmyv2AdnWdrzkQBV4R68B5tNDdQjvED4_v5c82np2binp5xNWLXGxkRWFLURoYA5XNPmeY_e2NcLUkgOU4nPDbo0dYIs3JSzEc-Bo_FuR79uDC2w0Qe9AuW8dYjlKVlYgvll9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