1 /*
  2  * Copyright (c) 1997, 2017, 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_VM_UTILITIES_GROWABLEARRAY_HPP
 26 #define SHARE_VM_UTILITIES_GROWABLEARRAY_HPP
 27 
 28 #include "memory/allocation.hpp"
 29 #include "utilities/debug.hpp"
 30 #include "utilities/globalDefinitions.hpp"
 31 #include "utilities/ostream.hpp"
 32 
 33 // A growable array.
 34 
 35 /*************************************************************************/
 36 /*                                                                       */
 37 /*     WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING   */
 38 /*                                                                       */
 39 /* Should you use GrowableArrays to contain handles you must be certain  */
 40 /* the the GrowableArray does not outlive the HandleMark that contains   */
 41 /* the handles. Since GrowableArrays are typically resource allocated    */
 42 /* the following is an example of INCORRECT CODE,                        */
 43 /*                                                                       */
 44 /* ResourceMark rm;                                                      */
 45 /* GrowableArray<Handle>* arr = new GrowableArray<Handle>(size);         */
 46 /* if (blah) {                                                           */
 47 /*    while (...) {                                                      */
 48 /*      HandleMark hm;                                                   */
 49 /*      ...                                                              */
 50 /*      Handle h(THREAD, some_oop);                                      */
 51 /*      arr->append(h);                                                  */
 52 /*    }                                                                  */
 53 /* }                                                                     */
 54 /* if (arr->length() != 0 ) {                                            */
 55 /*    oop bad_oop = arr->at(0)(); // Handle is BAD HERE.                 */
 56 /*    ...                                                                */
 57 /* }                                                                     */
 58 /*                                                                       */
 59 /* If the GrowableArrays you are creating is C_Heap allocated then it    */
 60 /* hould not old handles since the handles could trivially try and       */
 61 /* outlive their HandleMark. In some situations you might need to do     */
 62 /* this and it would be legal but be very careful and see if you can do  */
 63 /* the code in some other manner.                                        */
 64 /*                                                                       */
 65 /*************************************************************************/
 66 
 67 // To call default constructor the placement operator new() is used.
 68 // It should be empty (it only returns the passed void* pointer).
 69 // The definition of placement operator new(size_t, void*) in the <new>.
 70 
 71 #include <new>
 72 
 73 // Need the correct linkage to call qsort without warnings
 74 extern "C" {
 75   typedef int (*_sort_Fn)(const void *, const void *);
 76 }
 77 
 78 class GenericGrowableArray : public ResourceObj {
 79   friend class VMStructs;
 80 
 81  protected:
 82   int    _len;          // current length
 83   int    _max;          // maximum length
 84   Arena* _arena;        // Indicates where allocation occurs:
 85                         //   0 means default ResourceArea
 86                         //   1 means on C heap
 87                         //   otherwise, allocate in _arena
 88 
 89   MEMFLAGS   _memflags;   // memory type if allocation in C heap
 90 
 91 #ifdef ASSERT
 92   int    _nesting;      // resource area nesting at creation
 93   void   set_nesting();
 94   void   check_nesting();
 95 #else
 96 #define  set_nesting();
 97 #define  check_nesting();
 98 #endif
 99 
100   // Where are we going to allocate memory?
101   bool on_C_heap() { return _arena == (Arena*)1; }
102   bool on_stack () { return _arena == NULL;      }
103   bool on_arena () { return _arena >  (Arena*)1;  }
104 
105   // This GA will use the resource stack for storage if c_heap==false,
106   // Else it will use the C heap.  Use clear_and_deallocate to avoid leaks.
107   GenericGrowableArray(int initial_size, int initial_len, bool c_heap, MEMFLAGS flags = mtNone) {
108     _len = initial_len;
109     _max = initial_size;
110     _memflags = flags;
111 
112     // memory type has to be specified for C heap allocation
113     assert(!(c_heap && flags == mtNone), "memory type not specified for C heap object");
114 
115     assert(_len >= 0 && _len <= _max, "initial_len too big");
116     _arena = (c_heap ? (Arena*)1 : NULL);
117     set_nesting();
118     assert(!on_C_heap() || allocated_on_C_heap(), "growable array must be on C heap if elements are");
119     assert(!on_stack() ||
120            (allocated_on_res_area() || allocated_on_stack()),
121            "growable array must be on stack if elements are not on arena and not on C heap");
122   }
123 
124   // This GA will use the given arena for storage.
125   // Consider using new(arena) GrowableArray<T> to allocate the header.
126   GenericGrowableArray(Arena* arena, int initial_size, int initial_len) {
127     _len = initial_len;
128     _max = initial_size;
129     assert(_len >= 0 && _len <= _max, "initial_len too big");
130     _arena = arena;
131     _memflags = mtNone;
132 
133     assert(on_arena(), "arena has taken on reserved value 0 or 1");
134     // Relax next assert to allow object allocation on resource area,
135     // on stack or embedded into an other object.
136     assert(allocated_on_arena() || allocated_on_stack(),
137            "growable array must be on arena or on stack if elements are on arena");
138   }
139 
140   void* raw_allocate(int elementSize);
141 
142   // some uses pass the Thread explicitly for speed (4990299 tuning)
143   void* raw_allocate(Thread* thread, int elementSize) {
144     assert(on_stack(), "fast ResourceObj path only");
145     return (void*)resource_allocate_bytes(thread, elementSize * _max);
146   }
147 
148   void free_C_heap(void* elements);
149 };
150 
151 template<class E> class GrowableArrayIterator;
152 template<class E, class UnaryPredicate> class GrowableArrayFilterIterator;
153 
154 template<class E> class GrowableArray : public GenericGrowableArray {
155   friend class VMStructs;
156 
157  private:
158   E*     _data;         // data array
159 
160   void grow(int j);
161   void raw_at_put_grow(int i, const E& p, const E& fill);
162   void  clear_and_deallocate();
163  public:
164   GrowableArray(Thread* thread, int initial_size) : GenericGrowableArray(initial_size, 0, false) {
165     _data = (E*)raw_allocate(thread, sizeof(E));
166     for (int i = 0; i < _max; i++) ::new ((void*)&_data[i]) E();
167   }
168 
169   GrowableArray(int initial_size, bool C_heap = false, MEMFLAGS F = mtInternal)
170     : GenericGrowableArray(initial_size, 0, C_heap, F) {
171     _data = (E*)raw_allocate(sizeof(E));
172 // Needed for Visual Studio 2012 and older
173 #ifdef _MSC_VER
174 #pragma warning(suppress: 4345)
175 #endif
176     for (int i = 0; i < _max; i++) ::new ((void*)&_data[i]) E();
177   }
178 
179   GrowableArray(int initial_size, int initial_len, const E& filler, bool C_heap = false, MEMFLAGS memflags = mtInternal)
180     : GenericGrowableArray(initial_size, initial_len, C_heap, memflags) {
181     _data = (E*)raw_allocate(sizeof(E));
182     int i = 0;
183     for (; i < _len; i++) ::new ((void*)&_data[i]) E(filler);
184     for (; i < _max; i++) ::new ((void*)&_data[i]) E();
185   }
186 
187   GrowableArray(Arena* arena, int initial_size, int initial_len, const E& filler) : GenericGrowableArray(arena, initial_size, initial_len) {
188     _data = (E*)raw_allocate(sizeof(E));
189     int i = 0;
190     for (; i < _len; i++) ::new ((void*)&_data[i]) E(filler);
191     for (; i < _max; i++) ::new ((void*)&_data[i]) E();
192   }
193 
194   GrowableArray() : GenericGrowableArray(2, 0, false) {
195     _data = (E*)raw_allocate(sizeof(E));
196     ::new ((void*)&_data[0]) E();
197     ::new ((void*)&_data[1]) E();
198   }
199 
200                                 // Does nothing for resource and arena objects
201   ~GrowableArray()              { if (on_C_heap()) clear_and_deallocate(); }
202 
203   void  clear()                 { _len = 0; }
204   int   length() const          { return _len; }
205   int   max_length() const      { return _max; }
206   void  trunc_to(int l)         { assert(l <= _len,"cannot increase length"); _len = l; }
207   bool  is_empty() const        { return _len == 0; }
208   bool  is_nonempty() const     { return _len != 0; }
209   bool  is_full() const         { return _len == _max; }
210   DEBUG_ONLY(E* data_addr() const      { return _data; })
211 
212   void print();
213 
214   int append(const E& elem) {
215     check_nesting();
216     if (_len == _max) grow(_len);
217     int idx = _len++;
218     _data[idx] = elem;
219     return idx;
220   }
221 
222   bool append_if_missing(const E& elem) {
223     // Returns TRUE if elem is added.
224     bool missed = !contains(elem);
225     if (missed) append(elem);
226     return missed;
227   }
228 
229   E& at(int i) {
230     assert(0 <= i && i < _len, "illegal index");
231     return _data[i];
232   }
233 
234   E const& at(int i) const {
235     assert(0 <= i && i < _len, "illegal index");
236     return _data[i];
237   }
238 
239   E* adr_at(int i) const {
240     assert(0 <= i && i < _len, "illegal index");
241     return &_data[i];
242   }
243 
244   E first() const {
245     assert(_len > 0, "empty list");
246     return _data[0];
247   }
248 
249   E top() const {
250     assert(_len > 0, "empty list");
251     return _data[_len-1];
252   }
253 
254   E last() const {
255     return top();
256   }
257 
258   GrowableArrayIterator<E> begin() const {
259     return GrowableArrayIterator<E>(this, 0);
260   }
261 
262   GrowableArrayIterator<E> end() const {
263     return GrowableArrayIterator<E>(this, length());
264   }
265 
266   void push(const E& elem) { append(elem); }
267 
268   E pop() {
269     assert(_len > 0, "empty list");
270     return _data[--_len];
271   }
272 
273   void at_put(int i, const E& elem) {
274     assert(0 <= i && i < _len, "illegal index");
275     _data[i] = elem;
276   }
277 
278   E at_grow(int i, const E& fill = E()) {
279     assert(0 <= i, "negative index");
280     check_nesting();
281     if (i >= _len) {
282       if (i >= _max) grow(i);
283       for (int j = _len; j <= i; j++)
284         _data[j] = fill;
285       _len = i+1;
286     }
287     return _data[i];
288   }
289 
290   void at_put_grow(int i, const E& elem, const E& fill = E()) {
291     assert(0 <= i, "negative index");
292     check_nesting();
293     raw_at_put_grow(i, elem, fill);
294   }
295 
296   bool contains(const E& elem) const {
297     for (int i = 0; i < _len; i++) {
298       if (_data[i] == elem) return true;
299     }
300     return false;
301   }
302 
303   int  find(const E& elem) const {
304     for (int i = 0; i < _len; i++) {
305       if (_data[i] == elem) return i;
306     }
307     return -1;
308   }
309 
310   int  find_from_end(const E& elem) const {
311     for (int i = _len-1; i >= 0; i--) {
312       if (_data[i] == elem) return i;
313     }
314     return -1;
315   }
316 
317   int  find(void* token, bool f(void*, E)) const {
318     for (int i = 0; i < _len; i++) {
319       if (f(token, _data[i])) return i;
320     }
321     return -1;
322   }
323 
324   int  find_from_end(void* token, bool f(void*, E)) const {
325     // start at the end of the array
326     for (int i = _len-1; i >= 0; i--) {
327       if (f(token, _data[i])) return i;
328     }
329     return -1;
330   }
331 
332   void remove(const E& elem) {
333     for (int i = 0; i < _len; i++) {
334       if (_data[i] == elem) {
335         for (int j = i + 1; j < _len; j++) _data[j-1] = _data[j];
336         _len--;
337         return;
338       }
339     }
340     ShouldNotReachHere();
341   }
342 
343   // The order is preserved.
344   void remove_at(int index) {
345     assert(0 <= index && index < _len, "illegal index");
346     for (int j = index + 1; j < _len; j++) _data[j-1] = _data[j];
347     _len--;
348   }
349 
350   // The order is changed.
351   void delete_at(int index) {
352     assert(0 <= index && index < _len, "illegal index");
353     if (index < --_len) {
354       // Replace removed element with last one.
355       _data[index] = _data[_len];
356     }
357   }
358 
359   // inserts the given element before the element at index i
360   void insert_before(const int idx, const E& elem) {
361     assert(0 <= idx && idx <= _len, "illegal index");
362     check_nesting();
363     if (_len == _max) grow(_len);
364     for (int j = _len - 1; j >= idx; j--) {
365       _data[j + 1] = _data[j];
366     }
367     _len++;
368     _data[idx] = elem;
369   }
370 
371   void insert_before(const int idx, const GrowableArray<E>* array) {
372     assert(0 <= idx && idx <= _len, "illegal index");
373     check_nesting();
374     int array_len = array->length();
375     int new_len = _len + array_len;
376     if (new_len >= _max) grow(new_len);
377 
378     for (int j = _len - 1; j >= idx; j--) {
379       _data[j + array_len] = _data[j];
380     }
381 
382     for (int j = 0; j < array_len; j++) {
383       _data[idx + j] = array->_data[j];
384     }
385 
386     _len += array_len;
387   }
388 
389   void appendAll(const GrowableArray<E>* l) {
390     for (int i = 0; i < l->_len; i++) {
391       raw_at_put_grow(_len, l->_data[i], E());
392     }
393   }
394 
395   void sort(int f(E*,E*)) {
396     qsort(_data, length(), sizeof(E), (_sort_Fn)f);
397   }
398   // sort by fixed-stride sub arrays:
399   void sort(int f(E*,E*), int stride) {
400     qsort(_data, length() / stride, sizeof(E) * stride, (_sort_Fn)f);
401   }
402 
403   // Binary search and insertion utility.  Search array for element
404   // matching key according to the static compare function.  Insert
405   // that element is not already in the list.  Assumes the list is
406   // already sorted according to compare function.
407   template <int compare(const E&, const E&)> E insert_sorted(const E& key) {
408     bool found;
409     int location = find_sorted<E, compare>(key, found);
410     if (!found) {
411       insert_before(location, key);
412     }
413     return at(location);
414   }
415 
416   template <typename K, int compare(const K&, const E&)> int find_sorted(const K& key, bool& found) {
417     found = false;
418     int min = 0;
419     int max = length() - 1;
420 
421     while (max >= min) {
422       int mid = (int)(((uint)max + min) / 2);
423       E value = at(mid);
424       int diff = compare(key, value);
425       if (diff > 0) {
426         min = mid + 1;
427       } else if (diff < 0) {
428         max = mid - 1;
429       } else {
430         found = true;
431         return mid;
432       }
433     }
434     return min;
435   }
436 };
437 
438 // Global GrowableArray methods (one instance in the library per each 'E' type).
439 
440 template<class E> void GrowableArray<E>::grow(int j) {
441     // grow the array by doubling its size (amortized growth)
442     int old_max = _max;
443     if (_max == 0) _max = 1; // prevent endless loop
444     while (j >= _max) _max = _max*2;
445     // j < _max
446     E* newData = (E*)raw_allocate(sizeof(E));
447     int i = 0;
448     for (     ; i < _len; i++) ::new ((void*)&newData[i]) E(_data[i]);
449 // Needed for Visual Studio 2012 and older
450 #ifdef _MSC_VER
451 #pragma warning(suppress: 4345)
452 #endif
453     for (     ; i < _max; i++) ::new ((void*)&newData[i]) E();
454     for (i = 0; i < old_max; i++) _data[i].~E();
455     if (on_C_heap() && _data != NULL) {
456       free_C_heap(_data);
457     }
458     _data = newData;
459 }
460 
461 template<class E> void GrowableArray<E>::raw_at_put_grow(int i, const E& p, const E& fill) {
462     if (i >= _len) {
463       if (i >= _max) grow(i);
464       for (int j = _len; j < i; j++)
465         _data[j] = fill;
466       _len = i+1;
467     }
468     _data[i] = p;
469 }
470 
471 // This function clears and deallocate the data in the growable array that
472 // has been allocated on the C heap.  It's not public - called by the
473 // destructor.
474 template<class E> void GrowableArray<E>::clear_and_deallocate() {
475     assert(on_C_heap(),
476            "clear_and_deallocate should only be called when on C heap");
477     clear();
478     if (_data != NULL) {
479       for (int i = 0; i < _max; i++) _data[i].~E();
480       free_C_heap(_data);
481       _data = NULL;
482     }
483 }
484 
485 template<class E> void GrowableArray<E>::print() {
486     tty->print("Growable Array " INTPTR_FORMAT, this);
487     tty->print(": length %ld (_max %ld) { ", _len, _max);
488     for (int i = 0; i < _len; i++) tty->print(INTPTR_FORMAT " ", *(intptr_t*)&(_data[i]));
489     tty->print("}\n");
490 }
491 
492 // Custom STL-style iterator to iterate over GrowableArrays
493 // It is constructed by invoking GrowableArray::begin() and GrowableArray::end()
494 template<class E> class GrowableArrayIterator : public StackObj {
495   friend class GrowableArray<E>;
496   template<class F, class UnaryPredicate> friend class GrowableArrayFilterIterator;
497 
498  private:
499   const GrowableArray<E>* _array; // GrowableArray we iterate over
500   int _position;                  // The current position in the GrowableArray
501 
502   // Private constructor used in GrowableArray::begin() and GrowableArray::end()
503   GrowableArrayIterator(const GrowableArray<E>* array, int position) : _array(array), _position(position) {
504     assert(0 <= position && position <= _array->length(), "illegal position");
505   }
506 
507  public:
508   GrowableArrayIterator() : _array(NULL), _position(0) { }
509   GrowableArrayIterator<E>& operator++()  { ++_position; return *this; }
510   E operator*()                           { return _array->at(_position); }
511 
512   bool operator==(const GrowableArrayIterator<E>& rhs)  {
513     assert(_array == rhs._array, "iterator belongs to different array");
514     return _position == rhs._position;
515   }
516 
517   bool operator!=(const GrowableArrayIterator<E>& rhs)  {
518     assert(_array == rhs._array, "iterator belongs to different array");
519     return _position != rhs._position;
520   }
521 };
522 
523 // Custom STL-style iterator to iterate over elements of a GrowableArray that satisfy a given predicate
524 template<class E, class UnaryPredicate> class GrowableArrayFilterIterator : public StackObj {
525   friend class GrowableArray<E>;
526 
527  private:
528   const GrowableArray<E>* _array;   // GrowableArray we iterate over
529   int _position;                    // Current position in the GrowableArray
530   UnaryPredicate _predicate;        // Unary predicate the elements of the GrowableArray should satisfy
531 
532  public:
533   GrowableArrayFilterIterator(const GrowableArrayIterator<E>& begin, UnaryPredicate filter_predicate)
534    : _array(begin._array), _position(begin._position), _predicate(filter_predicate) {
535     // Advance to first element satisfying the predicate
536     while(_position != _array->length() && !_predicate(_array->at(_position))) {
537       ++_position;
538     }
539   }
540 
541   GrowableArrayFilterIterator<E, UnaryPredicate>& operator++() {
542     do {
543       // Advance to next element satisfying the predicate
544       ++_position;
545     } while(_position != _array->length() && !_predicate(_array->at(_position)));
546     return *this;
547   }
548 
549   E operator*()   { return _array->at(_position); }
550 
551   bool operator==(const GrowableArrayIterator<E>& rhs)  {
552     assert(_array == rhs._array, "iterator belongs to different array");
553     return _position == rhs._position;
554   }
555 
556   bool operator!=(const GrowableArrayIterator<E>& rhs)  {
557     assert(_array == rhs._array, "iterator belongs to different array");
558     return _position != rhs._position;
559   }
560 
561   bool operator==(const GrowableArrayFilterIterator<E, UnaryPredicate>& rhs)  {
562     assert(_array == rhs._array, "iterator belongs to different array");
563     return _position == rhs._position;
564   }
565 
566   bool operator!=(const GrowableArrayFilterIterator<E, UnaryPredicate>& rhs)  {
567     assert(_array == rhs._array, "iterator belongs to different array");
568     return _position != rhs._position;
569   }
570 };
571 
572 // Arrays for basic types
573 typedef GrowableArray<int> intArray;
574 typedef GrowableArray<int> intStack;
575 typedef GrowableArray<bool> boolArray;
576 
577 #endif // SHARE_VM_UTILITIES_GROWABLEARRAY_HPP