Skip to content

Commit

Permalink
Fix SafeIntIterator reference type
Browse files Browse the repository at this point in the history
We explicitly state that the `reference` type for Sequence iterator is a `value_type`.
Since the iterator is a lazy generator, it cannot point to any memory and so it cannot have a reference type.
Fixes #61122

Differential Revision: https://reviews.llvm.org/D145373
  • Loading branch information
gchatelet committed Mar 6, 2023
1 parent 960126e commit bff3682
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
6 changes: 3 additions & 3 deletions llvm/include/llvm/ADT/Sequence.h
Expand Up @@ -190,17 +190,17 @@ template <typename T, bool IsReverse> struct SafeIntIterator {
using value_type = T;
using difference_type = intmax_t;
using pointer = T *;
using reference = T &;
using reference = value_type; // The iterator does not reference memory.

// Construct from T.
explicit SafeIntIterator(T Value) : SI(CheckedInt::from<T>(Value)) {}
// Construct from other direction.
SafeIntIterator(const SafeIntIterator<T, !IsReverse> &O) : SI(O.SI) {}

// Dereference
value_type operator*() const { return SI.to<T>(); }
reference operator*() const { return SI.to<T>(); }
// Indexing
value_type operator[](intmax_t Offset) const { return *(*this + Offset); }
reference operator[](intmax_t Offset) const { return *(*this + Offset); }

// Can be compared for equivalence using the equality/inequality operators.
bool operator==(const SafeIntIterator &O) const { return SI == O.SI; }
Expand Down
9 changes: 9 additions & 0 deletions llvm/unittests/ADT/SequenceTest.cpp
Expand Up @@ -296,4 +296,13 @@ TEST(SequenceTest, NonIterableEnums) {
ElementsAre(UntypedEnum::A));
}

// Reproducer for https://github.com/llvm/llvm-project/issues/61122
TEST(SequenceTest, CorrectReferenceType) {
std::vector<int> vals = {1, 2, 3};
detail::SafeIntIterator<int, false> begin(4);
detail::SafeIntIterator<int, false> end(6);
vals.insert(vals.end(), begin, end);
EXPECT_THAT(vals, ElementsAre(1, 2, 3, 4, 5));
}

} // namespace

0 comments on commit bff3682

Please sign in to comment.