[PATCH] D84293: Add an assertion in SmallVector::push_back()

Mehdi AMINI via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Tue Jul 21 21:43:07 PDT 2020


mehdi_amini created this revision.
mehdi_amini added a reviewer: bkramer.
Herald added subscribers: llvm-commits, dexonsmith.
Herald added a project: LLVM.

This assertion ensures the input value isn't part of the vector when
growing is required. In such cases the vector will grow and the input
value is invalidated before being read from.

This found 14 failed Tests.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D84293

Files:
  llvm/include/llvm/ADT/SmallVector.h
  llvm/include/llvm/MC/MCInst.h


Index: llvm/include/llvm/MC/MCInst.h
===================================================================
--- llvm/include/llvm/MC/MCInst.h
+++ llvm/include/llvm/MC/MCInst.h
@@ -181,7 +181,10 @@
   MCOperand &getOperand(unsigned i) { return Operands[i]; }
   unsigned getNumOperands() const { return Operands.size(); }
 
-  void addOperand(const MCOperand &Op) { Operands.push_back(Op); }
+  void addOperand(const MCOperand &Op) {
+    Operands.reserve(Operands.size() + 1);
+    Operands.push_back(Op);
+  }
 
   using iterator = SmallVectorImpl<MCOperand>::iterator;
   using const_iterator = SmallVectorImpl<MCOperand>::const_iterator;
Index: llvm/include/llvm/ADT/SmallVector.h
===================================================================
--- llvm/include/llvm/ADT/SmallVector.h
+++ llvm/include/llvm/ADT/SmallVector.h
@@ -129,6 +129,13 @@
     this->Size = this->Capacity = 0; // FIXME: Setting Capacity to 0 is suspect.
   }
 
+  void assertSafeToPush(const void *Elt) {
+    assert(
+        (Elt < begin() || Elt >= end() || this->size() < this->capacity()) &&
+        "Attempting to push_back to the vector an element of the vector without"
+        " enough space reserved");
+  }
+
 public:
   using size_type = size_t;
   using difference_type = ptrdiff_t;
@@ -244,6 +251,7 @@
 
 public:
   void push_back(const T &Elt) {
+    this->assertSafeToPush(&Elt);
     if (LLVM_UNLIKELY(this->size() >= this->capacity()))
       this->grow();
     ::new ((void*) this->end()) T(Elt);
@@ -251,6 +259,7 @@
   }
 
   void push_back(T &&Elt) {
+    this->assertSafeToPush(&Elt);
     if (LLVM_UNLIKELY(this->size() >= this->capacity()))
       this->grow();
     ::new ((void*) this->end()) T(::std::move(Elt));
@@ -346,6 +355,7 @@
 
 public:
   void push_back(const T &Elt) {
+    this->assertSafeToPush(&Elt);
     if (LLVM_UNLIKELY(this->size() >= this->capacity()))
       this->grow();
     memcpy(reinterpret_cast<void *>(this->end()), &Elt, sizeof(T));


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D84293.279703.patch
Type: text/x-patch
Size: 1968 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20200722/a051171b/attachment.bin>


More information about the llvm-commits mailing list