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 "memory/allocation.inline.hpp"
  30 #include "utilities/debug.hpp"
  31 #include "utilities/globalDefinitions.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 
 149 template<class E> class GrowableArrayIterator;
 150 template<class E, class UnaryPredicate> class GrowableArrayFilterIterator;
 151 
 152 template<class E> class GrowableArray : public GenericGrowableArray {
 153   friend class VMStructs;
 154 
 155  private:
 156   E*     _data;         // data array
 157 
 158   void grow(int j);
 159   void raw_at_put_grow(int i, const E& p, const E& fill);
 160   void  clear_and_deallocate();
 161  public:
 162   GrowableArray(Thread* thread, int initial_size) : GenericGrowableArray(initial_size, 0, false) {
 163     _data = (E*)raw_allocate(thread, sizeof(E));
 164     for (int i = 0; i < _max; i++) ::new ((void*)&_data[i]) E();
 165   }
 166 
 167   GrowableArray(int initial_size, bool C_heap = false, MEMFLAGS F = mtInternal)
 168     : GenericGrowableArray(initial_size, 0, C_heap, F) {
 169     _data = (E*)raw_allocate(sizeof(E));
 170 // Needed for Visual Studio 2012 and older
 171 #ifdef _MSC_VER
 172 #pragma warning(suppress: 4345)
 173 #endif
 174     for (int i = 0; i < _max; i++) ::new ((void*)&_data[i]) E();
 175   }
 176 
 177   GrowableArray(int initial_size, int initial_len, const E& filler, bool C_heap = false, MEMFLAGS memflags = mtInternal)
 178     : GenericGrowableArray(initial_size, initial_len, C_heap, memflags) {
 179     _data = (E*)raw_allocate(sizeof(E));
 180     int i = 0;
 181     for (; i < _len; i++) ::new ((void*)&_data[i]) E(filler);
 182     for (; i < _max; i++) ::new ((void*)&_data[i]) E();
 183   }
 184 
 185   GrowableArray(Arena* arena, int initial_size, int initial_len, const E& filler) : GenericGrowableArray(arena, initial_size, initial_len) {
 186     _data = (E*)raw_allocate(sizeof(E));
 187     int i = 0;
 188     for (; i < _len; i++) ::new ((void*)&_data[i]) E(filler);
 189     for (; i < _max; i++) ::new ((void*)&_data[i]) E();
 190   }
 191 
 192   GrowableArray() : GenericGrowableArray(2, 0, false) {
 193     _data = (E*)raw_allocate(sizeof(E));
 194     ::new ((void*)&_data[0]) E();
 195     ::new ((void*)&_data[1]) E();
 196   }
 197 
 198                                 // Does nothing for resource and arena objects
 199   ~GrowableArray()              { if (on_C_heap()) clear_and_deallocate(); }
 200 
 201   void  clear()                 { _len = 0; }
 202   int   length() const          { return _len; }
 203   int   max_length() const      { return _max; }
 204   void  trunc_to(int l)         { assert(l <= _len,"cannot increase length"); _len = l; }
 205   bool  is_empty() const        { return _len == 0; }
 206   bool  is_nonempty() const     { return _len != 0; }
 207   bool  is_full() const         { return _len == _max; }
 208   DEBUG_ONLY(E* data_addr() const      { return _data; })
 209 
 210   void print();
 211 
 212   int append(const E& elem) {
 213     check_nesting();
 214     if (_len == _max) grow(_len);
 215     int idx = _len++;
 216     _data[idx] = elem;
 217     return idx;
 218   }
 219 
 220   bool append_if_missing(const E& elem) {
 221     // Returns TRUE if elem is added.
 222     bool missed = !contains(elem);
 223     if (missed) append(elem);
 224     return missed;
 225   }
 226 
 227   E& at(int i) {
 228     assert(0 <= i && i < _len, "illegal index");
 229     return _data[i];
 230   }
 231 
 232   E const& at(int i) const {
 233     assert(0 <= i && i < _len, "illegal index");
 234     return _data[i];
 235   }
 236 
 237   E* adr_at(int i) const {
 238     assert(0 <= i && i < _len, "illegal index");
 239     return &_data[i];
 240   }
 241 
 242   E first() const {
 243     assert(_len > 0, "empty list");
 244     return _data[0];
 245   }
 246 
 247   E top() const {
 248     assert(_len > 0, "empty list");
 249     return _data[_len-1];
 250   }
 251 
 252   E last() const {
 253     return top();
 254   }
 255 
 256   GrowableArrayIterator<E> begin() const {
 257     return GrowableArrayIterator<E>(this, 0);
 258   }
 259 
 260   GrowableArrayIterator<E> end() const {
 261     return GrowableArrayIterator<E>(this, length());
 262   }
 263 
 264   void push(const E& elem) { append(elem); }
 265 
 266   E pop() {
 267     assert(_len > 0, "empty list");
 268     return _data[--_len];
 269   }
 270 
 271   void at_put(int i, const E& elem) {
 272     assert(0 <= i && i < _len, "illegal index");
 273     _data[i] = elem;
 274   }
 275 
 276   E at_grow(int i, const E& fill = E()) {
 277     assert(0 <= i, "negative index");
 278     check_nesting();
 279     if (i >= _len) {
 280       if (i >= _max) grow(i);
 281       for (int j = _len; j <= i; j++)
 282         _data[j] = fill;
 283       _len = i+1;
 284     }
 285     return _data[i];
 286   }
 287 
 288   void at_put_grow(int i, const E& elem, const E& fill = E()) {
 289     assert(0 <= i, "negative index");
 290     check_nesting();
 291     raw_at_put_grow(i, elem, fill);
 292   }
 293 
 294   bool contains(const E& elem) const {
 295     for (int i = 0; i < _len; i++) {
 296       if (_data[i] == elem) return true;
 297     }
 298     return false;
 299   }
 300 
 301   int  find(const E& elem) const {
 302     for (int i = 0; i < _len; i++) {
 303       if (_data[i] == elem) return i;
 304     }
 305     return -1;
 306   }
 307 
 308   int  find_from_end(const E& elem) const {
 309     for (int i = _len-1; i >= 0; i--) {
 310       if (_data[i] == elem) return i;
 311     }
 312     return -1;
 313   }
 314 
 315   int  find(void* token, bool f(void*, E)) const {
 316     for (int i = 0; i < _len; i++) {
 317       if (f(token, _data[i])) return i;
 318     }
 319     return -1;
 320   }
 321 
 322   int  find_from_end(void* token, bool f(void*, E)) const {
 323     // start at the end of the array
 324     for (int i = _len-1; i >= 0; i--) {
 325       if (f(token, _data[i])) return i;
 326     }
 327     return -1;
 328   }
 329 
 330   void remove(const E& elem) {
 331     for (int i = 0; i < _len; i++) {
 332       if (_data[i] == elem) {
 333         for (int j = i + 1; j < _len; j++) _data[j-1] = _data[j];
 334         _len--;
 335         return;
 336       }
 337     }
 338     ShouldNotReachHere();
 339   }
 340 
 341   // The order is preserved.
 342   void remove_at(int index) {
 343     assert(0 <= index && index < _len, "illegal index");
 344     for (int j = index + 1; j < _len; j++) _data[j-1] = _data[j];
 345     _len--;
 346   }
 347 
 348   // The order is changed.
 349   void delete_at(int index) {
 350     assert(0 <= index && index < _len, "illegal index");
 351     if (index < --_len) {
 352       // Replace removed element with last one.
 353       _data[index] = _data[_len];
 354     }
 355   }
 356 
 357   // inserts the given element before the element at index i
 358   void insert_before(const int idx, const E& elem) {
 359     assert(0 <= idx && idx <= _len, "illegal index");
 360     check_nesting();
 361     if (_len == _max) grow(_len);
 362     for (int j = _len - 1; j >= idx; j--) {
 363       _data[j + 1] = _data[j];
 364     }
 365     _len++;
 366     _data[idx] = elem;
 367   }
 368 
 369   void insert_before(const int idx, const GrowableArray<E>* array) {
 370     assert(0 <= idx && idx <= _len, "illegal index");
 371     check_nesting();
 372     int array_len = array->length();
 373     int new_len = _len + array_len;
 374     if (new_len >= _max) grow(new_len);
 375 
 376     for (int j = _len - 1; j >= idx; j--) {
 377       _data[j + array_len] = _data[j];
 378     }
 379 
 380     for (int j = 0; j < array_len; j++) {
 381       _data[idx + j] = array->_data[j];
 382     }
 383 
 384     _len += array_len;
 385   }
 386 
 387   void appendAll(const GrowableArray<E>* l) {
 388     for (int i = 0; i < l->_len; i++) {
 389       raw_at_put_grow(_len, l->_data[i], E());
 390     }
 391   }
 392 
 393   void sort(int f(E*,E*)) {
 394     qsort(_data, length(), sizeof(E), (_sort_Fn)f);
 395   }
 396   // sort by fixed-stride sub arrays:
 397   void sort(int f(E*,E*), int stride) {
 398     qsort(_data, length() / stride, sizeof(E) * stride, (_sort_Fn)f);
 399   }
 400 
 401   // Binary search and insertion utility.  Search array for element
 402   // matching key according to the static compare function.  Insert
 403   // that element is not already in the list.  Assumes the list is
 404   // already sorted according to compare function.
 405   template <int compare(const E&, const E&)> E insert_sorted(E& key) {
 406     bool found;
 407     int location = find_sorted<E, compare>(key, found);
 408     if (!found) {
 409       insert_before(location, key);
 410     }
 411     return at(location);
 412   }
 413 
 414   template <typename K, int compare(const K&, const E&)> int find_sorted(const K& key, bool& found) {
 415     found = false;
 416     int min = 0;
 417     int max = length() - 1;
 418 
 419     while (max >= min) {
 420       int mid = (int)(((uint)max + min) / 2);
 421       E value = at(mid);
 422       int diff = compare(key, value);
 423       if (diff > 0) {
 424         min = mid + 1;
 425       } else if (diff < 0) {
 426         max = mid - 1;
 427       } else {
 428         found = true;
 429         return mid;
 430       }
 431     }
 432     return min;
 433   }
 434 };
 435 
 436 // Global GrowableArray methods (one instance in the library per each 'E' type).
 437 
 438 template<class E> void GrowableArray<E>::grow(int j) {
 439     // grow the array by doubling its size (amortized growth)
 440     int old_max = _max;
 441     if (_max == 0) _max = 1; // prevent endless loop
 442     while (j >= _max) _max = _max*2;
 443     // j < _max
 444     E* newData = (E*)raw_allocate(sizeof(E));
 445     int i = 0;
 446     for (     ; i < _len; i++) ::new ((void*)&newData[i]) E(_data[i]);
 447 // Needed for Visual Studio 2012 and older
 448 #ifdef _MSC_VER
 449 #pragma warning(suppress: 4345)
 450 #endif
 451     for (     ; i < _max; i++) ::new ((void*)&newData[i]) E();
 452     for (i = 0; i < old_max; i++) _data[i].~E();
 453     if (on_C_heap() && _data != NULL) {
 454       FreeHeap(_data);
 455     }
 456     _data = newData;
 457 }
 458 
 459 template<class E> void GrowableArray<E>::raw_at_put_grow(int i, const E& p, const E& fill) {
 460     if (i >= _len) {
 461       if (i >= _max) grow(i);
 462       for (int j = _len; j < i; j++)
 463         _data[j] = fill;
 464       _len = i+1;
 465     }
 466     _data[i] = p;
 467 }
 468 
 469 // This function clears and deallocate the data in the growable array that
 470 // has been allocated on the C heap.  It's not public - called by the
 471 // destructor.
 472 template<class E> void GrowableArray<E>::clear_and_deallocate() {
 473     assert(on_C_heap(),
 474            "clear_and_deallocate should only be called when on C heap");
 475     clear();
 476     if (_data != NULL) {
 477       for (int i = 0; i < _max; i++) _data[i].~E();
 478       FreeHeap(_data);
 479       _data = NULL;
 480     }
 481 }
 482 
 483 template<class E> void GrowableArray<E>::print() {
 484     tty->print("Growable Array " INTPTR_FORMAT, this);
 485     tty->print(": length %ld (_max %ld) { ", _len, _max);
 486     for (int i = 0; i < _len; i++) tty->print(INTPTR_FORMAT " ", *(intptr_t*)&(_data[i]));
 487     tty->print("}\n");
 488 }
 489 
 490 // Custom STL-style iterator to iterate over GrowableArrays
 491 // It is constructed by invoking GrowableArray::begin() and GrowableArray::end()
 492 template<class E> class GrowableArrayIterator : public StackObj {
 493   friend class GrowableArray<E>;
 494   template<class F, class UnaryPredicate> friend class GrowableArrayFilterIterator;
 495 
 496  private:
 497   const GrowableArray<E>* _array; // GrowableArray we iterate over
 498   int _position;                  // The current position in the GrowableArray
 499 
 500   // Private constructor used in GrowableArray::begin() and GrowableArray::end()
 501   GrowableArrayIterator(const GrowableArray<E>* array, int position) : _array(array), _position(position) {
 502     assert(0 <= position && position <= _array->length(), "illegal position");
 503   }
 504 
 505  public:
 506   GrowableArrayIterator() : _array(NULL), _position(0) { }
 507   GrowableArrayIterator<E>& operator++()  { ++_position; return *this; }
 508   E operator*()                           { return _array->at(_position); }
 509 
 510   bool operator==(const GrowableArrayIterator<E>& rhs)  {
 511     assert(_array == rhs._array, "iterator belongs to different array");
 512     return _position == rhs._position;
 513   }
 514 
 515   bool operator!=(const GrowableArrayIterator<E>& rhs)  {
 516     assert(_array == rhs._array, "iterator belongs to different array");
 517     return _position != rhs._position;
 518   }
 519 };
 520 
 521 // Custom STL-style iterator to iterate over elements of a GrowableArray that satisfy a given predicate
 522 template<class E, class UnaryPredicate> class GrowableArrayFilterIterator : public StackObj {
 523   friend class GrowableArray<E>;
 524 
 525  private:
 526   const GrowableArray<E>* _array;   // GrowableArray we iterate over
 527   int _position;                    // Current position in the GrowableArray
 528   UnaryPredicate _predicate;        // Unary predicate the elements of the GrowableArray should satisfy
 529 
 530  public:
 531   GrowableArrayFilterIterator(const GrowableArrayIterator<E>& begin, UnaryPredicate filter_predicate)
 532    : _array(begin._array), _position(begin._position), _predicate(filter_predicate) {
 533     // Advance to first element satisfying the predicate
 534     while(_position != _array->length() && !_predicate(_array->at(_position))) {
 535       ++_position;
 536     }
 537   }
 538 
 539   GrowableArrayFilterIterator<E, UnaryPredicate>& operator++() {
 540     do {
 541       // Advance to next element satisfying the predicate
 542       ++_position;
 543     } while(_position != _array->length() && !_predicate(_array->at(_position)));
 544     return *this;
 545   }
 546 
 547   E operator*()   { return _array->at(_position); }
 548 
 549   bool operator==(const GrowableArrayIterator<E>& rhs)  {
 550     assert(_array == rhs._array, "iterator belongs to different array");
 551     return _position == rhs._position;
 552   }
 553 
 554   bool operator!=(const GrowableArrayIterator<E>& rhs)  {
 555     assert(_array == rhs._array, "iterator belongs to different array");
 556     return _position != rhs._position;
 557   }
 558 
 559   bool operator==(const GrowableArrayFilterIterator<E, UnaryPredicate>& rhs)  {
 560     assert(_array == rhs._array, "iterator belongs to different array");
 561     return _position == rhs._position;
 562   }
 563 
 564   bool operator!=(const GrowableArrayFilterIterator<E, UnaryPredicate>& rhs)  {
 565     assert(_array == rhs._array, "iterator belongs to different array");
 566     return _position != rhs._position;
 567   }
 568 };
 569 
 570 // Arrays for basic types
 571 typedef GrowableArray<int> intArray;
 572 typedef GrowableArray<int> intStack;
 573 typedef GrowableArray<bool> boolArray;
 574 
 575 #endif // SHARE_VM_UTILITIES_GROWABLEARRAY_HPP