1 /*
  2  * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 #ifndef SHARE_UTILITIES_GROWABLEARRAY_HPP
 26 #define SHARE_UTILITIES_GROWABLEARRAY_HPP
 27 
 28 #include "memory/allocation.hpp"
 29 #include "oops/array.hpp"
 30 #include "oops/oop.hpp"
 31 #include "memory/iterator.hpp"
 32 #include "utilities/debug.hpp"
 33 #include "utilities/globalDefinitions.hpp"
 34 #include "utilities/ostream.hpp"
 35 #include "utilities/powerOfTwo.hpp"
 36 
 37 // A growable array.
 38 
 39 /*************************************************************************/
 40 /*                                                                       */
 41 /*     WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING   */
 42 /*                                                                       */
 43 /* Should you use GrowableArrays to contain handles you must be certain  */
 44 /* that the GrowableArray does not outlive the HandleMark that contains  */
 45 /* the handles. Since GrowableArrays are typically resource allocated    */
 46 /* the following is an example of INCORRECT CODE,                        */
 47 /*                                                                       */
 48 /* ResourceMark rm;                                                      */
 49 /* GrowableArray<Handle>* arr = new GrowableArray<Handle>(size);         */
 50 /* if (blah) {                                                           */
 51 /*    while (...) {                                                      */
 52 /*      HandleMark hm;                                                   */
 53 /*      ...                                                              */
 54 /*      Handle h(THREAD, some_oop);                                      */
 55 /*      arr->append(h);                                                  */
 56 /*    }                                                                  */
 57 /* }                                                                     */
 58 /* if (arr->length() != 0 ) {                                            */
 59 /*    oop bad_oop = arr->at(0)(); // Handle is BAD HERE.                 */
 60 /*    ...                                                                */
 61 /* }                                                                     */
 62 /*                                                                       */
 63 /* If the GrowableArrays you are creating is C_Heap allocated then it    */
 64 /* should not hold handles since the handles could trivially try and     */
 65 /* outlive their HandleMark. In some situations you might need to do     */
 66 /* this and it would be legal but be very careful and see if you can do  */
 67 /* the code in some other manner.                                        */
 68 /*                                                                       */
 69 /*************************************************************************/
 70 
 71 // Non-template base class responsible for handling the length and max.
 72 
 73 
 74 class GrowableArrayBase : public AnyObj {
 75   friend class VMStructs;
 76 
 77 protected:
 78   // Current number of accessible elements
 79   int _len;
 80   // Current number of allocated elements
 81   int _capacity;
 82 
 83   GrowableArrayBase(int capacity, int initial_len) :
 84       _len(initial_len),
 85       _capacity(capacity) {
 86     assert(_len >= 0 && _len <= _capacity, "initial_len too big");
 87   }
 88 
 89   ~GrowableArrayBase() {}
 90 
 91 public:
 92   int   length() const          { return _len; }
 93   int   capacity() const        { return _capacity; }
 94 
 95   bool  is_empty() const        { return _len == 0; }
 96   bool  is_nonempty() const     { return _len != 0; }
 97   bool  is_full() const         { return _len == _capacity; }
 98 
 99   void  clear()                 { _len = 0; }
100   void  trunc_to(int length)    {
101     assert(length <= _len,"cannot increase length");
102     _len = length;
103   }
104 };
105 
106 template <typename E> class GrowableArrayIterator;
107 template <typename E, typename UnaryPredicate> class GrowableArrayFilterIterator;
108 
109 // Extends GrowableArrayBase with a typed data array.
110 //
111 // E: Element type
112 //
113 // The "view" adds function that don't grow or deallocate
114 // the _data array, so there's no need for an allocator.
115 //
116 // The "view" can be used to type erase the allocator classes
117 // of GrowableArrayWithAllocator.
118 template <typename E>
119 class GrowableArrayView : public GrowableArrayBase {
120 protected:
121   E* _data; // data array
122 
123   GrowableArrayView(E* data, int capacity, int initial_len) :
124       GrowableArrayBase(capacity, initial_len), _data(data) {}
125 
126   ~GrowableArrayView() {}
127 
128 public:
129   bool operator==(const GrowableArrayView& rhs) const {
130     if (_len != rhs._len)
131       return false;
132     for (int i = 0; i < _len; i++) {
133       if (at(i) != rhs.at(i)) {
134         return false;
135       }
136     }
137     return true;
138   }
139 
140   bool operator!=(const GrowableArrayView& rhs) const {
141     return !(*this == rhs);
142   }
143 
144   E& at(int i) {
145     assert(0 <= i && i < _len, "illegal index %d for length %d", i, _len);
146     return _data[i];
147   }
148 
149   E const& at(int i) const {
150     assert(0 <= i && i < _len, "illegal index %d for length %d", i, _len);
151     return _data[i];
152   }
153 
154   E* adr_at(int i) const {
155     assert(0 <= i && i < _len, "illegal index %d for length %d", i, _len);
156     return &_data[i];
157   }
158 
159   E& first() {
160     assert(_len > 0, "empty");
161     return _data[0];
162   }
163 
164   E const& first() const {
165     assert(_len > 0, "empty");
166     return _data[0];
167   }
168 
169   E& top() {
170     assert(_len > 0, "empty");
171     return _data[_len - 1];
172   }
173 
174   E const& top() const {
175     assert(_len > 0, "empty");
176     return _data[_len - 1];
177   }
178 
179   E& last() {
180     return top();
181   }
182 
183   E const& last() const {
184     return top();
185   }
186 
187   GrowableArrayIterator<E> begin() const {
188     return GrowableArrayIterator<E>(this, 0);
189   }
190 
191   GrowableArrayIterator<E> end() const {
192     return GrowableArrayIterator<E>(this, length());
193   }
194 
195   E pop() {
196     assert(_len > 0, "empty list");
197     return _data[--_len];
198   }
199 
200   void at_put(int i, const E& elem) {
201     assert(0 <= i && i < _len, "illegal index %d for length %d", i, _len);
202     _data[i] = elem;
203   }
204 
205   bool contains(const E& elem) const {
206     for (int i = 0; i < _len; i++) {
207       if (_data[i] == elem) return true;
208     }
209     return false;
210   }
211 
212   int  find(const E& elem) const {
213     for (int i = 0; i < _len; i++) {
214       if (_data[i] == elem) return i;
215     }
216     return -1;
217   }
218 
219   int  find_from_end(const E& elem) const {
220     for (int i = _len-1; i >= 0; i--) {
221       if (_data[i] == elem) return i;
222     }
223     return -1;
224   }
225 
226   // Find first element that matches the given predicate.
227   //
228   // Predicate: bool predicate(const E& elem)
229   //
230   // Returns the index of the element or -1 if no element matches the predicate
231   template<typename Predicate>
232   int find_if(Predicate predicate) const {
233     for (int i = 0; i < _len; i++) {
234       if (predicate(_data[i])) return i;
235     }
236     return -1;
237   }
238 
239   // Find last element that matches the given predicate.
240   //
241   // Predicate: bool predicate(const E& elem)
242   //
243   // Returns the index of the element or -1 if no element matches the predicate
244   template<typename Predicate>
245   int find_from_end_if(Predicate predicate) const {
246     // start at the end of the array
247     for (int i = _len-1; i >= 0; i--) {
248       if (predicate(_data[i])) return i;
249     }
250     return -1;
251   }
252 
253   // Order preserving remove operations.
254 
255   void remove(const E& elem) {
256     // Assuming that element does exist.
257     bool removed = remove_if_existing(elem);
258     if (removed) return;
259     ShouldNotReachHere();
260   }
261 
262   bool remove_if_existing(const E& elem) {
263     // Returns TRUE if elem is removed.
264     for (int i = 0; i < _len; i++) {
265       if (_data[i] == elem) {
266         remove_at(i);
267         return true;
268       }
269     }
270     return false;
271   }
272 
273   void remove_at(int index) {
274     assert(0 <= index && index < _len, "illegal index %d for length %d", index, _len);
275     for (int j = index + 1; j < _len; j++) {
276       _data[j-1] = _data[j];
277     }
278     _len--;
279   }
280 
281   // Remove all elements up to the index (exclusive). The order is preserved.
282   void remove_till(int idx) {
283     remove_range(0, idx);
284   }
285 
286   // Remove all elements in the range [start - end). The order is preserved.
287   void remove_range(int start, int end) {
288     assert(0 <= start, "illegal start index %d", start);
289     assert(start < end && end <= _len, "erase called with invalid range (%d, %d) for length %d", start, end, _len);
290 
291     for (int i = start, j = end; j < length(); i++, j++) {
292       at_put(i, at(j));
293     }
294     trunc_to(length() - (end - start));
295   }
296 
297   // The order is changed.
298   void delete_at(int index) {
299     assert(0 <= index && index < _len, "illegal index %d for length %d", index, _len);
300     if (index < --_len) {
301       // Replace removed element with last one.
302       _data[index] = _data[_len];
303     }
304   }
305 
306   void sort(int f(E*, E*)) {
307     if (_data == nullptr) return;
308     qsort(_data, length(), sizeof(E), (_sort_Fn)f);
309   }
310   // sort by fixed-stride sub arrays:
311   void sort(int f(E*, E*), int stride) {
312     if (_data == nullptr) return;
313     qsort(_data, length() / stride, sizeof(E) * stride, (_sort_Fn)f);
314   }
315 
316   template <typename K, int compare(const K&, const E&)> int find_sorted(const K& key, bool& found) const {
317     found = false;
318     int min = 0;
319     int max = length() - 1;
320 
321     while (max >= min) {
322       int mid = (int)(((uint)max + min) / 2);
323       E value = at(mid);
324       int diff = compare(key, value);
325       if (diff > 0) {
326         min = mid + 1;
327       } else if (diff < 0) {
328         max = mid - 1;
329       } else {
330         found = true;
331         return mid;
332       }
333     }
334     return min;
335   }
336 
337   template <typename K>
338   int find_sorted(CompareClosure<E>* cc, const K& key, bool& found) {
339     found = false;
340     int min = 0;
341     int max = length() - 1;
342 
343     while (max >= min) {
344       int mid = (int)(((uint)max + min) / 2);
345       E value = at(mid);
346       int diff = cc->do_compare(key, value);
347       if (diff > 0) {
348         min = mid + 1;
349       } else if (diff < 0) {
350         max = mid - 1;
351       } else {
352         found = true;
353         return mid;
354       }
355     }
356     return min;
357   }
358 
359   void print() const {
360     tty->print("Growable Array " PTR_FORMAT, p2i(this));
361     tty->print(": length %d (capacity %d) { ", _len, _capacity);
362     for (int i = 0; i < _len; i++) {
363       tty->print(INTPTR_FORMAT " ", *(intptr_t*)&(_data[i]));
364     }
365     tty->print("}\n");
366   }
367 };
368 
369 template <typename E>
370 class GrowableArrayFromArray : public GrowableArrayView<E> {
371 public:
372 
373   GrowableArrayFromArray(E* data, int len) :
374     GrowableArrayView<E>(data, len, len) {}
375 };
376 
377 // GrowableArrayWithAllocator extends the "view" with
378 // the capability to grow and deallocate the data array.
379 //
380 // The allocator responsibility is delegated to the sub-class.
381 //
382 // Derived: The sub-class responsible for allocation / deallocation
383 //  - E* Derived::allocate()       - member function responsible for allocation
384 //  - void Derived::deallocate(E*) - member function responsible for deallocation
385 template <typename E, typename Derived>
386 class GrowableArrayWithAllocator : public GrowableArrayView<E> {
387   friend class VMStructs;
388 
389   void expand_to(int j);
390   void grow(int j);
391 
392 protected:
393   GrowableArrayWithAllocator(E* data, int capacity) :
394       GrowableArrayView<E>(data, capacity, 0) {
395     for (int i = 0; i < capacity; i++) {
396       ::new ((void*)&data[i]) E();
397     }
398   }
399 
400   GrowableArrayWithAllocator(E* data, int capacity, int initial_len, const E& filler) :
401       GrowableArrayView<E>(data, capacity, initial_len) {
402     int i = 0;
403     for (; i < initial_len; i++) {
404       ::new ((void*)&data[i]) E(filler);
405     }
406     for (; i < capacity; i++) {
407       ::new ((void*)&data[i]) E();
408     }
409   }
410 
411   ~GrowableArrayWithAllocator() {}
412 
413 public:
414   int append(const E& elem) {
415     if (this->_len == this->_capacity) grow(this->_len);
416     int idx = this->_len++;
417     this->_data[idx] = elem;
418     return idx;
419   }
420 
421   bool append_if_missing(const E& elem) {
422     // Returns TRUE if elem is added.
423     bool missed = !this->contains(elem);
424     if (missed) append(elem);
425     return missed;
426   }
427 
428   void push(const E& elem) { append(elem); }
429 
430   E& at_grow(int i, const E& fill = E()) {
431     assert(0 <= i, "negative index %d", i);
432     if (i >= this->_len) {
433       if (i >= this->_capacity) grow(i);
434       for (int j = this->_len; j <= i; j++)
435         this->_data[j] = fill;
436       this->_len = i+1;
437     }
438     return this->_data[i];
439   }
440 
441   void at_put_grow(int i, const E& elem, const E& fill = E()) {
442     assert(0 <= i, "negative index %d", i);
443     if (i >= this->_len) {
444       if (i >= this->_capacity) grow(i);
445       for (int j = this->_len; j < i; j++)
446         this->_data[j] = fill;
447       this->_len = i+1;
448     }
449     this->_data[i] = elem;
450   }
451 
452   // inserts the given element before the element at index i
453   void insert_before(const int idx, const E& elem) {
454     assert(0 <= idx && idx <= this->_len, "illegal index %d for length %d", idx, this->_len);
455     if (this->_len == this->_capacity) grow(this->_len);
456     for (int j = this->_len - 1; j >= idx; j--) {
457       this->_data[j + 1] = this->_data[j];
458     }
459     this->_len++;
460     this->_data[idx] = elem;
461   }
462 
463   void insert_before(const int idx, const GrowableArrayView<E>* array) {
464     assert(0 <= idx && idx <= this->_len, "illegal index %d for length %d", idx, this->_len);
465     int array_len = array->length();
466     int new_len = this->_len + array_len;
467     if (new_len >= this->_capacity) grow(new_len);
468 
469     for (int j = this->_len - 1; j >= idx; j--) {
470       this->_data[j + array_len] = this->_data[j];
471     }
472 
473     for (int j = 0; j < array_len; j++) {
474       this->_data[idx + j] = array->at(j);
475     }
476 
477     this->_len += array_len;
478   }
479 
480   void appendAll(const GrowableArrayView<E>* l) {
481     for (int i = 0; i < l->length(); i++) {
482       this->at_put_grow(this->_len, l->at(i), E());
483     }
484   }
485 
486   void appendAll(const Array<E>* l) {
487     for (int i = 0; i < l->length(); i++) {
488       this->at_put_grow(this->_len, l->at(i), E());
489     }
490   }
491 
492   // Binary search and insertion utility.  Search array for element
493   // matching key according to the static compare function.  Insert
494   // that element if not already in the list.  Assumes the list is
495   // already sorted according to compare function.
496   template <int compare(const E&, const E&)> E insert_sorted(const E& key) {
497     bool found;
498     int location = GrowableArrayView<E>::template find_sorted<E, compare>(key, found);
499     if (!found) {
500       insert_before(location, key);
501     }
502     return this->at(location);
503   }
504 
505   E insert_sorted(CompareClosure<E>* cc, const E& key) {
506     bool found;
507     int location = find_sorted(cc, key, found);
508     if (!found) {
509       insert_before(location, key);
510     }
511     return this->at(location);
512   }
513 
514   void swap(GrowableArrayWithAllocator* other) {
515     ::swap(this->_data, other->_data);
516     ::swap(this->_len, other->_len);
517     ::swap(this->_capacity, other->_capacity);
518   }
519 
520   // Ensure capacity is at least new_capacity.
521   void reserve(int new_capacity);
522 
523   // Reduce capacity to length.
524   void shrink_to_fit();
525 
526   void clear_and_deallocate();
527 };
528 
529 template <typename E, typename Derived>
530 void GrowableArrayWithAllocator<E, Derived>::expand_to(int new_capacity) {
531   int old_capacity = this->_capacity;
532   assert(new_capacity > old_capacity,
533          "expected growth but %d <= %d", new_capacity, old_capacity);
534   this->_capacity = new_capacity;
535   E* newData = static_cast<Derived*>(this)->allocate();
536   int i = 0;
537   for (     ; i < this->_len; i++) ::new ((void*)&newData[i]) E(this->_data[i]);
538   for (     ; i < this->_capacity; i++) ::new ((void*)&newData[i]) E();
539   for (i = 0; i < old_capacity; i++) this->_data[i].~E();
540   if (this->_data != nullptr) {
541     static_cast<Derived*>(this)->deallocate(this->_data);
542   }
543   this->_data = newData;
544 }
545 
546 template <typename E, typename Derived>
547 void GrowableArrayWithAllocator<E, Derived>::grow(int j) {
548   // grow the array by increasing _capacity to the first power of two larger than the size we need
549   expand_to(next_power_of_2(j));
550 }
551 
552 template <typename E, typename Derived>
553 void GrowableArrayWithAllocator<E, Derived>::reserve(int new_capacity) {
554   if (new_capacity > this->_capacity) {
555     expand_to(new_capacity);
556   }
557 }
558 
559 template <typename E, typename Derived>
560 void GrowableArrayWithAllocator<E, Derived>::shrink_to_fit() {
561   int old_capacity = this->_capacity;
562   int len = this->_len;
563   assert(len <= old_capacity, "invariant");
564 
565   // If already at full capacity, nothing to do.
566   if (len == old_capacity) {
567     return;
568   }
569 
570   // If not empty, allocate new, smaller, data, and copy old data to it.
571   E* old_data = this->_data;
572   E* new_data = nullptr;
573   this->_capacity = len;        // Must preceed allocate().
574   if (len > 0) {
575     new_data = static_cast<Derived*>(this)->allocate();
576     for (int i = 0; i < len; ++i) ::new (&new_data[i]) E(old_data[i]);
577   }
578   // Destroy contents of old data, and deallocate it.
579   for (int i = 0; i < old_capacity; ++i) old_data[i].~E();
580   if (old_data != nullptr) {
581     static_cast<Derived*>(this)->deallocate(old_data);
582   }
583   // Install new data, which might be nullptr.
584   this->_data = new_data;
585 }
586 
587 template <typename E, typename Derived>
588 void GrowableArrayWithAllocator<E, Derived>::clear_and_deallocate() {
589   this->clear();
590   this->shrink_to_fit();
591 }
592 
593 class GrowableArrayResourceAllocator {
594 public:
595   static void* allocate(int max, int element_size);
596 };
597 
598 // Arena allocator
599 class GrowableArrayArenaAllocator {
600 public:
601   static void* allocate(int max, int element_size, Arena* arena);
602 };
603 
604 // CHeap allocator
605 class GrowableArrayCHeapAllocator {
606 public:
607   static void* allocate(int max, int element_size, MemTag mem_tag);
608   static void deallocate(void* mem);
609 };
610 
611 #ifdef ASSERT
612 
613 // Checks resource allocation nesting
614 class GrowableArrayNestingCheck {
615   // resource area nesting at creation
616   int _nesting;
617 
618 public:
619   GrowableArrayNestingCheck(bool on_resource_area);
620 
621   void on_resource_area_alloc() const;
622 };
623 
624 #endif // ASSERT
625 
626 // Encodes where the backing array is allocated
627 // and performs necessary checks.
628 class GrowableArrayMetadata {
629   uintptr_t _bits;
630 
631   // resource area nesting at creation
632   debug_only(GrowableArrayNestingCheck _nesting_check;)
633 
634   // Resource allocation
635   static uintptr_t bits() {
636     return 0;
637   }
638 
639   // CHeap allocation
640   static uintptr_t bits(MemTag mem_tag) {
641     assert(mem_tag != mtNone, "Must provide a proper MemTag");
642     return (uintptr_t(mem_tag) << 1) | 1;
643   }
644 
645   // Arena allocation
646   static uintptr_t bits(Arena* arena) {
647     assert((uintptr_t(arena) & 1) == 0, "Required for on_C_heap() to work");
648     return uintptr_t(arena);
649   }
650 
651 public:
652   // Resource allocation
653   GrowableArrayMetadata() :
654       _bits(bits())
655       debug_only(COMMA _nesting_check(true)) {
656   }
657 
658   // Arena allocation
659   GrowableArrayMetadata(Arena* arena) :
660       _bits(bits(arena))
661       debug_only(COMMA _nesting_check(false)) {
662   }
663 
664   // CHeap allocation
665   GrowableArrayMetadata(MemTag mem_tag) :
666       _bits(bits(mem_tag))
667       debug_only(COMMA _nesting_check(false)) {
668   }
669 
670 #ifdef ASSERT
671   GrowableArrayMetadata(const GrowableArrayMetadata& other) :
672       _bits(other._bits),
673       _nesting_check(other._nesting_check) {
674     assert(!on_C_heap(), "Copying of CHeap arrays not supported");
675     assert(!other.on_C_heap(), "Copying of CHeap arrays not supported");
676   }
677 
678   GrowableArrayMetadata& operator=(const GrowableArrayMetadata& other) {
679     _bits = other._bits;
680     _nesting_check = other._nesting_check;
681     assert(!on_C_heap(), "Assignment of CHeap arrays not supported");
682     assert(!other.on_C_heap(), "Assignment of CHeap arrays not supported");
683     return *this;
684   }
685 
686   void init_checks(const GrowableArrayBase* array) const;
687   void on_resource_area_alloc_check() const;
688 #endif // ASSERT
689 
690   bool on_C_heap() const        { return (_bits & 1) == 1; }
691   bool on_resource_area() const { return _bits == 0; }
692   bool on_arena() const         { return (_bits & 1) == 0 && _bits != 0; }
693 
694   Arena* arena() const      { return (Arena*)_bits; }
695   MemTag mem_tag() const { return MemTag(_bits >> 1); }
696 };
697 
698 // THE GrowableArray.
699 //
700 // Supports multiple allocation strategies:
701 //  - Resource stack allocation: if no extra argument is provided
702 //  - CHeap allocation: if mem_tag is provided
703 //  - Arena allocation: if an arena is provided
704 //
705 // There are some drawbacks of using GrowableArray, that are removed in some
706 // of the other implementations of GrowableArrayWithAllocator sub-classes:
707 //
708 // Memory overhead: The multiple allocation strategies uses extra metadata
709 //  embedded in the instance.
710 //
711 // Strict allocation locations: There are rules about where the GrowableArray
712 //  instance is allocated, that depends on where the data array is allocated.
713 //  See: init_checks.
714 
715 template <typename E>
716 class GrowableArray : public GrowableArrayWithAllocator<E, GrowableArray<E>> {
717   friend class GrowableArrayWithAllocator<E, GrowableArray>;
718   friend class GrowableArrayTest;
719 
720   static E* allocate(int max) {
721     return (E*)GrowableArrayResourceAllocator::allocate(max, sizeof(E));
722   }
723 
724   static E* allocate(int max, MemTag mem_tag) {
725     return (E*)GrowableArrayCHeapAllocator::allocate(max, sizeof(E), mem_tag);
726   }
727 
728   static E* allocate(int max, Arena* arena) {
729     return (E*)GrowableArrayArenaAllocator::allocate(max, sizeof(E), arena);
730   }
731 
732   GrowableArrayMetadata _metadata;
733 
734   void init_checks() const { debug_only(_metadata.init_checks(this);) }
735 
736   // Where are we going to allocate memory?
737   bool on_C_heap() const        { return _metadata.on_C_heap(); }
738   bool on_resource_area() const { return _metadata.on_resource_area(); }
739   bool on_arena() const         { return _metadata.on_arena(); }
740 
741   E* allocate() {
742     if (on_resource_area()) {
743       debug_only(_metadata.on_resource_area_alloc_check());
744       return allocate(this->_capacity);
745     }
746 
747     if (on_C_heap()) {
748       return allocate(this->_capacity, _metadata.mem_tag());
749     }
750 
751     assert(on_arena(), "Sanity");
752     return allocate(this->_capacity, _metadata.arena());
753   }
754 
755   void deallocate(E* mem) {
756     if (on_C_heap()) {
757       GrowableArrayCHeapAllocator::deallocate(mem);
758     }
759   }
760 
761 public:
762   GrowableArray() : GrowableArray(2 /* initial_capacity */) {}
763 
764   explicit GrowableArray(int initial_capacity) :
765       GrowableArrayWithAllocator<E, GrowableArray>(
766           allocate(initial_capacity),
767           initial_capacity),
768       _metadata() {
769     init_checks();
770   }
771 
772   GrowableArray(int initial_capacity, MemTag mem_tag) :
773       GrowableArrayWithAllocator<E, GrowableArray>(
774           allocate(initial_capacity, mem_tag),
775           initial_capacity),
776       _metadata(mem_tag) {
777     init_checks();
778   }
779 
780   GrowableArray(int initial_capacity, int initial_len, const E& filler) :
781       GrowableArrayWithAllocator<E, GrowableArray>(
782           allocate(initial_capacity),
783           initial_capacity, initial_len, filler),
784       _metadata() {
785     init_checks();
786   }
787 
788   GrowableArray(int initial_capacity, int initial_len, const E& filler, MemTag mem_tag) :
789       GrowableArrayWithAllocator<E, GrowableArray>(
790           allocate(initial_capacity, mem_tag),
791           initial_capacity, initial_len, filler),
792       _metadata(mem_tag) {
793     init_checks();
794   }
795 
796   GrowableArray(Arena* arena, int initial_capacity, int initial_len, const E& filler) :
797       GrowableArrayWithAllocator<E, GrowableArray>(
798           allocate(initial_capacity, arena),
799           initial_capacity, initial_len, filler),
800       _metadata(arena) {
801     init_checks();
802   }
803 
804   ~GrowableArray() {
805     if (on_C_heap()) {
806       this->clear_and_deallocate();
807     }
808   }
809 };
810 
811 // Leaner GrowableArray for CHeap backed data arrays, with compile-time decided MemTag.
812 template <typename E, MemTag MT>
813 class GrowableArrayCHeap : public GrowableArrayWithAllocator<E, GrowableArrayCHeap<E, MT> > {
814   friend class GrowableArrayWithAllocator<E, GrowableArrayCHeap<E, MT> >;
815 
816   STATIC_ASSERT(MT != mtNone);
817 
818   static E* allocate(int max, MemTag mem_tag) {
819     if (max == 0) {
820       return nullptr;
821     }
822 
823     return (E*)GrowableArrayCHeapAllocator::allocate(max, sizeof(E), mem_tag);
824   }
825 
826   NONCOPYABLE(GrowableArrayCHeap);
827 
828   E* allocate() {
829     return allocate(this->_capacity, MT);
830   }
831 
832   void deallocate(E* mem) {
833     GrowableArrayCHeapAllocator::deallocate(mem);
834   }
835 
836 public:
837   GrowableArrayCHeap(int initial_capacity = 0) :
838       GrowableArrayWithAllocator<E, GrowableArrayCHeap<E, MT> >(
839           allocate(initial_capacity, MT),
840           initial_capacity) {}
841 
842   GrowableArrayCHeap(int initial_capacity, int initial_len, const E& filler) :
843       GrowableArrayWithAllocator<E, GrowableArrayCHeap<E, MT> >(
844           allocate(initial_capacity, MT),
845           initial_capacity, initial_len, filler) {}
846 
847   ~GrowableArrayCHeap() {
848     this->clear_and_deallocate();
849   }
850 
851   void* operator new(size_t size) {
852     return AnyObj::operator new(size, MT);
853   }
854 
855   void* operator new(size_t size, const std::nothrow_t&  nothrow_constant) throw() {
856     return AnyObj::operator new(size, nothrow_constant, MT);
857   }
858   void operator delete(void *p) {
859     AnyObj::operator delete(p);
860   }
861 };
862 
863 // Custom STL-style iterator to iterate over GrowableArrays
864 // It is constructed by invoking GrowableArray::begin() and GrowableArray::end()
865 template <typename E>
866 class GrowableArrayIterator : public StackObj {
867   friend class GrowableArrayView<E>;
868   template <typename F, typename UnaryPredicate> friend class GrowableArrayFilterIterator;
869 
870  private:
871   const GrowableArrayView<E>* _array; // GrowableArray we iterate over
872   int _position;                      // The current position in the GrowableArray
873 
874   // Private constructor used in GrowableArray::begin() and GrowableArray::end()
875   GrowableArrayIterator(const GrowableArrayView<E>* array, int position) : _array(array), _position(position) {
876     assert(0 <= position && position <= _array->length(), "illegal position");
877   }
878 
879  public:
880   GrowableArrayIterator() : _array(nullptr), _position(0) { }
881   GrowableArrayIterator& operator++() { ++_position; return *this; }
882   E operator*()                       { return _array->at(_position); }
883 
884   bool operator==(const GrowableArrayIterator& rhs)  {
885     assert(_array == rhs._array, "iterator belongs to different array");
886     return _position == rhs._position;
887   }
888 
889   bool operator!=(const GrowableArrayIterator& rhs)  {
890     assert(_array == rhs._array, "iterator belongs to different array");
891     return _position != rhs._position;
892   }
893 };
894 
895 // Custom STL-style iterator to iterate over elements of a GrowableArray that satisfy a given predicate
896 template <typename E, class UnaryPredicate>
897 class GrowableArrayFilterIterator : public StackObj {
898   friend class GrowableArrayView<E>;
899 
900  private:
901   const GrowableArrayView<E>* _array; // GrowableArray we iterate over
902   int _position;                      // Current position in the GrowableArray
903   UnaryPredicate _predicate;          // Unary predicate the elements of the GrowableArray should satisfy
904 
905  public:
906   GrowableArrayFilterIterator(const GrowableArray<E>* array, UnaryPredicate filter_predicate) :
907       _array(array), _position(0), _predicate(filter_predicate) {
908     // Advance to first element satisfying the predicate
909     while(!at_end() && !_predicate(_array->at(_position))) {
910       ++_position;
911     }
912   }
913 
914   GrowableArrayFilterIterator<E, UnaryPredicate>& operator++() {
915     do {
916       // Advance to next element satisfying the predicate
917       ++_position;
918     } while(!at_end() && !_predicate(_array->at(_position)));
919     return *this;
920   }
921 
922   E operator*() { return _array->at(_position); }
923 
924   bool operator==(const GrowableArrayIterator<E>& rhs)  {
925     assert(_array == rhs._array, "iterator belongs to different array");
926     return _position == rhs._position;
927   }
928 
929   bool operator!=(const GrowableArrayIterator<E>& rhs)  {
930     assert(_array == rhs._array, "iterator belongs to different array");
931     return _position != rhs._position;
932   }
933 
934   bool operator==(const GrowableArrayFilterIterator<E, UnaryPredicate>& rhs)  {
935     assert(_array == rhs._array, "iterator belongs to different array");
936     return _position == rhs._position;
937   }
938 
939   bool operator!=(const GrowableArrayFilterIterator<E, UnaryPredicate>& rhs)  {
940     assert(_array == rhs._array, "iterator belongs to different array");
941     return _position != rhs._position;
942   }
943 
944   bool at_end() const {
945     return _array == nullptr || _position == _array->end()._position;
946   }
947 };
948 
949 // Arrays for basic types
950 typedef GrowableArray<int> intArray;
951 typedef GrowableArray<int> intStack;
952 typedef GrowableArray<bool> boolArray;
953 
954 #endif // SHARE_UTILITIES_GROWABLEARRAY_HPP