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