1 /*
   2  * Copyright (c) 1997, 2012, 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 #ifdef ASSERT
  90   int    _nesting;      // resource area nesting at creation
  91   void   set_nesting();
  92   void   check_nesting();
  93 #else
  94 #define  set_nesting();
  95 #define  check_nesting();
  96 #endif
  97 
  98   // Where are we going to allocate memory?
  99   bool on_C_heap() { return _arena == (Arena*)1; }
 100   bool on_stack () { return _arena == NULL;      }
 101   bool on_arena () { return _arena >  (Arena*)1;  }
 102 
 103   // This GA will use the resource stack for storage if c_heap==false,
 104   // Else it will use the C heap.  Use clear_and_deallocate to avoid leaks.
 105   GenericGrowableArray(int initial_size, int initial_len, bool c_heap) {
 106     _len = initial_len;
 107     _max = initial_size;
 108     assert(_len >= 0 && _len <= _max, "initial_len too big");
 109     _arena = (c_heap ? (Arena*)1 : NULL);
 110     set_nesting();
 111     assert(!on_C_heap() || allocated_on_C_heap(), "growable array must be on C heap if elements are");
 112     assert(!on_stack() ||
 113            (allocated_on_res_area() || allocated_on_stack()),
 114            "growable array must be on stack if elements are not on arena and not on C heap");
 115   }
 116 
 117   // This GA will use the given arena for storage.
 118   // Consider using new(arena) GrowableArray<T> to allocate the header.
 119   GenericGrowableArray(Arena* arena, int initial_size, int initial_len) {
 120     _len = initial_len;
 121     _max = initial_size;
 122     assert(_len >= 0 && _len <= _max, "initial_len too big");
 123     _arena = arena;
 124     assert(on_arena(), "arena has taken on reserved value 0 or 1");
 125     // Relax next assert to allow object allocation on resource area,
 126     // on stack or embedded into an other object.
 127     assert(allocated_on_arena() || allocated_on_stack(),
 128            "growable array must be on arena or on stack if elements are on arena");
 129   }
 130 
 131   void* raw_allocate(int elementSize);
 132 
 133   // some uses pass the Thread explicitly for speed (4990299 tuning)
 134   void* raw_allocate(Thread* thread, int elementSize) {
 135     assert(on_stack(), "fast ResourceObj path only");
 136     return (void*)resource_allocate_bytes(thread, elementSize * _max);
 137   }
 138 };
 139 
 140 template<class E> class GrowableArray : public GenericGrowableArray {
 141   friend class VMStructs;
 142 
 143  private:
 144   E*     _data;         // data array
 145 
 146   void grow(int j);
 147   void raw_at_put_grow(int i, const E& p, const E& fill);
 148   void  clear_and_deallocate();
 149  public:
 150   GrowableArray(Thread* thread, int initial_size) : GenericGrowableArray(initial_size, 0, false) {
 151     _data = (E*)raw_allocate(thread, sizeof(E));
 152     for (int i = 0; i < _max; i++) ::new ((void*)&_data[i]) E();
 153   }
 154 
 155   GrowableArray(int initial_size, bool C_heap = false) : GenericGrowableArray(initial_size, 0, C_heap) {
 156     _data = (E*)raw_allocate(sizeof(E));
 157     for (int i = 0; i < _max; i++) ::new ((void*)&_data[i]) E();
 158   }
 159 
 160   GrowableArray(int initial_size, int initial_len, const E& filler, bool C_heap = false) : GenericGrowableArray(initial_size, initial_len, C_heap) {
 161     _data = (E*)raw_allocate(sizeof(E));
 162     int i = 0;
 163     for (; i < _len; i++) ::new ((void*)&_data[i]) E(filler);
 164     for (; i < _max; i++) ::new ((void*)&_data[i]) E();
 165   }
 166 
 167   GrowableArray(Arena* arena, int initial_size, int initial_len, const E& filler) : GenericGrowableArray(arena, initial_size, initial_len) {
 168     _data = (E*)raw_allocate(sizeof(E));
 169     int i = 0;
 170     for (; i < _len; i++) ::new ((void*)&_data[i]) E(filler);
 171     for (; i < _max; i++) ::new ((void*)&_data[i]) E();
 172   }
 173 
 174   GrowableArray() : GenericGrowableArray(2, 0, false) {
 175     _data = (E*)raw_allocate(sizeof(E));
 176     ::new ((void*)&_data[0]) E();
 177     ::new ((void*)&_data[1]) E();
 178   }
 179 
 180                                 // Does nothing for resource and arena objects
 181   ~GrowableArray()              { if (on_C_heap()) clear_and_deallocate(); }
 182 
 183   void  clear()                 { _len = 0; }
 184   int   length() const          { return _len; }
 185   void  trunc_to(int l)         { assert(l <= _len,"cannot increase length"); _len = l; }
 186   bool  is_empty() const        { return _len == 0; }
 187   bool  is_nonempty() const     { return _len != 0; }
 188   bool  is_full() const         { return _len == _max; }
 189   DEBUG_ONLY(E* data_addr() const      { return _data; })
 190 
 191   void print();
 192 
 193   int append(const E& elem) {
 194     check_nesting();
 195     if (_len == _max) grow(_len);
 196     int idx = _len++;
 197     _data[idx] = elem;
 198     return idx;
 199   }
 200 
 201   void append_if_missing(const E& elem) {
 202     if (!contains(elem)) append(elem);
 203   }
 204 
 205   E at(int i) const {
 206     assert(0 <= i && i < _len, "illegal index");
 207     return _data[i];
 208   }
 209 
 210   E* adr_at(int i) const {
 211     assert(0 <= i && i < _len, "illegal index");
 212     return &_data[i];
 213   }
 214 
 215   E first() const {
 216     assert(_len > 0, "empty list");
 217     return _data[0];
 218   }
 219 
 220   E top() const {
 221     assert(_len > 0, "empty list");
 222     return _data[_len-1];
 223   }
 224 
 225   void push(const E& elem) { append(elem); }
 226 
 227   E pop() {
 228     assert(_len > 0, "empty list");
 229     return _data[--_len];
 230   }
 231 
 232   void at_put(int i, const E& elem) {
 233     assert(0 <= i && i < _len, "illegal index");
 234     _data[i] = elem;
 235   }
 236 
 237   E at_grow(int i, const E& fill = E()) {
 238     assert(0 <= i, "negative index");
 239     check_nesting();
 240     if (i >= _len) {
 241       if (i >= _max) grow(i);
 242       for (int j = _len; j <= i; j++)
 243         _data[j] = fill;
 244       _len = i+1;
 245     }
 246     return _data[i];
 247   }
 248 
 249   void at_put_grow(int i, const E& elem, const E& fill = E()) {
 250     assert(0 <= i, "negative index");
 251     check_nesting();
 252     raw_at_put_grow(i, elem, fill);
 253   }
 254 
 255   bool contains(const E& elem) const {
 256     for (int i = 0; i < _len; i++) {
 257       if (_data[i] == elem) return true;
 258     }
 259     return false;
 260   }
 261 
 262   int  find(const E& elem) const {
 263     for (int i = 0; i < _len; i++) {
 264       if (_data[i] == elem) return i;
 265     }
 266     return -1;
 267   }
 268 
 269   int  find(void* token, bool f(void*, E)) const {
 270     for (int i = 0; i < _len; i++) {
 271       if (f(token, _data[i])) return i;
 272     }
 273     return -1;
 274   }
 275 
 276   int  find_at_end(void* token, bool f(void*, E)) const {
 277     // start at the end of the array
 278     for (int i = _len-1; i >= 0; i--) {
 279       if (f(token, _data[i])) return i;
 280     }
 281     return -1;
 282   }
 283 
 284   void remove(const E& elem) {
 285     for (int i = 0; i < _len; i++) {
 286       if (_data[i] == elem) {
 287         for (int j = i + 1; j < _len; j++) _data[j-1] = _data[j];
 288         _len--;
 289         return;
 290       }
 291     }
 292     ShouldNotReachHere();
 293   }
 294 
 295   // The order is preserved.
 296   void remove_at(int index) {
 297     assert(0 <= index && index < _len, "illegal index");
 298     for (int j = index + 1; j < _len; j++) _data[j-1] = _data[j];
 299     _len--;
 300   }
 301 
 302   // The order is changed.
 303   void delete_at(int index) {
 304     assert(0 <= index && index < _len, "illegal index");
 305     if (index < --_len) {
 306       // Replace removed element with last one.
 307       _data[index] = _data[_len];
 308     }
 309   }
 310 
 311   // inserts the given element before the element at index i
 312   void insert_before(const int idx, const E& elem) {
 313     check_nesting();
 314     if (_len == _max) grow(_len);
 315     for (int j = _len - 1; j >= idx; j--) {
 316       _data[j + 1] = _data[j];
 317     }
 318     _len++;
 319     _data[idx] = elem;
 320   }
 321 
 322   void appendAll(const GrowableArray<E>* l) {
 323     for (int i = 0; i < l->_len; i++) {
 324       raw_at_put_grow(_len, l->_data[i], 0);
 325     }
 326   }
 327 
 328   void sort(int f(E*,E*)) {
 329     qsort(_data, length(), sizeof(E), (_sort_Fn)f);
 330   }
 331   // sort by fixed-stride sub arrays:
 332   void sort(int f(E*,E*), int stride) {
 333     qsort(_data, length() / stride, sizeof(E) * stride, (_sort_Fn)f);
 334   }
 335 };
 336 
 337 // Global GrowableArray methods (one instance in the library per each 'E' type).
 338 
 339 template<class E> void GrowableArray<E>::grow(int j) {
 340     // grow the array by doubling its size (amortized growth)
 341     int old_max = _max;
 342     if (_max == 0) _max = 1; // prevent endless loop
 343     while (j >= _max) _max = _max*2;
 344     // j < _max
 345     E* newData = (E*)raw_allocate(sizeof(E));
 346     int i = 0;
 347     for (     ; i < _len; i++) ::new ((void*)&newData[i]) E(_data[i]);
 348     for (     ; i < _max; i++) ::new ((void*)&newData[i]) E();
 349     for (i = 0; i < old_max; i++) _data[i].~E();
 350     if (on_C_heap() && _data != NULL) {
 351       FreeHeap(_data);
 352     }
 353     _data = newData;
 354 }
 355 
 356 template<class E> void GrowableArray<E>::raw_at_put_grow(int i, const E& p, const E& fill) {
 357     if (i >= _len) {
 358       if (i >= _max) grow(i);
 359       for (int j = _len; j < i; j++)
 360         _data[j] = fill;
 361       _len = i+1;
 362     }
 363     _data[i] = p;
 364 }
 365 
 366 // This function clears and deallocate the data in the growable array that
 367 // has been allocated on the C heap.  It's not public - called by the
 368 // destructor.
 369 template<class E> void GrowableArray<E>::clear_and_deallocate() {
 370     assert(on_C_heap(),
 371            "clear_and_deallocate should only be called when on C heap");
 372     clear();
 373     if (_data != NULL) {
 374       for (int i = 0; i < _max; i++) _data[i].~E();
 375       FreeHeap(_data);
 376       _data = NULL;
 377     }
 378 }
 379 
 380 template<class E> void GrowableArray<E>::print() {
 381     tty->print("Growable Array " INTPTR_FORMAT, this);
 382     tty->print(": length %ld (_max %ld) { ", _len, _max);
 383     for (int i = 0; i < _len; i++) tty->print(INTPTR_FORMAT " ", *(intptr_t*)&(_data[i]));
 384     tty->print("}\n");
 385 }
 386 
 387 #endif // SHARE_VM_UTILITIES_GROWABLEARRAY_HPP