[libcxx-commits] [libcxx] [libc++][hardening] Use bounded iterators in std::vector and std::string (PR #78929)
David Benjamin via libcxx-commits
libcxx-commits at lists.llvm.org
Fri Feb 9 12:48:26 PST 2024
davidben wrote:
Another thing I realized: the trick of using the capacity will slightly impede optimizability of range-for loops. Because that will expand the code into:
```
auto begin = vec.__begin_;
auto end = vec.__end_;
auto end_cap = vec. __end_cap();
auto iter = begin;
while (iter != end) {
assert(iter != end_cap);
f(*iter);
auto(iter != end_cap);
iter++;
}
```
In order for the compiler to delete those assertions, it needs to know that `begin <= end <= end_cap`, and I think it has no way to learn that a priori. Interestingly, the assertions in `__bounded_iter`'s constructor are enough to do that, but
1. They're disabled by way of `_LIBCPP_ASSERT_INTERNAL`
2. We don't actually want a runtime check on that because this is an invariant that `std::vector` maintains. I.e. no incorrect use of `std::vector` (should of rampant memory unsafety scribbling over it) will break that invariant.
3. Although `_LIBCPP_ASSERT_INTERNAL` turns into `_LIBCPP_ASSUME`, `_LIBCPP_ASSUME` is currently disabled because it breaks optimizations. So we have to either fix that or add `_LIBCPP_ASSUME_FOR_REAL` on those two invariants. :-)
https://github.com/llvm/llvm-project/pull/78929
More information about the libcxx-commits
mailing list