Fix SafeIntIterator reference type
authorGuillaume Chatelet <gchatelet@google.com>
Mon, 6 Mar 2023 14:13:07 +0000 (14:13 +0000)
committerGuillaume Chatelet <gchatelet@google.com>
Mon, 6 Mar 2023 15:28:25 +0000 (15:28 +0000)
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 https://github.com/llvm/llvm-project/issues/61122

Differential Revision: https://reviews.llvm.org/D145373

llvm/include/llvm/ADT/Sequence.h
llvm/unittests/ADT/SequenceTest.cpp

index 1153352..ddda9a9 100644 (file)
@@ -190,7 +190,7 @@ 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)) {}
@@ -198,9 +198,9 @@ template <typename T, bool IsReverse> struct SafeIntIterator {
   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; }
index aec1ea4..acc15bf 100644 (file)
@@ -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