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