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