1 /*
   2  * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2018, 2019 SAP SE. All rights reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 // With this declaration macro, it is possible to switch between
  27 //  - direct output into an argument-passed outputStream and
  28 //  - buffered output into a bufferedStream with subsequent flush
  29 //    of the filled buffer to the outputStream.
  30 #define USE_BUFFEREDSTREAM
  31 
  32 #include "precompiled.hpp"
  33 #include "code/codeHeapState.hpp"
  34 #include "compiler/compileBroker.hpp"
  35 #include "runtime/sweeper.hpp"
  36 
  37 // -------------------------
  38 // |  General Description  |
  39 // -------------------------
  40 // The CodeHeap state analytics are divided in two parts.
  41 // The first part examines the entire CodeHeap and aggregates all
  42 // information that is believed useful/important.
  43 //
  44 // Aggregation condenses the information of a piece of the CodeHeap
  45 // (4096 bytes by default) into an analysis granule. These granules
  46 // contain enough detail to gain initial insight while keeping the
  47 // internal structure sizes in check.
  48 //
  49 // The second part, which consists of several, independent steps,
  50 // prints the previously collected information with emphasis on
  51 // various aspects.
  52 //
  53 // The CodeHeap is a living thing. Therefore, protection against concurrent
  54 // modification (by acquiring the CodeCache_lock) is necessary. It has
  55 // to be provided by the caller of the analysis functions.
  56 // If the CodeCache_lock is not held, the analysis functions may print
  57 // less detailed information or may just do nothing. It is by intention
  58 // that an unprotected invocation is not abnormally terminated.
  59 //
  60 // Data collection and printing is done on an "on request" basis.
  61 // While no request is being processed, there is no impact on performance.
  62 // The CodeHeap state analytics do have some memory footprint.
  63 // The "aggregate" step allocates some data structures to hold the aggregated
  64 // information for later output. These data structures live until they are
  65 // explicitly discarded (function "discard") or until the VM terminates.
  66 // There is one exception: the function "all" does not leave any data
  67 // structures allocated.
  68 //
  69 // Requests for real-time, on-the-fly analysis can be issued via
  70 //   jcmd <pid> Compiler.CodeHeap_Analytics [<function>] [<granularity>]
  71 //
  72 // If you are (only) interested in how the CodeHeap looks like after running
  73 // a sample workload, you can use the command line option
  74 //   -XX:+PrintCodeHeapAnalytics
  75 // It will cause a full analysis to be written to tty. In addition, a full
  76 // analysis will be written the first time a "CodeCache full" condition is
  77 // detected.
  78 //
  79 // The command line option produces output identical to the jcmd function
  80 //   jcmd <pid> Compiler.CodeHeap_Analytics all 4096
  81 // ---------------------------------------------------------------------------------
  82 //
  83 // There are instances when composing an output line or a small set of
  84 // output lines out of many tty->print() calls creates significant overhead.
  85 // Writing to a bufferedStream buffer first has a significant advantage:
  86 // It uses noticeably less cpu cycles and reduces (when writing to a
  87 // network file) the required bandwidth by at least a factor of ten. Observed on MacOS.
  88 // That clearly makes up for the increased code complexity.
  89 //
  90 // Conversion of existing code is easy and straightforward, if the code already
  91 // uses a parameterized output destination, e.g. "outputStream st".
  92 //  - rename the formal parameter to any other name, e.g. out_st.
  93 //  - at a suitable place in your code, insert
  94 //      BUFFEREDSTEAM_DECL(buf_st, out_st)
  95 // This will provide all the declarations necessary. After that, all
  96 // buf_st->print() (and the like) calls will be directed to a bufferedStream object.
  97 // Once a block of output (a line or a small set of lines) is composed, insert
  98 //      BUFFEREDSTREAM_FLUSH(termstring)
  99 // to flush the bufferedStream to the final destination out_st. termstring is just
 100 // an arbitrary string (e.g. "\n") which is appended to the bufferedStream before
 101 // being written to out_st. Be aware that the last character written MUST be a '\n'.
 102 // Otherwise, buf_st->position() does not correspond to out_st->position() any longer.
 103 //      BUFFEREDSTREAM_FLUSH_LOCKED(termstring)
 104 // does the same thing, protected by the ttyLocker lock.
 105 //      BUFFEREDSTREAM_FLUSH_IF(termstring, remSize)
 106 // does a flush only if the remaining buffer space is less than remSize.
 107 //
 108 // To activate, #define USE_BUFFERED_STREAM before including this header.
 109 // If not activated, output will directly go to the originally used outputStream
 110 // with no additional overhead.
 111 //
 112 #if defined(USE_BUFFEREDSTREAM)
 113 #define BUFFEREDSTREAM_DECL_SIZE(_anyst, _outst, _capa)       \
 114     ResourceMark         _rm;                                 \
 115     /* _anyst  name of the stream as used in the code */      \
 116     /* _outst  stream where final output will go to   */      \
 117     /* _capa   allocated capacity of stream buffer    */      \
 118     size_t           _nflush = 0;                             \
 119     size_t     _nforcedflush = 0;                             \
 120     size_t      _nsavedflush = 0;                             \
 121     size_t     _nlockedflush = 0;                             \
 122     size_t     _nflush_bytes = 0;                             \
 123     size_t         _capacity = _capa;                         \
 124     bufferedStream   _sstobj = bufferedStream(_capa);         \
 125     bufferedStream*  _sstbuf = &_sstobj;                      \
 126     outputStream*    _outbuf = _outst;                        \
 127     bufferedStream*   _anyst = &_sstobj; /* any stream. Use this to just print - no buffer flush.  */
 128 
 129 #define BUFFEREDSTREAM_DECL(_anyst, _outst)                   \
 130     BUFFEREDSTREAM_DECL_SIZE(_anyst, _outst, 4*K);
 131 
 132 #define BUFFEREDSTREAM_FLUSH(_termString)                     \
 133     if ((_termString != NULL) && (strlen(_termString) > 0)) { \
 134       _sstbuf->print("%s", _termString);                      \
 135     }                                                         \
 136     if (_sstbuf != _outbuf) {                                 \
 137       if (_sstbuf->size() != 0) {                             \
 138         _nforcedflush++; _nflush_bytes += _sstbuf->size();    \
 139         _outbuf->print("%s", _sstbuf->as_string());           \
 140         _sstbuf->reset();                                     \
 141       }                                                       \
 142     }
 143 
 144 #define BUFFEREDSTREAM_FLUSH_IF(_termString, _remSize)        \
 145     if (_sstbuf != _outbuf) {                                 \
 146       if ((_capacity - _sstbuf->size()) < (size_t)_remSize) { \
 147         _nflush++; _nforcedflush--;                           \
 148         BUFFEREDSTREAM_FLUSH(_termString)                     \
 149       } else {                                                \
 150         _nsavedflush++;                                       \
 151       }                                                       \
 152     }
 153 
 154 #define BUFFEREDSTREAM_FLUSH_LOCKED(_termString)              \
 155     { ttyLocker ttyl;/* keep this output block together */    \
 156       _nlockedflush++;                                        \
 157       BUFFEREDSTREAM_FLUSH(_termString)                       \
 158     }
 159 
 160 // #define BUFFEREDSTREAM_FLUSH_STAT()                           \
 161 //     if (_sstbuf != _outbuf) {                                 \
 162 //       _outbuf->print_cr("%ld flushes (buffer full), %ld forced, %ld locked, %ld bytes total, %ld flushes saved", _nflush, _nforcedflush, _nlockedflush, _nflush_bytes, _nsavedflush); \
 163 //    }
 164 
 165 #define BUFFEREDSTREAM_FLUSH_STAT()
 166 #else
 167 #define BUFFEREDSTREAM_DECL_SIZE(_anyst, _outst, _capa)       \
 168     size_t       _capacity = _capa;                           \
 169     outputStream*  _outbuf = _outst;                          \
 170     outputStream*  _anyst  = _outst;   /* any stream. Use this to just print - no buffer flush.  */
 171 
 172 #define BUFFEREDSTREAM_DECL(_anyst, _outst)                   \
 173     BUFFEREDSTREAM_DECL_SIZE(_anyst, _outst, 4*K)
 174 
 175 #define BUFFEREDSTREAM_FLUSH_IF(_termString, _remSize)        \
 176     if ((_termString != NULL) && (strlen(_termString) > 0)) { \
 177       _outbuf->print("%s", _termString);                      \
 178     }
 179 
 180 #define BUFFEREDSTREAM_FLUSH(_termString)                     \
 181     if ((_termString != NULL) && (strlen(_termString) > 0)) { \
 182       _outbuf->print("%s", _termString);                      \
 183     }
 184 
 185 #define BUFFEREDSTREAM_FLUSH_LOCKED(_termString)              \
 186     if ((_termString != NULL) && (strlen(_termString) > 0)) { \
 187       _outbuf->print("%s", _termString);                      \
 188     }
 189 
 190 #define BUFFEREDSTREAM_FLUSH_STAT()
 191 #endif
 192 #define HEX32_FORMAT  "0x%x"  // just a helper format string used below multiple times
 193 
 194 const char  blobTypeChar[] = {' ', 'C', 'N', 'I', 'X', 'Z', 'U', 'R', '?', 'D', 'T', 'E', 'S', 'A', 'M', 'B', 'L' };
 195 const char* blobTypeName[] = {"noType"
 196                              ,     "nMethod (under construction)"
 197                              ,          "nMethod (active)"
 198                              ,               "nMethod (inactive)"
 199                              ,                    "nMethod (deopt)"
 200                              ,                         "nMethod (zombie)"
 201                              ,                              "nMethod (unloaded)"
 202                              ,                                   "runtime stub"
 203                              ,                                        "ricochet stub"
 204                              ,                                             "deopt stub"
 205                              ,                                                  "uncommon trap stub"
 206                              ,                                                       "exception stub"
 207                              ,                                                            "safepoint stub"
 208                              ,                                                                 "adapter blob"
 209                              ,                                                                      "MH adapter blob"
 210                              ,                                                                           "buffer blob"
 211                              ,                                                                                "lastType"
 212                              };
 213 const char* compTypeName[] = { "none", "c1", "c2", "jvmci" };
 214 
 215 // Be prepared for ten different CodeHeap segments. Should be enough for a few years.
 216 const  unsigned int        nSizeDistElements = 31;  // logarithmic range growth, max size: 2**32
 217 const  unsigned int        maxTopSizeBlocks  = 50;
 218 const  unsigned int        tsbStopper        = 2 * maxTopSizeBlocks;
 219 const  unsigned int        maxHeaps          = 10;
 220 static unsigned int        nHeaps            = 0;
 221 static struct CodeHeapStat CodeHeapStatArray[maxHeaps];
 222 
 223 // static struct StatElement *StatArray      = NULL;
 224 static StatElement* StatArray             = NULL;
 225 static int          log2_seg_size         = 0;
 226 static size_t       seg_size              = 0;
 227 static size_t       alloc_granules        = 0;
 228 static size_t       granule_size          = 0;
 229 static bool         segment_granules      = false;
 230 static unsigned int nBlocks_t1            = 0;  // counting "in_use" nmethods only.
 231 static unsigned int nBlocks_t2            = 0;  // counting "in_use" nmethods only.
 232 static unsigned int nBlocks_alive         = 0;  // counting "not_used" and "not_entrant" nmethods only.
 233 static unsigned int nBlocks_dead          = 0;  // counting "zombie" and "unloaded" methods only.
 234 static unsigned int nBlocks_inconstr      = 0;  // counting "inconstruction" nmethods only. This is a transient state.
 235 static unsigned int nBlocks_unloaded      = 0;  // counting "unloaded" nmethods only. This is a transient state.
 236 static unsigned int nBlocks_stub          = 0;
 237 
 238 static struct FreeBlk*          FreeArray = NULL;
 239 static unsigned int      alloc_freeBlocks = 0;
 240 
 241 static struct TopSizeBlk*    TopSizeArray = NULL;
 242 static unsigned int   alloc_topSizeBlocks = 0;
 243 static unsigned int    used_topSizeBlocks = 0;
 244 
 245 static struct SizeDistributionElement*  SizeDistributionArray = NULL;
 246 
 247 // nMethod temperature (hotness) indicators.
 248 static int                     avgTemp    = 0;
 249 static int                     maxTemp    = 0;
 250 static int                     minTemp    = 0;
 251 
 252 static unsigned int  latest_compilation_id   = 0;
 253 static volatile bool initialization_complete = false;
 254 
 255 const char* CodeHeapState::get_heapName(CodeHeap* heap) {
 256   if (SegmentedCodeCache) {
 257     return heap->name();
 258   } else {
 259     return "CodeHeap";
 260   }
 261 }
 262 
 263 // returns the index for the heap being processed.
 264 unsigned int CodeHeapState::findHeapIndex(outputStream* out, const char* heapName) {
 265   if (heapName == NULL) {
 266     return maxHeaps;
 267   }
 268   if (SegmentedCodeCache) {
 269     // Search for a pre-existing entry. If found, return that index.
 270     for (unsigned int i = 0; i < nHeaps; i++) {
 271       if (CodeHeapStatArray[i].heapName != NULL && strcmp(heapName, CodeHeapStatArray[i].heapName) == 0) {
 272         return i;
 273       }
 274     }
 275 
 276     // check if there are more code heap segments than we can handle.
 277     if (nHeaps == maxHeaps) {
 278       out->print_cr("Too many heap segments for current limit(%d).", maxHeaps);
 279       return maxHeaps;
 280     }
 281 
 282     // allocate new slot in StatArray.
 283     CodeHeapStatArray[nHeaps].heapName = heapName;
 284     return nHeaps++;
 285   } else {
 286     nHeaps = 1;
 287     CodeHeapStatArray[0].heapName = heapName;
 288     return 0; // This is the default index if CodeCache is not segmented.
 289   }
 290 }
 291 
 292 void CodeHeapState::get_HeapStatGlobals(outputStream* out, const char* heapName) {
 293   unsigned int ix = findHeapIndex(out, heapName);
 294   if (ix < maxHeaps) {
 295     StatArray             = CodeHeapStatArray[ix].StatArray;
 296     seg_size              = CodeHeapStatArray[ix].segment_size;
 297     log2_seg_size         = seg_size == 0 ? 0 : exact_log2(seg_size);
 298     alloc_granules        = CodeHeapStatArray[ix].alloc_granules;
 299     granule_size          = CodeHeapStatArray[ix].granule_size;
 300     segment_granules      = CodeHeapStatArray[ix].segment_granules;
 301     nBlocks_t1            = CodeHeapStatArray[ix].nBlocks_t1;
 302     nBlocks_t2            = CodeHeapStatArray[ix].nBlocks_t2;
 303     nBlocks_alive         = CodeHeapStatArray[ix].nBlocks_alive;
 304     nBlocks_dead          = CodeHeapStatArray[ix].nBlocks_dead;
 305     nBlocks_inconstr      = CodeHeapStatArray[ix].nBlocks_inconstr;
 306     nBlocks_unloaded      = CodeHeapStatArray[ix].nBlocks_unloaded;
 307     nBlocks_stub          = CodeHeapStatArray[ix].nBlocks_stub;
 308     FreeArray             = CodeHeapStatArray[ix].FreeArray;
 309     alloc_freeBlocks      = CodeHeapStatArray[ix].alloc_freeBlocks;
 310     TopSizeArray          = CodeHeapStatArray[ix].TopSizeArray;
 311     alloc_topSizeBlocks   = CodeHeapStatArray[ix].alloc_topSizeBlocks;
 312     used_topSizeBlocks    = CodeHeapStatArray[ix].used_topSizeBlocks;
 313     SizeDistributionArray = CodeHeapStatArray[ix].SizeDistributionArray;
 314     avgTemp               = CodeHeapStatArray[ix].avgTemp;
 315     maxTemp               = CodeHeapStatArray[ix].maxTemp;
 316     minTemp               = CodeHeapStatArray[ix].minTemp;
 317   } else {
 318     StatArray             = NULL;
 319     seg_size              = 0;
 320     log2_seg_size         = 0;
 321     alloc_granules        = 0;
 322     granule_size          = 0;
 323     segment_granules      = false;
 324     nBlocks_t1            = 0;
 325     nBlocks_t2            = 0;
 326     nBlocks_alive         = 0;
 327     nBlocks_dead          = 0;
 328     nBlocks_inconstr      = 0;
 329     nBlocks_unloaded      = 0;
 330     nBlocks_stub          = 0;
 331     FreeArray             = NULL;
 332     alloc_freeBlocks      = 0;
 333     TopSizeArray          = NULL;
 334     alloc_topSizeBlocks   = 0;
 335     used_topSizeBlocks    = 0;
 336     SizeDistributionArray = NULL;
 337     avgTemp               = 0;
 338     maxTemp               = 0;
 339     minTemp               = 0;
 340   }
 341 }
 342 
 343 void CodeHeapState::set_HeapStatGlobals(outputStream* out, const char* heapName) {
 344   unsigned int ix = findHeapIndex(out, heapName);
 345   if (ix < maxHeaps) {
 346     CodeHeapStatArray[ix].StatArray             = StatArray;
 347     CodeHeapStatArray[ix].segment_size          = seg_size;
 348     CodeHeapStatArray[ix].alloc_granules        = alloc_granules;
 349     CodeHeapStatArray[ix].granule_size          = granule_size;
 350     CodeHeapStatArray[ix].segment_granules      = segment_granules;
 351     CodeHeapStatArray[ix].nBlocks_t1            = nBlocks_t1;
 352     CodeHeapStatArray[ix].nBlocks_t2            = nBlocks_t2;
 353     CodeHeapStatArray[ix].nBlocks_alive         = nBlocks_alive;
 354     CodeHeapStatArray[ix].nBlocks_dead          = nBlocks_dead;
 355     CodeHeapStatArray[ix].nBlocks_inconstr      = nBlocks_inconstr;
 356     CodeHeapStatArray[ix].nBlocks_unloaded      = nBlocks_unloaded;
 357     CodeHeapStatArray[ix].nBlocks_stub          = nBlocks_stub;
 358     CodeHeapStatArray[ix].FreeArray             = FreeArray;
 359     CodeHeapStatArray[ix].alloc_freeBlocks      = alloc_freeBlocks;
 360     CodeHeapStatArray[ix].TopSizeArray          = TopSizeArray;
 361     CodeHeapStatArray[ix].alloc_topSizeBlocks   = alloc_topSizeBlocks;
 362     CodeHeapStatArray[ix].used_topSizeBlocks    = used_topSizeBlocks;
 363     CodeHeapStatArray[ix].SizeDistributionArray = SizeDistributionArray;
 364     CodeHeapStatArray[ix].avgTemp               = avgTemp;
 365     CodeHeapStatArray[ix].maxTemp               = maxTemp;
 366     CodeHeapStatArray[ix].minTemp               = minTemp;
 367   }
 368 }
 369 
 370 //---<  get a new statistics array  >---
 371 void CodeHeapState::prepare_StatArray(outputStream* out, size_t nElem, size_t granularity, const char* heapName) {
 372   if (StatArray == NULL) {
 373     StatArray      = new StatElement[nElem];
 374     //---<  reset some counts  >---
 375     alloc_granules = nElem;
 376     granule_size   = granularity;
 377   }
 378 
 379   if (StatArray == NULL) {
 380     //---<  just do nothing if allocation failed  >---
 381     out->print_cr("Statistics could not be collected for %s, probably out of memory.", heapName);
 382     out->print_cr("Current granularity is " SIZE_FORMAT " bytes. Try a coarser granularity.", granularity);
 383     alloc_granules = 0;
 384     granule_size   = 0;
 385   } else {
 386     //---<  initialize statistics array  >---
 387     memset((void*)StatArray, 0, nElem*sizeof(StatElement));
 388   }
 389 }
 390 
 391 //---<  get a new free block array  >---
 392 void CodeHeapState::prepare_FreeArray(outputStream* out, unsigned int nElem, const char* heapName) {
 393   if (FreeArray == NULL) {
 394     FreeArray      = new FreeBlk[nElem];
 395     //---<  reset some counts  >---
 396     alloc_freeBlocks = nElem;
 397   }
 398 
 399   if (FreeArray == NULL) {
 400     //---<  just do nothing if allocation failed  >---
 401     out->print_cr("Free space analysis cannot be done for %s, probably out of memory.", heapName);
 402     alloc_freeBlocks = 0;
 403   } else {
 404     //---<  initialize free block array  >---
 405     memset((void*)FreeArray, 0, alloc_freeBlocks*sizeof(FreeBlk));
 406   }
 407 }
 408 
 409 //---<  get a new TopSizeArray  >---
 410 void CodeHeapState::prepare_TopSizeArray(outputStream* out, unsigned int nElem, const char* heapName) {
 411   if (TopSizeArray == NULL) {
 412     TopSizeArray   = new TopSizeBlk[nElem];
 413     //---<  reset some counts  >---
 414     alloc_topSizeBlocks = nElem;
 415     used_topSizeBlocks  = 0;
 416   }
 417 
 418   if (TopSizeArray == NULL) {
 419     //---<  just do nothing if allocation failed  >---
 420     out->print_cr("Top-%d list of largest CodeHeap blocks can not be collected for %s, probably out of memory.", nElem, heapName);
 421     alloc_topSizeBlocks = 0;
 422   } else {
 423     //---<  initialize TopSizeArray  >---
 424     memset((void*)TopSizeArray, 0, nElem*sizeof(TopSizeBlk));
 425     used_topSizeBlocks  = 0;
 426   }
 427 }
 428 
 429 //---<  get a new SizeDistributionArray  >---
 430 void CodeHeapState::prepare_SizeDistArray(outputStream* out, unsigned int nElem, const char* heapName) {
 431   if (SizeDistributionArray == NULL) {
 432     SizeDistributionArray = new SizeDistributionElement[nElem];
 433   }
 434 
 435   if (SizeDistributionArray == NULL) {
 436     //---<  just do nothing if allocation failed  >---
 437     out->print_cr("Size distribution can not be collected for %s, probably out of memory.", heapName);
 438   } else {
 439     //---<  initialize SizeDistArray  >---
 440     memset((void*)SizeDistributionArray, 0, nElem*sizeof(SizeDistributionElement));
 441     // Logarithmic range growth. First range starts at _segment_size.
 442     SizeDistributionArray[log2_seg_size-1].rangeEnd = 1U;
 443     for (unsigned int i = log2_seg_size; i < nElem; i++) {
 444       SizeDistributionArray[i].rangeStart = 1U << (i     - log2_seg_size);
 445       SizeDistributionArray[i].rangeEnd   = 1U << ((i+1) - log2_seg_size);
 446     }
 447   }
 448 }
 449 
 450 //---<  get a new SizeDistributionArray  >---
 451 void CodeHeapState::update_SizeDistArray(outputStream* out, unsigned int len) {
 452   if (SizeDistributionArray != NULL) {
 453     for (unsigned int i = log2_seg_size-1; i < nSizeDistElements; i++) {
 454       if ((SizeDistributionArray[i].rangeStart <= len) && (len < SizeDistributionArray[i].rangeEnd)) {
 455         SizeDistributionArray[i].lenSum += len;
 456         SizeDistributionArray[i].count++;
 457         break;
 458       }
 459     }
 460   }
 461 }
 462 
 463 void CodeHeapState::discard_StatArray(outputStream* out) {
 464   if (StatArray != NULL) {
 465     delete StatArray;
 466     StatArray        = NULL;
 467     alloc_granules   = 0;
 468     granule_size     = 0;
 469   }
 470 }
 471 
 472 void CodeHeapState::discard_FreeArray(outputStream* out) {
 473   if (FreeArray != NULL) {
 474     delete[] FreeArray;
 475     FreeArray        = NULL;
 476     alloc_freeBlocks = 0;
 477   }
 478 }
 479 
 480 void CodeHeapState::discard_TopSizeArray(outputStream* out) {
 481   if (TopSizeArray != NULL) {
 482     delete[] TopSizeArray;
 483     TopSizeArray        = NULL;
 484     alloc_topSizeBlocks = 0;
 485     used_topSizeBlocks  = 0;
 486   }
 487 }
 488 
 489 void CodeHeapState::discard_SizeDistArray(outputStream* out) {
 490   if (SizeDistributionArray != NULL) {
 491     delete[] SizeDistributionArray;
 492     SizeDistributionArray = NULL;
 493   }
 494 }
 495 
 496 // Discard all allocated internal data structures.
 497 // This should be done after an analysis session is completed.
 498 void CodeHeapState::discard(outputStream* out, CodeHeap* heap) {
 499   if (!initialization_complete) {
 500     return;
 501   }
 502 
 503   if (nHeaps > 0) {
 504     for (unsigned int ix = 0; ix < nHeaps; ix++) {
 505       get_HeapStatGlobals(out, CodeHeapStatArray[ix].heapName);
 506       discard_StatArray(out);
 507       discard_FreeArray(out);
 508       discard_TopSizeArray(out);
 509       discard_SizeDistArray(out);
 510       set_HeapStatGlobals(out, CodeHeapStatArray[ix].heapName);
 511       CodeHeapStatArray[ix].heapName = NULL;
 512     }
 513     nHeaps = 0;
 514   }
 515 }
 516 
 517 void CodeHeapState::aggregate(outputStream* out, CodeHeap* heap, const char* granularity_request) {
 518   unsigned int nBlocks_free    = 0;
 519   unsigned int nBlocks_used    = 0;
 520   unsigned int nBlocks_zomb    = 0;
 521   unsigned int nBlocks_disconn = 0;
 522   unsigned int nBlocks_notentr = 0;
 523 
 524   //---<  max & min of TopSizeArray  >---
 525   //  it is sufficient to have these sizes as 32bit unsigned ints.
 526   //  The CodeHeap is limited in size to 4GB. Furthermore, the sizes
 527   //  are stored in _segment_size units, scaling them down by a factor of 64 (at least).
 528   unsigned int  currMax          = 0;
 529   unsigned int  currMin          = 0;
 530   unsigned int  currMin_ix       = 0;
 531   unsigned long total_iterations = 0;
 532 
 533   bool  done             = false;
 534   const int min_granules = 256;
 535   const int max_granules = 512*K; // limits analyzable CodeHeap (with segment_granules) to 32M..128M
 536                                   // results in StatArray size of 24M (= max_granules * 48 Bytes per element)
 537                                   // For a 1GB CodeHeap, the granule size must be at least 2kB to not violate the max_granles limit.
 538   const char* heapName   = get_heapName(heap);
 539   BUFFEREDSTREAM_DECL(ast, out)
 540 
 541   if (!initialization_complete) {
 542     memset(CodeHeapStatArray, 0, sizeof(CodeHeapStatArray));
 543     initialization_complete = true;
 544 
 545     printBox(ast, '=', "C O D E   H E A P   A N A L Y S I S   (general remarks)", NULL);
 546     ast->print_cr("   The code heap analysis function provides deep insights into\n"
 547                   "   the inner workings and the internal state of the Java VM's\n"
 548                   "   code cache - the place where all the JVM generated machine\n"
 549                   "   code is stored.\n"
 550                   "   \n"
 551                   "   This function is designed and provided for support engineers\n"
 552                   "   to help them understand and solve issues in customer systems.\n"
 553                   "   It is not intended for use and interpretation by other persons.\n"
 554                   "   \n");
 555     BUFFEREDSTREAM_FLUSH("")
 556   }
 557   get_HeapStatGlobals(out, heapName);
 558 
 559 
 560   // Since we are (and must be) analyzing the CodeHeap contents under the CodeCache_lock,
 561   // all heap information is "constant" and can be safely extracted/calculated before we
 562   // enter the while() loop. Actually, the loop will only be iterated once.
 563   char*  low_bound     = heap->low_boundary();
 564   size_t size          = heap->capacity();
 565   size_t res_size      = heap->max_capacity();
 566   seg_size             = heap->segment_size();
 567   log2_seg_size        = seg_size == 0 ? 0 : exact_log2(seg_size);  // This is a global static value.
 568 
 569   if (seg_size == 0) {
 570     printBox(ast, '-', "Heap not fully initialized yet, segment size is zero for segment ", heapName);
 571     BUFFEREDSTREAM_FLUSH("")
 572     return;
 573   }
 574 
 575   if (!CodeCache_lock->owned_by_self()) {
 576     printBox(ast, '-', "aggregate function called without holding the CodeCache_lock for ", heapName);
 577     BUFFEREDSTREAM_FLUSH("")
 578     return;
 579   }
 580 
 581   // Calculate granularity of analysis (and output).
 582   //   The CodeHeap is managed (allocated) in segments (units) of CodeCacheSegmentSize.
 583   //   The CodeHeap can become fairly large, in particular in productive real-life systems.
 584   //
 585   //   It is often neither feasible nor desirable to aggregate the data with the highest possible
 586   //   level of detail, i.e. inspecting and printing each segment on its own.
 587   //
 588   //   The granularity parameter allows to specify the level of detail available in the analysis.
 589   //   It must be a positive multiple of the segment size and should be selected such that enough
 590   //   detail is provided while, at the same time, the printed output does not explode.
 591   //
 592   //   By manipulating the granularity value, we enforce that at least min_granules units
 593   //   of analysis are available. We also enforce an upper limit of max_granules units to
 594   //   keep the amount of allocated storage in check.
 595   //
 596   //   Finally, we adjust the granularity such that each granule covers at most 64k-1 segments.
 597   //   This is necessary to prevent an unsigned short overflow while accumulating space information.
 598   //
 599   size_t granularity = strtol(granularity_request, NULL, 0);
 600   if (granularity > size) {
 601     granularity = size;
 602   }
 603   if (size/granularity < min_granules) {
 604     granularity = size/min_granules;                                   // at least min_granules granules
 605   }
 606   granularity = granularity & (~(seg_size - 1));                       // must be multiple of seg_size
 607   if (granularity < seg_size) {
 608     granularity = seg_size;                                            // must be at least seg_size
 609   }
 610   if (size/granularity > max_granules) {
 611     granularity = size/max_granules;                                   // at most max_granules granules
 612   }
 613   granularity = granularity & (~(seg_size - 1));                       // must be multiple of seg_size
 614   if (granularity>>log2_seg_size >= (1L<<sizeof(unsigned short)*8)) {
 615     granularity = ((1L<<(sizeof(unsigned short)*8))-1)<<log2_seg_size; // Limit: (64k-1) * seg_size
 616   }
 617   segment_granules = granularity == seg_size;
 618   size_t granules  = (size + (granularity-1))/granularity;
 619 
 620   printBox(ast, '=', "C O D E   H E A P   A N A L Y S I S   (used blocks) for segment ", heapName);
 621   ast->print_cr("   The aggregate step takes an aggregated snapshot of the CodeHeap.\n"
 622                 "   Subsequent print functions create their output based on this snapshot.\n"
 623                 "   The CodeHeap is a living thing, and every effort has been made for the\n"
 624                 "   collected data to be consistent. Only the method names and signatures\n"
 625                 "   are retrieved at print time. That may lead to rare cases where the\n"
 626                 "   name of a method is no longer available, e.g. because it was unloaded.\n");
 627   ast->print_cr("   CodeHeap committed size " SIZE_FORMAT "K (" SIZE_FORMAT "M), reserved size " SIZE_FORMAT "K (" SIZE_FORMAT "M), %d%% occupied.",
 628                 size/(size_t)K, size/(size_t)M, res_size/(size_t)K, res_size/(size_t)M, (unsigned int)(100.0*size/res_size));
 629   ast->print_cr("   CodeHeap allocation segment size is " SIZE_FORMAT " bytes. This is the smallest possible granularity.", seg_size);
 630   ast->print_cr("   CodeHeap (committed part) is mapped to " SIZE_FORMAT " granules of size " SIZE_FORMAT " bytes.", granules, granularity);
 631   ast->print_cr("   Each granule takes " SIZE_FORMAT " bytes of C heap, that is " SIZE_FORMAT "K in total for statistics data.", sizeof(StatElement), (sizeof(StatElement)*granules)/(size_t)K);
 632   ast->print_cr("   The number of granules is limited to %dk, requiring a granules size of at least %d bytes for a 1GB heap.", (unsigned int)(max_granules/K), (unsigned int)(G/max_granules));
 633   BUFFEREDSTREAM_FLUSH("\n")
 634 
 635 
 636   while (!done) {
 637     //---<  reset counters with every aggregation  >---
 638     nBlocks_t1       = 0;
 639     nBlocks_t2       = 0;
 640     nBlocks_alive    = 0;
 641     nBlocks_dead     = 0;
 642     nBlocks_inconstr = 0;
 643     nBlocks_unloaded = 0;
 644     nBlocks_stub     = 0;
 645 
 646     nBlocks_free     = 0;
 647     nBlocks_used     = 0;
 648     nBlocks_zomb     = 0;
 649     nBlocks_disconn  = 0;
 650     nBlocks_notentr  = 0;
 651 
 652     //---<  discard old arrays if size does not match  >---
 653     if (granules != alloc_granules) {
 654       discard_StatArray(out);
 655       discard_TopSizeArray(out);
 656     }
 657 
 658     //---<  allocate arrays if they don't yet exist, initialize  >---
 659     prepare_StatArray(out, granules, granularity, heapName);
 660     if (StatArray == NULL) {
 661       set_HeapStatGlobals(out, heapName);
 662       return;
 663     }
 664     prepare_TopSizeArray(out, maxTopSizeBlocks, heapName);
 665     prepare_SizeDistArray(out, nSizeDistElements, heapName);
 666 
 667     latest_compilation_id = CompileBroker::get_compilation_id();
 668     unsigned int highest_compilation_id = 0;
 669     size_t       usedSpace     = 0;
 670     size_t       t1Space       = 0;
 671     size_t       t2Space       = 0;
 672     size_t       aliveSpace    = 0;
 673     size_t       disconnSpace  = 0;
 674     size_t       notentrSpace  = 0;
 675     size_t       deadSpace     = 0;
 676     size_t       inconstrSpace = 0;
 677     size_t       unloadedSpace = 0;
 678     size_t       stubSpace     = 0;
 679     size_t       freeSpace     = 0;
 680     size_t       maxFreeSize   = 0;
 681     HeapBlock*   maxFreeBlock  = NULL;
 682     bool         insane        = false;
 683 
 684     int64_t hotnessAccumulator = 0;
 685     unsigned int n_methods     = 0;
 686     avgTemp       = 0;
 687     minTemp       = (int)(res_size > M ? (res_size/M)*2 : 1);
 688     maxTemp       = -minTemp;
 689 
 690     for (HeapBlock *h = heap->first_block(); h != NULL && !insane; h = heap->next_block(h)) {
 691       unsigned int hb_len     = (unsigned int)h->length();  // despite being size_t, length can never overflow an unsigned int.
 692       size_t       hb_bytelen = ((size_t)hb_len)<<log2_seg_size;
 693       unsigned int ix_beg     = (unsigned int)(((char*)h-low_bound)/granule_size);
 694       unsigned int ix_end     = (unsigned int)(((char*)h-low_bound+(hb_bytelen-1))/granule_size);
 695       unsigned int compile_id = 0;
 696       CompLevel    comp_lvl   = CompLevel_none;
 697       compType     cType      = noComp;
 698       blobType     cbType     = noType;
 699 
 700       //---<  some sanity checks  >---
 701       // Do not assert here, just check, print error message and return.
 702       // This is a diagnostic function. It is not supposed to tear down the VM.
 703       if ((char*)h <  low_bound) {
 704         insane = true; ast->print_cr("Sanity check: HeapBlock @%p below low bound (%p)", (char*)h, low_bound);
 705       }
 706       if ((char*)h >  (low_bound + res_size)) {
 707         insane = true; ast->print_cr("Sanity check: HeapBlock @%p outside reserved range (%p)", (char*)h, low_bound + res_size);
 708       }
 709       if ((char*)h >  (low_bound + size)) {
 710         insane = true; ast->print_cr("Sanity check: HeapBlock @%p outside used range (%p)", (char*)h, low_bound + size);
 711       }
 712       if (ix_end   >= granules) {
 713         insane = true; ast->print_cr("Sanity check: end index (%d) out of bounds (" SIZE_FORMAT ")", ix_end, granules);
 714       }
 715       if (size     != heap->capacity()) {
 716         insane = true; ast->print_cr("Sanity check: code heap capacity has changed (" SIZE_FORMAT "K to " SIZE_FORMAT "K)", size/(size_t)K, heap->capacity()/(size_t)K);
 717       }
 718       if (ix_beg   >  ix_end) {
 719         insane = true; ast->print_cr("Sanity check: end index (%d) lower than begin index (%d)", ix_end, ix_beg);
 720       }
 721       if (insane) {
 722         BUFFEREDSTREAM_FLUSH("")
 723         continue;
 724       }
 725 
 726       if (h->free()) {
 727         nBlocks_free++;
 728         freeSpace    += hb_bytelen;
 729         if (hb_bytelen > maxFreeSize) {
 730           maxFreeSize   = hb_bytelen;
 731           maxFreeBlock  = h;
 732         }
 733       } else {
 734         update_SizeDistArray(out, hb_len);
 735         nBlocks_used++;
 736         usedSpace    += hb_bytelen;
 737         CodeBlob* cb  = (CodeBlob*)heap->find_start(h);
 738         if (cb != NULL) {
 739           cbType = get_cbType(cb);
 740           if (cb->is_nmethod()) {
 741             compile_id = ((nmethod*)cb)->compile_id();
 742             comp_lvl   = (CompLevel)((nmethod*)cb)->comp_level();
 743             if (((nmethod*)cb)->is_compiled_by_c1()) {
 744               cType = c1;
 745             }
 746             if (((nmethod*)cb)->is_compiled_by_c2()) {
 747               cType = c2;
 748             }
 749             if (((nmethod*)cb)->is_compiled_by_jvmci()) {
 750               cType = jvmci;
 751             }
 752             switch (cbType) {
 753               case nMethod_inuse: { // only for executable methods!!!
 754                 // space for these cbs is accounted for later.
 755                 int temperature = ((nmethod*)cb)->hotness_counter();
 756                 hotnessAccumulator += temperature;
 757                 n_methods++;
 758                 maxTemp = (temperature > maxTemp) ? temperature : maxTemp;
 759                 minTemp = (temperature < minTemp) ? temperature : minTemp;
 760                 break;
 761               }
 762               case nMethod_notused:
 763                 nBlocks_alive++;
 764                 nBlocks_disconn++;
 765                 aliveSpace     += hb_bytelen;
 766                 disconnSpace   += hb_bytelen;
 767                 break;
 768               case nMethod_notentrant:  // equivalent to nMethod_alive
 769                 nBlocks_alive++;
 770                 nBlocks_notentr++;
 771                 aliveSpace     += hb_bytelen;
 772                 notentrSpace   += hb_bytelen;
 773                 break;
 774               case nMethod_unloaded:
 775                 nBlocks_unloaded++;
 776                 unloadedSpace  += hb_bytelen;
 777                 break;
 778               case nMethod_dead:
 779                 nBlocks_dead++;
 780                 deadSpace      += hb_bytelen;
 781                 break;
 782               case nMethod_inconstruction:
 783                 nBlocks_inconstr++;
 784                 inconstrSpace  += hb_bytelen;
 785                 break;
 786               default:
 787                 break;
 788             }
 789           }
 790 
 791           //------------------------------------------
 792           //---<  register block in TopSizeArray  >---
 793           //------------------------------------------
 794           if (alloc_topSizeBlocks > 0) {
 795             if (used_topSizeBlocks == 0) {
 796               TopSizeArray[0].start    = h;
 797               TopSizeArray[0].len      = hb_len;
 798               TopSizeArray[0].index    = tsbStopper;
 799               TopSizeArray[0].compiler = cType;
 800               TopSizeArray[0].level    = comp_lvl;
 801               TopSizeArray[0].type     = cbType;
 802               currMax    = hb_len;
 803               currMin    = hb_len;
 804               currMin_ix = 0;
 805               used_topSizeBlocks++;
 806             // This check roughly cuts 5000 iterations (JVM98, mixed, dbg, termination stats):
 807             } else if ((used_topSizeBlocks < alloc_topSizeBlocks) && (hb_len < currMin)) {
 808               //---<  all blocks in list are larger, but there is room left in array  >---
 809               TopSizeArray[currMin_ix].index = used_topSizeBlocks;
 810               TopSizeArray[used_topSizeBlocks].start    = h;
 811               TopSizeArray[used_topSizeBlocks].len      = hb_len;
 812               TopSizeArray[used_topSizeBlocks].index    = tsbStopper;
 813               TopSizeArray[used_topSizeBlocks].compiler = cType;
 814               TopSizeArray[used_topSizeBlocks].level    = comp_lvl;
 815               TopSizeArray[used_topSizeBlocks].type     = cbType;
 816               currMin    = hb_len;
 817               currMin_ix = used_topSizeBlocks;
 818               used_topSizeBlocks++;
 819             } else {
 820               // This check cuts total_iterations by a factor of 6 (JVM98, mixed, dbg, termination stats):
 821               //   We don't need to search the list if we know beforehand that the current block size is
 822               //   smaller than the currently recorded minimum and there is no free entry left in the list.
 823               if (!((used_topSizeBlocks == alloc_topSizeBlocks) && (hb_len <= currMin))) {
 824                 if (currMax < hb_len) {
 825                   currMax = hb_len;
 826                 }
 827                 unsigned int i;
 828                 unsigned int prev_i  = tsbStopper;
 829                 unsigned int limit_i =  0;
 830                 for (i = 0; i != tsbStopper; i = TopSizeArray[i].index) {
 831                   if (limit_i++ >= alloc_topSizeBlocks) {
 832                     insane = true; break; // emergency exit
 833                   }
 834                   if (i >= used_topSizeBlocks)  {
 835                     insane = true; break; // emergency exit
 836                   }
 837                   total_iterations++;
 838                   if (TopSizeArray[i].len < hb_len) {
 839                     //---<  We want to insert here, element <i> is smaller than the current one  >---
 840                     if (used_topSizeBlocks < alloc_topSizeBlocks) { // still room for a new entry to insert
 841                       // old entry gets moved to the next free element of the array.
 842                       // That's necessary to keep the entry for the largest block at index 0.
 843                       // This move might cause the current minimum to be moved to another place
 844                       if (i == currMin_ix) {
 845                         assert(TopSizeArray[i].len == currMin, "sort error");
 846                         currMin_ix = used_topSizeBlocks;
 847                       }
 848                       memcpy((void*)&TopSizeArray[used_topSizeBlocks], (void*)&TopSizeArray[i], sizeof(TopSizeBlk));
 849                       TopSizeArray[i].start    = h;
 850                       TopSizeArray[i].len      = hb_len;
 851                       TopSizeArray[i].index    = used_topSizeBlocks;
 852                       TopSizeArray[i].compiler = cType;
 853                       TopSizeArray[i].level    = comp_lvl;
 854                       TopSizeArray[i].type     = cbType;
 855                       used_topSizeBlocks++;
 856                     } else { // no room for new entries, current block replaces entry for smallest block
 857                       //---<  Find last entry (entry for smallest remembered block)  >---
 858                       unsigned int      j  = i;
 859                       unsigned int prev_j  = tsbStopper;
 860                       unsigned int limit_j = 0;
 861                       while (TopSizeArray[j].index != tsbStopper) {
 862                         if (limit_j++ >= alloc_topSizeBlocks) {
 863                           insane = true; break; // emergency exit
 864                         }
 865                         if (j >= used_topSizeBlocks)  {
 866                           insane = true; break; // emergency exit
 867                         }
 868                         total_iterations++;
 869                         prev_j = j;
 870                         j      = TopSizeArray[j].index;
 871                       }
 872                       if (!insane) {
 873                         if (prev_j == tsbStopper) {
 874                           //---<  Above while loop did not iterate, we already are the min entry  >---
 875                           //---<  We have to just replace the smallest entry                      >---
 876                           currMin    = hb_len;
 877                           currMin_ix = j;
 878                           TopSizeArray[j].start    = h;
 879                           TopSizeArray[j].len      = hb_len;
 880                           TopSizeArray[j].index    = tsbStopper; // already set!!
 881                           TopSizeArray[j].compiler = cType;
 882                           TopSizeArray[j].level    = comp_lvl;
 883                           TopSizeArray[j].type     = cbType;
 884                         } else {
 885                           //---<  second-smallest entry is now smallest  >---
 886                           TopSizeArray[prev_j].index = tsbStopper;
 887                           currMin    = TopSizeArray[prev_j].len;
 888                           currMin_ix = prev_j;
 889                           //---<  smallest entry gets overwritten  >---
 890                           memcpy((void*)&TopSizeArray[j], (void*)&TopSizeArray[i], sizeof(TopSizeBlk));
 891                           TopSizeArray[i].start    = h;
 892                           TopSizeArray[i].len      = hb_len;
 893                           TopSizeArray[i].index    = j;
 894                           TopSizeArray[i].compiler = cType;
 895                           TopSizeArray[i].level    = comp_lvl;
 896                           TopSizeArray[i].type     = cbType;
 897                         }
 898                       } // insane
 899                     }
 900                     break;
 901                   }
 902                   prev_i = i;
 903                 }
 904                 if (insane) {
 905                   // Note: regular analysis could probably continue by resetting "insane" flag.
 906                   out->print_cr("Possible loop in TopSizeBlocks list detected. Analysis aborted.");
 907                   discard_TopSizeArray(out);
 908                 }
 909               }
 910             }
 911           }
 912           //----------------------------------------------
 913           //---<  END register block in TopSizeArray  >---
 914           //----------------------------------------------
 915         } else {
 916           nBlocks_zomb++;
 917         }
 918 
 919         if (ix_beg == ix_end) {
 920           StatArray[ix_beg].type = cbType;
 921           switch (cbType) {
 922             case nMethod_inuse:
 923               highest_compilation_id = (highest_compilation_id >= compile_id) ? highest_compilation_id : compile_id;
 924               if (comp_lvl < CompLevel_full_optimization) {
 925                 nBlocks_t1++;
 926                 t1Space   += hb_bytelen;
 927                 StatArray[ix_beg].t1_count++;
 928                 StatArray[ix_beg].t1_space += (unsigned short)hb_len;
 929                 StatArray[ix_beg].t1_age    = StatArray[ix_beg].t1_age < compile_id ? compile_id : StatArray[ix_beg].t1_age;
 930               } else {
 931                 nBlocks_t2++;
 932                 t2Space   += hb_bytelen;
 933                 StatArray[ix_beg].t2_count++;
 934                 StatArray[ix_beg].t2_space += (unsigned short)hb_len;
 935                 StatArray[ix_beg].t2_age    = StatArray[ix_beg].t2_age < compile_id ? compile_id : StatArray[ix_beg].t2_age;
 936               }
 937               StatArray[ix_beg].level     = comp_lvl;
 938               StatArray[ix_beg].compiler  = cType;
 939               break;
 940             case nMethod_inconstruction: // let's count "in construction" nmethods here.
 941             case nMethod_alive:
 942               StatArray[ix_beg].tx_count++;
 943               StatArray[ix_beg].tx_space += (unsigned short)hb_len;
 944               StatArray[ix_beg].tx_age    = StatArray[ix_beg].tx_age < compile_id ? compile_id : StatArray[ix_beg].tx_age;
 945               StatArray[ix_beg].level     = comp_lvl;
 946               StatArray[ix_beg].compiler  = cType;
 947               break;
 948             case nMethod_dead:
 949             case nMethod_unloaded:
 950               StatArray[ix_beg].dead_count++;
 951               StatArray[ix_beg].dead_space += (unsigned short)hb_len;
 952               break;
 953             default:
 954               // must be a stub, if it's not a dead or alive nMethod
 955               nBlocks_stub++;
 956               stubSpace   += hb_bytelen;
 957               StatArray[ix_beg].stub_count++;
 958               StatArray[ix_beg].stub_space += (unsigned short)hb_len;
 959               break;
 960           }
 961         } else {
 962           unsigned int beg_space = (unsigned int)(granule_size - ((char*)h - low_bound - ix_beg*granule_size));
 963           unsigned int end_space = (unsigned int)(hb_bytelen - beg_space - (ix_end-ix_beg-1)*granule_size);
 964           beg_space = beg_space>>log2_seg_size;  // store in units of _segment_size
 965           end_space = end_space>>log2_seg_size;  // store in units of _segment_size
 966           StatArray[ix_beg].type = cbType;
 967           StatArray[ix_end].type = cbType;
 968           switch (cbType) {
 969             case nMethod_inuse:
 970               highest_compilation_id = (highest_compilation_id >= compile_id) ? highest_compilation_id : compile_id;
 971               if (comp_lvl < CompLevel_full_optimization) {
 972                 nBlocks_t1++;
 973                 t1Space   += hb_bytelen;
 974                 StatArray[ix_beg].t1_count++;
 975                 StatArray[ix_beg].t1_space += (unsigned short)beg_space;
 976                 StatArray[ix_beg].t1_age    = StatArray[ix_beg].t1_age < compile_id ? compile_id : StatArray[ix_beg].t1_age;
 977 
 978                 StatArray[ix_end].t1_count++;
 979                 StatArray[ix_end].t1_space += (unsigned short)end_space;
 980                 StatArray[ix_end].t1_age    = StatArray[ix_end].t1_age < compile_id ? compile_id : StatArray[ix_end].t1_age;
 981               } else {
 982                 nBlocks_t2++;
 983                 t2Space   += hb_bytelen;
 984                 StatArray[ix_beg].t2_count++;
 985                 StatArray[ix_beg].t2_space += (unsigned short)beg_space;
 986                 StatArray[ix_beg].t2_age    = StatArray[ix_beg].t2_age < compile_id ? compile_id : StatArray[ix_beg].t2_age;
 987 
 988                 StatArray[ix_end].t2_count++;
 989                 StatArray[ix_end].t2_space += (unsigned short)end_space;
 990                 StatArray[ix_end].t2_age    = StatArray[ix_end].t2_age < compile_id ? compile_id : StatArray[ix_end].t2_age;
 991               }
 992               StatArray[ix_beg].level     = comp_lvl;
 993               StatArray[ix_beg].compiler  = cType;
 994               StatArray[ix_end].level     = comp_lvl;
 995               StatArray[ix_end].compiler  = cType;
 996               break;
 997             case nMethod_inconstruction: // let's count "in construction" nmethods here.
 998             case nMethod_alive:
 999               StatArray[ix_beg].tx_count++;
1000               StatArray[ix_beg].tx_space += (unsigned short)beg_space;
1001               StatArray[ix_beg].tx_age    = StatArray[ix_beg].tx_age < compile_id ? compile_id : StatArray[ix_beg].tx_age;
1002 
1003               StatArray[ix_end].tx_count++;
1004               StatArray[ix_end].tx_space += (unsigned short)end_space;
1005               StatArray[ix_end].tx_age    = StatArray[ix_end].tx_age < compile_id ? compile_id : StatArray[ix_end].tx_age;
1006 
1007               StatArray[ix_beg].level     = comp_lvl;
1008               StatArray[ix_beg].compiler  = cType;
1009               StatArray[ix_end].level     = comp_lvl;
1010               StatArray[ix_end].compiler  = cType;
1011               break;
1012             case nMethod_dead:
1013             case nMethod_unloaded:
1014               StatArray[ix_beg].dead_count++;
1015               StatArray[ix_beg].dead_space += (unsigned short)beg_space;
1016               StatArray[ix_end].dead_count++;
1017               StatArray[ix_end].dead_space += (unsigned short)end_space;
1018               break;
1019             default:
1020               // must be a stub, if it's not a dead or alive nMethod
1021               nBlocks_stub++;
1022               stubSpace   += hb_bytelen;
1023               StatArray[ix_beg].stub_count++;
1024               StatArray[ix_beg].stub_space += (unsigned short)beg_space;
1025               StatArray[ix_end].stub_count++;
1026               StatArray[ix_end].stub_space += (unsigned short)end_space;
1027               break;
1028           }
1029           for (unsigned int ix = ix_beg+1; ix < ix_end; ix++) {
1030             StatArray[ix].type = cbType;
1031             switch (cbType) {
1032               case nMethod_inuse:
1033                 if (comp_lvl < CompLevel_full_optimization) {
1034                   StatArray[ix].t1_count++;
1035                   StatArray[ix].t1_space += (unsigned short)(granule_size>>log2_seg_size);
1036                   StatArray[ix].t1_age    = StatArray[ix].t1_age < compile_id ? compile_id : StatArray[ix].t1_age;
1037                 } else {
1038                   StatArray[ix].t2_count++;
1039                   StatArray[ix].t2_space += (unsigned short)(granule_size>>log2_seg_size);
1040                   StatArray[ix].t2_age    = StatArray[ix].t2_age < compile_id ? compile_id : StatArray[ix].t2_age;
1041                 }
1042                 StatArray[ix].level     = comp_lvl;
1043                 StatArray[ix].compiler  = cType;
1044                 break;
1045               case nMethod_inconstruction: // let's count "in construction" nmethods here.
1046               case nMethod_alive:
1047                 StatArray[ix].tx_count++;
1048                 StatArray[ix].tx_space += (unsigned short)(granule_size>>log2_seg_size);
1049                 StatArray[ix].tx_age    = StatArray[ix].tx_age < compile_id ? compile_id : StatArray[ix].tx_age;
1050                 StatArray[ix].level     = comp_lvl;
1051                 StatArray[ix].compiler  = cType;
1052                 break;
1053               case nMethod_dead:
1054               case nMethod_unloaded:
1055                 StatArray[ix].dead_count++;
1056                 StatArray[ix].dead_space += (unsigned short)(granule_size>>log2_seg_size);
1057                 break;
1058               default:
1059                 // must be a stub, if it's not a dead or alive nMethod
1060                 StatArray[ix].stub_count++;
1061                 StatArray[ix].stub_space += (unsigned short)(granule_size>>log2_seg_size);
1062                 break;
1063             }
1064           }
1065         }
1066       }
1067     }
1068     done = true;
1069 
1070     if (!insane) {
1071       // There is a risk for this block (because it contains many print statements) to get
1072       // interspersed with print data from other threads. We take this risk intentionally.
1073       // Getting stalled waiting for tty_lock while holding the CodeCache_lock is not desirable.
1074       printBox(ast, '-', "Global CodeHeap statistics for segment ", heapName);
1075       ast->print_cr("freeSpace        = " SIZE_FORMAT_W(8) "k, nBlocks_free     = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", freeSpace/(size_t)K,     nBlocks_free,     (100.0*freeSpace)/size,     (100.0*freeSpace)/res_size);
1076       ast->print_cr("usedSpace        = " SIZE_FORMAT_W(8) "k, nBlocks_used     = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", usedSpace/(size_t)K,     nBlocks_used,     (100.0*usedSpace)/size,     (100.0*usedSpace)/res_size);
1077       ast->print_cr("  Tier1 Space    = " SIZE_FORMAT_W(8) "k, nBlocks_t1       = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", t1Space/(size_t)K,       nBlocks_t1,       (100.0*t1Space)/size,       (100.0*t1Space)/res_size);
1078       ast->print_cr("  Tier2 Space    = " SIZE_FORMAT_W(8) "k, nBlocks_t2       = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", t2Space/(size_t)K,       nBlocks_t2,       (100.0*t2Space)/size,       (100.0*t2Space)/res_size);
1079       ast->print_cr("  Alive Space    = " SIZE_FORMAT_W(8) "k, nBlocks_alive    = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", aliveSpace/(size_t)K,    nBlocks_alive,    (100.0*aliveSpace)/size,    (100.0*aliveSpace)/res_size);
1080       ast->print_cr("    disconnected = " SIZE_FORMAT_W(8) "k, nBlocks_disconn  = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", disconnSpace/(size_t)K,  nBlocks_disconn,  (100.0*disconnSpace)/size,  (100.0*disconnSpace)/res_size);
1081       ast->print_cr("    not entrant  = " SIZE_FORMAT_W(8) "k, nBlocks_notentr  = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", notentrSpace/(size_t)K,  nBlocks_notentr,  (100.0*notentrSpace)/size,  (100.0*notentrSpace)/res_size);
1082       ast->print_cr("  inconstrSpace  = " SIZE_FORMAT_W(8) "k, nBlocks_inconstr = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", inconstrSpace/(size_t)K, nBlocks_inconstr, (100.0*inconstrSpace)/size, (100.0*inconstrSpace)/res_size);
1083       ast->print_cr("  unloadedSpace  = " SIZE_FORMAT_W(8) "k, nBlocks_unloaded = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", unloadedSpace/(size_t)K, nBlocks_unloaded, (100.0*unloadedSpace)/size, (100.0*unloadedSpace)/res_size);
1084       ast->print_cr("  deadSpace      = " SIZE_FORMAT_W(8) "k, nBlocks_dead     = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", deadSpace/(size_t)K,     nBlocks_dead,     (100.0*deadSpace)/size,     (100.0*deadSpace)/res_size);
1085       ast->print_cr("  stubSpace      = " SIZE_FORMAT_W(8) "k, nBlocks_stub     = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", stubSpace/(size_t)K,     nBlocks_stub,     (100.0*stubSpace)/size,     (100.0*stubSpace)/res_size);
1086       ast->print_cr("ZombieBlocks     = %8d. These are HeapBlocks which could not be identified as CodeBlobs.", nBlocks_zomb);
1087       ast->cr();
1088       ast->print_cr("Segment start          = " INTPTR_FORMAT ", used space      = " SIZE_FORMAT_W(8)"k", p2i(low_bound), size/K);
1089       ast->print_cr("Segment end (used)     = " INTPTR_FORMAT ", remaining space = " SIZE_FORMAT_W(8)"k", p2i(low_bound) + size, (res_size - size)/K);
1090       ast->print_cr("Segment end (reserved) = " INTPTR_FORMAT ", reserved space  = " SIZE_FORMAT_W(8)"k", p2i(low_bound) + res_size, res_size/K);
1091       ast->cr();
1092       ast->print_cr("latest allocated compilation id = %d", latest_compilation_id);
1093       ast->print_cr("highest observed compilation id = %d", highest_compilation_id);
1094       ast->print_cr("Building TopSizeList iterations = %ld", total_iterations);
1095       ast->cr();
1096 
1097       int             reset_val = NMethodSweeper::hotness_counter_reset_val();
1098       double reverse_free_ratio = (res_size > size) ? (double)res_size/(double)(res_size-size) : (double)res_size;
1099       printBox(ast, '-', "Method hotness information at time of this analysis", NULL);
1100       ast->print_cr("Highest possible method temperature:          %12d", reset_val);
1101       ast->print_cr("Threshold for method to be considered 'cold': %12.3f", -reset_val + reverse_free_ratio * NmethodSweepActivity);
1102       if (n_methods > 0) {
1103         avgTemp = hotnessAccumulator/n_methods;
1104         ast->print_cr("min. hotness = %6d", minTemp);
1105         ast->print_cr("avg. hotness = %6d", avgTemp);
1106         ast->print_cr("max. hotness = %6d", maxTemp);
1107       } else {
1108         avgTemp = 0;
1109         ast->print_cr("No hotness data available");
1110       }
1111       BUFFEREDSTREAM_FLUSH("\n")
1112 
1113       // This loop is intentionally printing directly to "out".
1114       // It should not print anything, anyway.
1115       out->print("Verifying collected data...");
1116       size_t granule_segs = granule_size>>log2_seg_size;
1117       for (unsigned int ix = 0; ix < granules; ix++) {
1118         if (StatArray[ix].t1_count   > granule_segs) {
1119           out->print_cr("t1_count[%d]   = %d", ix, StatArray[ix].t1_count);
1120         }
1121         if (StatArray[ix].t2_count   > granule_segs) {
1122           out->print_cr("t2_count[%d]   = %d", ix, StatArray[ix].t2_count);
1123         }
1124         if (StatArray[ix].tx_count   > granule_segs) {
1125           out->print_cr("tx_count[%d]   = %d", ix, StatArray[ix].tx_count);
1126         }
1127         if (StatArray[ix].stub_count > granule_segs) {
1128           out->print_cr("stub_count[%d] = %d", ix, StatArray[ix].stub_count);
1129         }
1130         if (StatArray[ix].dead_count > granule_segs) {
1131           out->print_cr("dead_count[%d] = %d", ix, StatArray[ix].dead_count);
1132         }
1133         if (StatArray[ix].t1_space   > granule_segs) {
1134           out->print_cr("t1_space[%d]   = %d", ix, StatArray[ix].t1_space);
1135         }
1136         if (StatArray[ix].t2_space   > granule_segs) {
1137           out->print_cr("t2_space[%d]   = %d", ix, StatArray[ix].t2_space);
1138         }
1139         if (StatArray[ix].tx_space   > granule_segs) {
1140           out->print_cr("tx_space[%d]   = %d", ix, StatArray[ix].tx_space);
1141         }
1142         if (StatArray[ix].stub_space > granule_segs) {
1143           out->print_cr("stub_space[%d] = %d", ix, StatArray[ix].stub_space);
1144         }
1145         if (StatArray[ix].dead_space > granule_segs) {
1146           out->print_cr("dead_space[%d] = %d", ix, StatArray[ix].dead_space);
1147         }
1148         //   this cast is awful! I need it because NT/Intel reports a signed/unsigned mismatch.
1149         if ((size_t)(StatArray[ix].t1_count+StatArray[ix].t2_count+StatArray[ix].tx_count+StatArray[ix].stub_count+StatArray[ix].dead_count) > granule_segs) {
1150           out->print_cr("t1_count[%d] = %d, t2_count[%d] = %d, tx_count[%d] = %d, stub_count[%d] = %d", ix, StatArray[ix].t1_count, ix, StatArray[ix].t2_count, ix, StatArray[ix].tx_count, ix, StatArray[ix].stub_count);
1151         }
1152         if ((size_t)(StatArray[ix].t1_space+StatArray[ix].t2_space+StatArray[ix].tx_space+StatArray[ix].stub_space+StatArray[ix].dead_space) > granule_segs) {
1153           out->print_cr("t1_space[%d] = %d, t2_space[%d] = %d, tx_space[%d] = %d, stub_space[%d] = %d", ix, StatArray[ix].t1_space, ix, StatArray[ix].t2_space, ix, StatArray[ix].tx_space, ix, StatArray[ix].stub_space);
1154         }
1155       }
1156 
1157       // This loop is intentionally printing directly to "out".
1158       // It should not print anything, anyway.
1159       if (used_topSizeBlocks > 0) {
1160         unsigned int j = 0;
1161         if (TopSizeArray[0].len != currMax) {
1162           out->print_cr("currMax(%d) differs from TopSizeArray[0].len(%d)", currMax, TopSizeArray[0].len);
1163         }
1164         for (unsigned int i = 0; (TopSizeArray[i].index != tsbStopper) && (j++ < alloc_topSizeBlocks); i = TopSizeArray[i].index) {
1165           if (TopSizeArray[i].len < TopSizeArray[TopSizeArray[i].index].len) {
1166             out->print_cr("sort error at index %d: %d !>= %d", i, TopSizeArray[i].len, TopSizeArray[TopSizeArray[i].index].len);
1167           }
1168         }
1169         if (j >= alloc_topSizeBlocks) {
1170           out->print_cr("Possible loop in TopSizeArray chaining!\n  allocBlocks = %d, usedBlocks = %d", alloc_topSizeBlocks, used_topSizeBlocks);
1171           for (unsigned int i = 0; i < alloc_topSizeBlocks; i++) {
1172             out->print_cr("  TopSizeArray[%d].index = %d, len = %d", i, TopSizeArray[i].index, TopSizeArray[i].len);
1173           }
1174         }
1175       }
1176       out->print_cr("...done\n\n");
1177     } else {
1178       // insane heap state detected. Analysis data incomplete. Just throw it away.
1179       discard_StatArray(out);
1180       discard_TopSizeArray(out);
1181     }
1182   }
1183 
1184 
1185   done        = false;
1186   while (!done && (nBlocks_free > 0)) {
1187 
1188     printBox(ast, '=', "C O D E   H E A P   A N A L Y S I S   (free blocks) for segment ", heapName);
1189     ast->print_cr("   The aggregate step collects information about all free blocks in CodeHeap.\n"
1190                   "   Subsequent print functions create their output based on this snapshot.\n");
1191     ast->print_cr("   Free space in %s is distributed over %d free blocks.", heapName, nBlocks_free);
1192     ast->print_cr("   Each free block takes " SIZE_FORMAT " bytes of C heap for statistics data, that is " SIZE_FORMAT "K in total.", sizeof(FreeBlk), (sizeof(FreeBlk)*nBlocks_free)/K);
1193     BUFFEREDSTREAM_FLUSH("\n")
1194 
1195     //----------------------------------------
1196     //--  Prepare the FreeArray of FreeBlks --
1197     //----------------------------------------
1198 
1199     //---< discard old array if size does not match  >---
1200     if (nBlocks_free != alloc_freeBlocks) {
1201       discard_FreeArray(out);
1202     }
1203 
1204     prepare_FreeArray(out, nBlocks_free, heapName);
1205     if (FreeArray == NULL) {
1206       done = true;
1207       continue;
1208     }
1209 
1210     //----------------------------------------
1211     //--  Collect all FreeBlks in FreeArray --
1212     //----------------------------------------
1213 
1214     unsigned int ix = 0;
1215     FreeBlock* cur  = heap->freelist();
1216 
1217     while (cur != NULL) {
1218       if (ix < alloc_freeBlocks) { // don't index out of bounds if _freelist has more blocks than anticipated
1219         FreeArray[ix].start = cur;
1220         FreeArray[ix].len   = (unsigned int)(cur->length()<<log2_seg_size);
1221         FreeArray[ix].index = ix;
1222       }
1223       cur  = cur->link();
1224       ix++;
1225     }
1226     if (ix != alloc_freeBlocks) {
1227       ast->print_cr("Free block count mismatch. Expected %d free blocks, but found %d.", alloc_freeBlocks, ix);
1228       ast->print_cr("I will update the counter and retry data collection");
1229       BUFFEREDSTREAM_FLUSH("\n")
1230       nBlocks_free = ix;
1231       continue;
1232     }
1233     done = true;
1234   }
1235 
1236   if (!done || (nBlocks_free == 0)) {
1237     if (nBlocks_free == 0) {
1238       printBox(ast, '-', "no free blocks found in ", heapName);
1239     } else if (!done) {
1240       ast->print_cr("Free block count mismatch could not be resolved.");
1241       ast->print_cr("Try to run \"aggregate\" function to update counters");
1242     }
1243     BUFFEREDSTREAM_FLUSH("")
1244 
1245     //---< discard old array and update global values  >---
1246     discard_FreeArray(out);
1247     set_HeapStatGlobals(out, heapName);
1248     return;
1249   }
1250 
1251   //---<  calculate and fill remaining fields  >---
1252   if (FreeArray != NULL) {
1253     // This loop is intentionally printing directly to "out".
1254     // It should not print anything, anyway.
1255     for (unsigned int ix = 0; ix < alloc_freeBlocks-1; ix++) {
1256       size_t lenSum = 0;
1257       FreeArray[ix].gap = (unsigned int)((address)FreeArray[ix+1].start - ((address)FreeArray[ix].start + FreeArray[ix].len));
1258       for (HeapBlock *h = heap->next_block(FreeArray[ix].start); (h != NULL) && (h != FreeArray[ix+1].start); h = heap->next_block(h)) {
1259         CodeBlob *cb  = (CodeBlob*)(heap->find_start(h));
1260         if ((cb != NULL) && !cb->is_nmethod()) {
1261           FreeArray[ix].stubs_in_gap = true;
1262         }
1263         FreeArray[ix].n_gapBlocks++;
1264         lenSum += h->length()<<log2_seg_size;
1265         if (((address)h < ((address)FreeArray[ix].start+FreeArray[ix].len)) || (h >= FreeArray[ix+1].start)) {
1266           out->print_cr("unsorted occupied CodeHeap block found @ %p, gap interval [%p, %p)", h, (address)FreeArray[ix].start+FreeArray[ix].len, FreeArray[ix+1].start);
1267         }
1268       }
1269       if (lenSum != FreeArray[ix].gap) {
1270         out->print_cr("Length mismatch for gap between FreeBlk[%d] and FreeBlk[%d]. Calculated: %d, accumulated: %d.", ix, ix+1, FreeArray[ix].gap, (unsigned int)lenSum);
1271       }
1272     }
1273   }
1274   set_HeapStatGlobals(out, heapName);
1275 
1276   printBox(ast, '=', "C O D E   H E A P   A N A L Y S I S   C O M P L E T E   for segment ", heapName);
1277   BUFFEREDSTREAM_FLUSH("\n")
1278 }
1279 
1280 
1281 void CodeHeapState::print_usedSpace(outputStream* out, CodeHeap* heap) {
1282   if (!initialization_complete) {
1283     return;
1284   }
1285 
1286   const char* heapName   = get_heapName(heap);
1287   get_HeapStatGlobals(out, heapName);
1288 
1289   if ((StatArray == NULL) || (TopSizeArray == NULL) || (used_topSizeBlocks == 0)) {
1290     return;
1291   }
1292   BUFFEREDSTREAM_DECL(ast, out)
1293 
1294   {
1295     printBox(ast, '=', "U S E D   S P A C E   S T A T I S T I C S   for ", heapName);
1296     ast->print_cr("Note: The Top%d list of the largest used blocks associates method names\n"
1297                   "      and other identifying information with the block size data.\n"
1298                   "\n"
1299                   "      Method names are dynamically retrieved from the code cache at print time.\n"
1300                   "      Due to the living nature of the code cache and because the CodeCache_lock\n"
1301                   "      is not continuously held, the displayed name might be wrong or no name\n"
1302                   "      might be found at all. The likelihood for that to happen increases\n"
1303                   "      over time passed between analysis and print step.\n", used_topSizeBlocks);
1304     BUFFEREDSTREAM_FLUSH_LOCKED("\n")
1305   }
1306 
1307   //----------------------------
1308   //--  Print Top Used Blocks --
1309   //----------------------------
1310   {
1311     char*     low_bound = heap->low_boundary();
1312     bool      have_CodeCache_lock = CodeCache_lock->owned_by_self();
1313 
1314     printBox(ast, '-', "Largest Used Blocks in ", heapName);
1315     print_blobType_legend(ast);
1316 
1317     ast->fill_to(51);
1318     ast->print("%4s", "blob");
1319     ast->fill_to(56);
1320     ast->print("%9s", "compiler");
1321     ast->fill_to(66);
1322     ast->print_cr("%6s", "method");
1323     ast->print_cr("%18s %13s %17s %4s %9s  %5s %s",      "Addr(module)      ", "offset", "size", "type", " type lvl", " temp", "Name");
1324     BUFFEREDSTREAM_FLUSH_LOCKED("")
1325 
1326     //---<  print Top Ten Used Blocks  >---
1327     if (used_topSizeBlocks > 0) {
1328       unsigned int printed_topSizeBlocks = 0;
1329       for (unsigned int i = 0; i != tsbStopper; i = TopSizeArray[i].index) {
1330         printed_topSizeBlocks++;
1331         nmethod*           nm = NULL;
1332         const char* blob_name = "unnamed blob or blob name unavailable";
1333         // heap->find_start() is safe. Only works on _segmap.
1334         // Returns NULL or void*. Returned CodeBlob may be uninitialized.
1335         HeapBlock* heapBlock = TopSizeArray[i].start;
1336         CodeBlob*  this_blob = (CodeBlob*)(heap->find_start(heapBlock));
1337         bool    blob_is_safe = blob_access_is_safe(this_blob, NULL);
1338         if (blob_is_safe) {
1339           //---<  access these fields only if we own the CodeCache_lock  >---
1340           if (have_CodeCache_lock) {
1341             blob_name = this_blob->name();
1342             nm        = this_blob->as_nmethod_or_null();
1343           }
1344           //---<  blob address  >---
1345           ast->print(INTPTR_FORMAT, p2i(this_blob));
1346           ast->fill_to(19);
1347           //---<  blob offset from CodeHeap begin  >---
1348           ast->print("(+" PTR32_FORMAT ")", (unsigned int)((char*)this_blob-low_bound));
1349           ast->fill_to(33);
1350         } else {
1351           //---<  block address  >---
1352           ast->print(INTPTR_FORMAT, p2i(TopSizeArray[i].start));
1353           ast->fill_to(19);
1354           //---<  block offset from CodeHeap begin  >---
1355           ast->print("(+" PTR32_FORMAT ")", (unsigned int)((char*)TopSizeArray[i].start-low_bound));
1356           ast->fill_to(33);
1357         }
1358 
1359         //---<  print size, name, and signature (for nMethods)  >---
1360         // access nmethod and Method fields only if we own the CodeCache_lock.
1361         // This fact is implicitly transported via nm != NULL.
1362         if (CompiledMethod::nmethod_access_is_safe(nm)) {
1363           ResourceMark rm;
1364           Method* method = nm->method();
1365           if (nm->is_in_use()) {
1366             blob_name = method->name_and_sig_as_C_string();
1367           }
1368           if (nm->is_not_entrant()) {
1369             blob_name = method->name_and_sig_as_C_string();
1370           }
1371           //---<  nMethod size in hex  >---
1372           unsigned int total_size = nm->total_size();
1373           ast->print(PTR32_FORMAT, total_size);
1374           ast->print("(" SIZE_FORMAT_W(4) "K)", total_size/K);
1375           ast->fill_to(51);
1376           ast->print("  %c", blobTypeChar[TopSizeArray[i].type]);
1377           //---<  compiler information  >---
1378           ast->fill_to(56);
1379           ast->print("%5s %3d", compTypeName[TopSizeArray[i].compiler], TopSizeArray[i].level);
1380           //---<  method temperature  >---
1381           ast->fill_to(67);
1382           ast->print("%5d", nm->hotness_counter());
1383           //---<  name and signature  >---
1384           ast->fill_to(67+6);
1385           if (nm->is_not_installed()) {
1386             ast->print(" not (yet) installed method ");
1387           }
1388           if (nm->is_zombie()) {
1389             ast->print(" zombie method ");
1390           }
1391           ast->print("%s", blob_name);
1392         } else {
1393           //---<  block size in hex  >---
1394           ast->print(PTR32_FORMAT, (unsigned int)(TopSizeArray[i].len<<log2_seg_size));
1395           ast->print("(" SIZE_FORMAT_W(4) "K)", (TopSizeArray[i].len<<log2_seg_size)/K);
1396           //---<  no compiler information  >---
1397           ast->fill_to(56);
1398           //---<  name and signature  >---
1399           ast->fill_to(67+6);
1400           ast->print("%s", blob_name);
1401         }
1402         ast->cr();
1403         BUFFEREDSTREAM_FLUSH_IF("", 512)
1404       }
1405       if (used_topSizeBlocks != printed_topSizeBlocks) {
1406         ast->print_cr("used blocks: %d, printed blocks: %d", used_topSizeBlocks, printed_topSizeBlocks);
1407         for (unsigned int i = 0; i < alloc_topSizeBlocks; i++) {
1408           ast->print_cr("  TopSizeArray[%d].index = %d, len = %d", i, TopSizeArray[i].index, TopSizeArray[i].len);
1409           BUFFEREDSTREAM_FLUSH_IF("", 512)
1410         }
1411       }
1412       BUFFEREDSTREAM_FLUSH("\n\n")
1413     }
1414   }
1415 
1416   //-----------------------------
1417   //--  Print Usage Histogram  --
1418   //-----------------------------
1419 
1420   if (SizeDistributionArray != NULL) {
1421     unsigned long total_count = 0;
1422     unsigned long total_size  = 0;
1423     const unsigned long pctFactor = 200;
1424 
1425     for (unsigned int i = 0; i < nSizeDistElements; i++) {
1426       total_count += SizeDistributionArray[i].count;
1427       total_size  += SizeDistributionArray[i].lenSum;
1428     }
1429 
1430     if ((total_count > 0) && (total_size > 0)) {
1431       printBox(ast, '-', "Block count histogram for ", heapName);
1432       ast->print_cr("Note: The histogram indicates how many blocks (as a percentage\n"
1433                     "      of all blocks) have a size in the given range.\n"
1434                     "      %ld characters are printed per percentage point.\n", pctFactor/100);
1435       ast->print_cr("total size   of all blocks: %7ldM", (total_size<<log2_seg_size)/M);
1436       ast->print_cr("total number of all blocks: %7ld\n", total_count);
1437       BUFFEREDSTREAM_FLUSH_LOCKED("")
1438 
1439       ast->print_cr("[Size Range)------avg.-size-+----count-+");
1440       for (unsigned int i = 0; i < nSizeDistElements; i++) {
1441         if (SizeDistributionArray[i].rangeStart<<log2_seg_size < K) {
1442           ast->print("[" SIZE_FORMAT_W(5) " .." SIZE_FORMAT_W(5) " ): "
1443                     ,(size_t)(SizeDistributionArray[i].rangeStart<<log2_seg_size)
1444                     ,(size_t)(SizeDistributionArray[i].rangeEnd<<log2_seg_size)
1445                     );
1446         } else if (SizeDistributionArray[i].rangeStart<<log2_seg_size < M) {
1447           ast->print("[" SIZE_FORMAT_W(5) "K.." SIZE_FORMAT_W(5) "K): "
1448                     ,(SizeDistributionArray[i].rangeStart<<log2_seg_size)/K
1449                     ,(SizeDistributionArray[i].rangeEnd<<log2_seg_size)/K
1450                     );
1451         } else {
1452           ast->print("[" SIZE_FORMAT_W(5) "M.." SIZE_FORMAT_W(5) "M): "
1453                     ,(SizeDistributionArray[i].rangeStart<<log2_seg_size)/M
1454                     ,(SizeDistributionArray[i].rangeEnd<<log2_seg_size)/M
1455                     );
1456         }
1457         ast->print(" %8d | %8d |",
1458                    SizeDistributionArray[i].count > 0 ? (SizeDistributionArray[i].lenSum<<log2_seg_size)/SizeDistributionArray[i].count : 0,
1459                    SizeDistributionArray[i].count);
1460 
1461         unsigned int percent = pctFactor*SizeDistributionArray[i].count/total_count;
1462         for (unsigned int j = 1; j <= percent; j++) {
1463           ast->print("%c", (j%((pctFactor/100)*10) == 0) ? ('0'+j/(((unsigned int)pctFactor/100)*10)) : '*');
1464         }
1465         ast->cr();
1466         BUFFEREDSTREAM_FLUSH_IF("", 512)
1467       }
1468       ast->print_cr("----------------------------+----------+");
1469       BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
1470 
1471       printBox(ast, '-', "Contribution per size range to total size for ", heapName);
1472       ast->print_cr("Note: The histogram indicates how much space (as a percentage of all\n"
1473                     "      occupied space) is used by the blocks in the given size range.\n"
1474                     "      %ld characters are printed per percentage point.\n", pctFactor/100);
1475       ast->print_cr("total size   of all blocks: %7ldM", (total_size<<log2_seg_size)/M);
1476       ast->print_cr("total number of all blocks: %7ld\n", total_count);
1477       BUFFEREDSTREAM_FLUSH_LOCKED("")
1478 
1479       ast->print_cr("[Size Range)------avg.-size-+----count-+");
1480       for (unsigned int i = 0; i < nSizeDistElements; i++) {
1481         if (SizeDistributionArray[i].rangeStart<<log2_seg_size < K) {
1482           ast->print("[" SIZE_FORMAT_W(5) " .." SIZE_FORMAT_W(5) " ): "
1483                     ,(size_t)(SizeDistributionArray[i].rangeStart<<log2_seg_size)
1484                     ,(size_t)(SizeDistributionArray[i].rangeEnd<<log2_seg_size)
1485                     );
1486         } else if (SizeDistributionArray[i].rangeStart<<log2_seg_size < M) {
1487           ast->print("[" SIZE_FORMAT_W(5) "K.." SIZE_FORMAT_W(5) "K): "
1488                     ,(SizeDistributionArray[i].rangeStart<<log2_seg_size)/K
1489                     ,(SizeDistributionArray[i].rangeEnd<<log2_seg_size)/K
1490                     );
1491         } else {
1492           ast->print("[" SIZE_FORMAT_W(5) "M.." SIZE_FORMAT_W(5) "M): "
1493                     ,(SizeDistributionArray[i].rangeStart<<log2_seg_size)/M
1494                     ,(SizeDistributionArray[i].rangeEnd<<log2_seg_size)/M
1495                     );
1496         }
1497         ast->print(" %8d | %8d |",
1498                    SizeDistributionArray[i].count > 0 ? (SizeDistributionArray[i].lenSum<<log2_seg_size)/SizeDistributionArray[i].count : 0,
1499                    SizeDistributionArray[i].count);
1500 
1501         unsigned int percent = pctFactor*(unsigned long)SizeDistributionArray[i].lenSum/total_size;
1502         for (unsigned int j = 1; j <= percent; j++) {
1503           ast->print("%c", (j%((pctFactor/100)*10) == 0) ? ('0'+j/(((unsigned int)pctFactor/100)*10)) : '*');
1504         }
1505         ast->cr();
1506         BUFFEREDSTREAM_FLUSH_IF("", 512)
1507       }
1508       ast->print_cr("----------------------------+----------+");
1509       BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
1510     }
1511   }
1512 }
1513 
1514 
1515 void CodeHeapState::print_freeSpace(outputStream* out, CodeHeap* heap) {
1516   if (!initialization_complete) {
1517     return;
1518   }
1519 
1520   const char* heapName   = get_heapName(heap);
1521   get_HeapStatGlobals(out, heapName);
1522 
1523   if ((StatArray == NULL) || (FreeArray == NULL) || (alloc_granules == 0)) {
1524     return;
1525   }
1526   BUFFEREDSTREAM_DECL(ast, out)
1527 
1528   {
1529     printBox(ast, '=', "F R E E   S P A C E   S T A T I S T I C S   for ", heapName);
1530     ast->print_cr("Note: in this context, a gap is the occupied space between two free blocks.\n"
1531                   "      Those gaps are of interest if there is a chance that they become\n"
1532                   "      unoccupied, e.g. by class unloading. Then, the two adjacent free\n"
1533                   "      blocks, together with the now unoccupied space, form a new, large\n"
1534                   "      free block.");
1535     BUFFEREDSTREAM_FLUSH_LOCKED("\n")
1536   }
1537 
1538   {
1539     printBox(ast, '-', "List of all Free Blocks in ", heapName);
1540 
1541     unsigned int ix = 0;
1542     for (ix = 0; ix < alloc_freeBlocks-1; ix++) {
1543       ast->print(INTPTR_FORMAT ": Len[%4d] = " HEX32_FORMAT ",", p2i(FreeArray[ix].start), ix, FreeArray[ix].len);
1544       ast->fill_to(38);
1545       ast->print("Gap[%4d..%4d]: " HEX32_FORMAT " bytes,", ix, ix+1, FreeArray[ix].gap);
1546       ast->fill_to(71);
1547       ast->print("block count: %6d", FreeArray[ix].n_gapBlocks);
1548       if (FreeArray[ix].stubs_in_gap) {
1549         ast->print(" !! permanent gap, contains stubs and/or blobs !!");
1550       }
1551       ast->cr();
1552       BUFFEREDSTREAM_FLUSH_IF("", 512)
1553     }
1554     ast->print_cr(INTPTR_FORMAT ": Len[%4d] = " HEX32_FORMAT, p2i(FreeArray[ix].start), ix, FreeArray[ix].len);
1555     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n")
1556   }
1557 
1558 
1559   //-----------------------------------------
1560   //--  Find and Print Top Ten Free Blocks --
1561   //-----------------------------------------
1562 
1563   //---<  find Top Ten Free Blocks  >---
1564   const unsigned int nTop = 10;
1565   unsigned int  currMax10 = 0;
1566   struct FreeBlk* FreeTopTen[nTop];
1567   memset(FreeTopTen, 0, sizeof(FreeTopTen));
1568 
1569   for (unsigned int ix = 0; ix < alloc_freeBlocks; ix++) {
1570     if (FreeArray[ix].len > currMax10) {  // larger than the ten largest found so far
1571       unsigned int currSize = FreeArray[ix].len;
1572 
1573       unsigned int iy;
1574       for (iy = 0; iy < nTop && FreeTopTen[iy] != NULL; iy++) {
1575         if (FreeTopTen[iy]->len < currSize) {
1576           for (unsigned int iz = nTop-1; iz > iy; iz--) { // make room to insert new free block
1577             FreeTopTen[iz] = FreeTopTen[iz-1];
1578           }
1579           FreeTopTen[iy] = &FreeArray[ix];        // insert new free block
1580           if (FreeTopTen[nTop-1] != NULL) {
1581             currMax10 = FreeTopTen[nTop-1]->len;
1582           }
1583           break; // done with this, check next free block
1584         }
1585       }
1586       if (iy >= nTop) {
1587         ast->print_cr("Internal logic error. New Max10 = %d detected, but could not be merged. Old Max10 = %d",
1588                       currSize, currMax10);
1589         continue;
1590       }
1591       if (FreeTopTen[iy] == NULL) {
1592         FreeTopTen[iy] = &FreeArray[ix];
1593         if (iy == (nTop-1)) {
1594           currMax10 = currSize;
1595         }
1596       }
1597     }
1598   }
1599   BUFFEREDSTREAM_FLUSH_IF("", 512)
1600 
1601   {
1602     printBox(ast, '-', "Top Ten Free Blocks in ", heapName);
1603 
1604     //---<  print Top Ten Free Blocks  >---
1605     for (unsigned int iy = 0; (iy < nTop) && (FreeTopTen[iy] != NULL); iy++) {
1606       ast->print("Pos %3d: Block %4d - size " HEX32_FORMAT ",", iy+1, FreeTopTen[iy]->index, FreeTopTen[iy]->len);
1607       ast->fill_to(39);
1608       if (FreeTopTen[iy]->index == (alloc_freeBlocks-1)) {
1609         ast->print("last free block in list.");
1610       } else {
1611         ast->print("Gap (to next) " HEX32_FORMAT ",", FreeTopTen[iy]->gap);
1612         ast->fill_to(63);
1613         ast->print("#blocks (in gap) %d", FreeTopTen[iy]->n_gapBlocks);
1614       }
1615       ast->cr();
1616       BUFFEREDSTREAM_FLUSH_IF("", 512)
1617     }
1618   }
1619   BUFFEREDSTREAM_FLUSH_LOCKED("\n\n")
1620 
1621 
1622   //--------------------------------------------------------
1623   //--  Find and Print Top Ten Free-Occupied-Free Triples --
1624   //--------------------------------------------------------
1625 
1626   //---<  find and print Top Ten Triples (Free-Occupied-Free)  >---
1627   currMax10 = 0;
1628   struct FreeBlk  *FreeTopTenTriple[nTop];
1629   memset(FreeTopTenTriple, 0, sizeof(FreeTopTenTriple));
1630 
1631   for (unsigned int ix = 0; ix < alloc_freeBlocks-1; ix++) {
1632     // If there are stubs in the gap, this gap will never become completely free.
1633     // The triple will thus never merge to one free block.
1634     unsigned int lenTriple  = FreeArray[ix].len + (FreeArray[ix].stubs_in_gap ? 0 : FreeArray[ix].gap + FreeArray[ix+1].len);
1635     FreeArray[ix].len = lenTriple;
1636     if (lenTriple > currMax10) {  // larger than the ten largest found so far
1637 
1638       unsigned int iy;
1639       for (iy = 0; (iy < nTop) && (FreeTopTenTriple[iy] != NULL); iy++) {
1640         if (FreeTopTenTriple[iy]->len < lenTriple) {
1641           for (unsigned int iz = nTop-1; iz > iy; iz--) {
1642             FreeTopTenTriple[iz] = FreeTopTenTriple[iz-1];
1643           }
1644           FreeTopTenTriple[iy] = &FreeArray[ix];
1645           if (FreeTopTenTriple[nTop-1] != NULL) {
1646             currMax10 = FreeTopTenTriple[nTop-1]->len;
1647           }
1648           break;
1649         }
1650       }
1651       if (iy == nTop) {
1652         ast->print_cr("Internal logic error. New Max10 = %d detected, but could not be merged. Old Max10 = %d",
1653                       lenTriple, currMax10);
1654         continue;
1655       }
1656       if (FreeTopTenTriple[iy] == NULL) {
1657         FreeTopTenTriple[iy] = &FreeArray[ix];
1658         if (iy == (nTop-1)) {
1659           currMax10 = lenTriple;
1660         }
1661       }
1662     }
1663   }
1664   BUFFEREDSTREAM_FLUSH_IF("", 512)
1665 
1666   {
1667     printBox(ast, '-', "Top Ten Free-Occupied-Free Triples in ", heapName);
1668     ast->print_cr("  Use this information to judge how likely it is that a large(r) free block\n"
1669                   "  might get created by code cache sweeping.\n"
1670                   "  If all the occupied blocks can be swept, the three free blocks will be\n"
1671                   "  merged into one (much larger) free block. That would reduce free space\n"
1672                   "  fragmentation.\n");
1673 
1674     //---<  print Top Ten Free-Occupied-Free Triples  >---
1675     for (unsigned int iy = 0; (iy < nTop) && (FreeTopTenTriple[iy] != NULL); iy++) {
1676       ast->print("Pos %3d: Block %4d - size " HEX32_FORMAT ",", iy+1, FreeTopTenTriple[iy]->index, FreeTopTenTriple[iy]->len);
1677       ast->fill_to(39);
1678       ast->print("Gap (to next) " HEX32_FORMAT ",", FreeTopTenTriple[iy]->gap);
1679       ast->fill_to(63);
1680       ast->print("#blocks (in gap) %d", FreeTopTenTriple[iy]->n_gapBlocks);
1681       ast->cr();
1682       BUFFEREDSTREAM_FLUSH_IF("", 512)
1683     }
1684   }
1685   BUFFEREDSTREAM_FLUSH_LOCKED("\n\n")
1686 }
1687 
1688 
1689 void CodeHeapState::print_count(outputStream* out, CodeHeap* heap) {
1690   if (!initialization_complete) {
1691     return;
1692   }
1693 
1694   const char* heapName   = get_heapName(heap);
1695   get_HeapStatGlobals(out, heapName);
1696 
1697   if ((StatArray == NULL) || (alloc_granules == 0)) {
1698     return;
1699   }
1700   BUFFEREDSTREAM_DECL(ast, out)
1701 
1702   unsigned int granules_per_line = 32;
1703   char*        low_bound         = heap->low_boundary();
1704 
1705   {
1706     printBox(ast, '=', "B L O C K   C O U N T S   for ", heapName);
1707     ast->print_cr("  Each granule contains an individual number of heap blocks. Large blocks\n"
1708                   "  may span multiple granules and are counted for each granule they touch.\n");
1709     if (segment_granules) {
1710       ast->print_cr("  You have selected granule size to be as small as segment size.\n"
1711                     "  As a result, each granule contains exactly one block (or a part of one block)\n"
1712                     "  or is displayed as empty (' ') if it's BlobType does not match the selection.\n"
1713                     "  Occupied granules show their BlobType character, see legend.\n");
1714       print_blobType_legend(ast);
1715     }
1716     BUFFEREDSTREAM_FLUSH_LOCKED("")
1717   }
1718 
1719   {
1720     if (segment_granules) {
1721       printBox(ast, '-', "Total (all types) count for granule size == segment size", NULL);
1722 
1723       granules_per_line = 128;
1724       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1725         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1726         print_blobType_single(ast, StatArray[ix].type);
1727       }
1728     } else {
1729       printBox(ast, '-', "Total (all tiers) count, 0x1..0xf. '*' indicates >= 16 blocks, ' ' indicates empty", NULL);
1730 
1731       granules_per_line = 128;
1732       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1733         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1734         unsigned int count = StatArray[ix].t1_count   + StatArray[ix].t2_count   + StatArray[ix].tx_count
1735                            + StatArray[ix].stub_count + StatArray[ix].dead_count;
1736         print_count_single(ast, count);
1737       }
1738     }
1739     BUFFEREDSTREAM_FLUSH_LOCKED("|\n\n\n")
1740   }
1741 
1742   {
1743     if (nBlocks_t1 > 0) {
1744       printBox(ast, '-', "Tier1 nMethod count only, 0x1..0xf. '*' indicates >= 16 blocks, ' ' indicates empty", NULL);
1745 
1746       granules_per_line = 128;
1747       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1748         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1749         if (segment_granules && StatArray[ix].t1_count > 0) {
1750           print_blobType_single(ast, StatArray[ix].type);
1751         } else {
1752           print_count_single(ast, StatArray[ix].t1_count);
1753         }
1754       }
1755       ast->print("|");
1756     } else {
1757       ast->print("No Tier1 nMethods found in CodeHeap.");
1758     }
1759     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
1760   }
1761 
1762   {
1763     if (nBlocks_t2 > 0) {
1764       printBox(ast, '-', "Tier2 nMethod count only, 0x1..0xf. '*' indicates >= 16 blocks, ' ' indicates empty", NULL);
1765 
1766       granules_per_line = 128;
1767       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1768         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1769         if (segment_granules && StatArray[ix].t2_count > 0) {
1770           print_blobType_single(ast, StatArray[ix].type);
1771         } else {
1772           print_count_single(ast, StatArray[ix].t2_count);
1773         }
1774       }
1775       ast->print("|");
1776     } else {
1777       ast->print("No Tier2 nMethods found in CodeHeap.");
1778     }
1779     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
1780   }
1781 
1782   {
1783     if (nBlocks_alive > 0) {
1784       printBox(ast, '-', "not_used/not_entrant/not_installed nMethod count only, 0x1..0xf. '*' indicates >= 16 blocks, ' ' indicates empty", NULL);
1785 
1786       granules_per_line = 128;
1787       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1788         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1789         if (segment_granules && StatArray[ix].tx_count > 0) {
1790           print_blobType_single(ast, StatArray[ix].type);
1791         } else {
1792           print_count_single(ast, StatArray[ix].tx_count);
1793         }
1794       }
1795       ast->print("|");
1796     } else {
1797       ast->print("No not_used/not_entrant nMethods found in CodeHeap.");
1798     }
1799     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
1800   }
1801 
1802   {
1803     if (nBlocks_stub > 0) {
1804       printBox(ast, '-', "Stub & Blob count only, 0x1..0xf. '*' indicates >= 16 blocks, ' ' indicates empty", NULL);
1805 
1806       granules_per_line = 128;
1807       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1808         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1809         if (segment_granules && StatArray[ix].stub_count > 0) {
1810           print_blobType_single(ast, StatArray[ix].type);
1811         } else {
1812           print_count_single(ast, StatArray[ix].stub_count);
1813         }
1814       }
1815       ast->print("|");
1816     } else {
1817       ast->print("No Stubs and Blobs found in CodeHeap.");
1818     }
1819     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
1820   }
1821 
1822   {
1823     if (nBlocks_dead > 0) {
1824       printBox(ast, '-', "Dead nMethod count only, 0x1..0xf. '*' indicates >= 16 blocks, ' ' indicates empty", NULL);
1825 
1826       granules_per_line = 128;
1827       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1828         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1829         if (segment_granules && StatArray[ix].dead_count > 0) {
1830           print_blobType_single(ast, StatArray[ix].type);
1831         } else {
1832           print_count_single(ast, StatArray[ix].dead_count);
1833         }
1834       }
1835       ast->print("|");
1836     } else {
1837       ast->print("No dead nMethods found in CodeHeap.");
1838     }
1839     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
1840   }
1841 
1842   {
1843     if (!segment_granules) { // Prevent totally redundant printouts
1844       printBox(ast, '-', "Count by tier (combined, no dead blocks): <#t1>:<#t2>:<#s>, 0x0..0xf. '*' indicates >= 16 blocks", NULL);
1845 
1846       granules_per_line = 24;
1847       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1848         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1849 
1850         print_count_single(ast, StatArray[ix].t1_count);
1851         ast->print(":");
1852         print_count_single(ast, StatArray[ix].t2_count);
1853         ast->print(":");
1854         if (segment_granules && StatArray[ix].stub_count > 0) {
1855           print_blobType_single(ast, StatArray[ix].type);
1856         } else {
1857           print_count_single(ast, StatArray[ix].stub_count);
1858         }
1859         ast->print(" ");
1860       }
1861       BUFFEREDSTREAM_FLUSH_LOCKED("|\n\n\n")
1862     }
1863   }
1864 }
1865 
1866 
1867 void CodeHeapState::print_space(outputStream* out, CodeHeap* heap) {
1868   if (!initialization_complete) {
1869     return;
1870   }
1871 
1872   const char* heapName   = get_heapName(heap);
1873   get_HeapStatGlobals(out, heapName);
1874 
1875   if ((StatArray == NULL) || (alloc_granules == 0)) {
1876     return;
1877   }
1878   BUFFEREDSTREAM_DECL(ast, out)
1879 
1880   unsigned int granules_per_line = 32;
1881   char*        low_bound         = heap->low_boundary();
1882 
1883   {
1884     printBox(ast, '=', "S P A C E   U S A G E  &  F R A G M E N T A T I O N   for ", heapName);
1885     ast->print_cr("  The heap space covered by one granule is occupied to a various extend.\n"
1886                   "  The granule occupancy is displayed by one decimal digit per granule.\n");
1887     if (segment_granules) {
1888       ast->print_cr("  You have selected granule size to be as small as segment size.\n"
1889                     "  As a result, each granule contains exactly one block (or a part of one block)\n"
1890                     "  or is displayed as empty (' ') if it's BlobType does not match the selection.\n"
1891                     "  Occupied granules show their BlobType character, see legend.\n");
1892       print_blobType_legend(ast);
1893     } else {
1894       ast->print_cr("  These digits represent a fill percentage range (see legend).\n");
1895       print_space_legend(ast);
1896     }
1897     BUFFEREDSTREAM_FLUSH_LOCKED("")
1898   }
1899 
1900   {
1901     if (segment_granules) {
1902       printBox(ast, '-', "Total (all types) space consumption for granule size == segment size", NULL);
1903 
1904       granules_per_line = 128;
1905       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1906         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1907         print_blobType_single(ast, StatArray[ix].type);
1908       }
1909     } else {
1910       printBox(ast, '-', "Total (all types) space consumption. ' ' indicates empty, '*' indicates full.", NULL);
1911 
1912       granules_per_line = 128;
1913       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1914         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1915         unsigned int space    = StatArray[ix].t1_space   + StatArray[ix].t2_space  + StatArray[ix].tx_space
1916                               + StatArray[ix].stub_space + StatArray[ix].dead_space;
1917         print_space_single(ast, space);
1918       }
1919     }
1920     BUFFEREDSTREAM_FLUSH_LOCKED("|\n\n\n")
1921   }
1922 
1923   {
1924     if (nBlocks_t1 > 0) {
1925       printBox(ast, '-', "Tier1 space consumption. ' ' indicates empty, '*' indicates full", NULL);
1926 
1927       granules_per_line = 128;
1928       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1929         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1930         if (segment_granules && StatArray[ix].t1_space > 0) {
1931           print_blobType_single(ast, StatArray[ix].type);
1932         } else {
1933           print_space_single(ast, StatArray[ix].t1_space);
1934         }
1935       }
1936       ast->print("|");
1937     } else {
1938       ast->print("No Tier1 nMethods found in CodeHeap.");
1939     }
1940     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
1941   }
1942 
1943   {
1944     if (nBlocks_t2 > 0) {
1945       printBox(ast, '-', "Tier2 space consumption. ' ' indicates empty, '*' indicates full", NULL);
1946 
1947       granules_per_line = 128;
1948       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1949         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1950         if (segment_granules && StatArray[ix].t2_space > 0) {
1951           print_blobType_single(ast, StatArray[ix].type);
1952         } else {
1953           print_space_single(ast, StatArray[ix].t2_space);
1954         }
1955       }
1956       ast->print("|");
1957     } else {
1958       ast->print("No Tier2 nMethods found in CodeHeap.");
1959     }
1960     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
1961   }
1962 
1963   {
1964     if (nBlocks_alive > 0) {
1965       printBox(ast, '-', "not_used/not_entrant/not_installed space consumption. ' ' indicates empty, '*' indicates full", NULL);
1966 
1967       granules_per_line = 128;
1968       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1969         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1970         if (segment_granules && StatArray[ix].tx_space > 0) {
1971           print_blobType_single(ast, StatArray[ix].type);
1972         } else {
1973           print_space_single(ast, StatArray[ix].tx_space);
1974         }
1975       }
1976       ast->print("|");
1977     } else {
1978       ast->print("No Tier2 nMethods found in CodeHeap.");
1979     }
1980     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
1981   }
1982 
1983   {
1984     if (nBlocks_stub > 0) {
1985       printBox(ast, '-', "Stub and Blob space consumption. ' ' indicates empty, '*' indicates full", NULL);
1986 
1987       granules_per_line = 128;
1988       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1989         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1990         if (segment_granules && StatArray[ix].stub_space > 0) {
1991           print_blobType_single(ast, StatArray[ix].type);
1992         } else {
1993           print_space_single(ast, StatArray[ix].stub_space);
1994         }
1995       }
1996       ast->print("|");
1997     } else {
1998       ast->print("No Stubs and Blobs found in CodeHeap.");
1999     }
2000     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
2001   }
2002 
2003   {
2004     if (nBlocks_dead > 0) {
2005       printBox(ast, '-', "Dead space consumption. ' ' indicates empty, '*' indicates full", NULL);
2006 
2007       granules_per_line = 128;
2008       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2009         print_line_delim(out, ast, low_bound, ix, granules_per_line);
2010         print_space_single(ast, StatArray[ix].dead_space);
2011       }
2012       ast->print("|");
2013     } else {
2014       ast->print("No dead nMethods found in CodeHeap.");
2015     }
2016     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
2017   }
2018 
2019   {
2020     if (!segment_granules) { // Prevent totally redundant printouts
2021       printBox(ast, '-', "Space consumption by tier (combined): <t1%>:<t2%>:<s%>. ' ' indicates empty, '*' indicates full", NULL);
2022 
2023       granules_per_line = 24;
2024       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2025         print_line_delim(out, ast, low_bound, ix, granules_per_line);
2026 
2027         if (segment_granules && StatArray[ix].t1_space > 0) {
2028           print_blobType_single(ast, StatArray[ix].type);
2029         } else {
2030           print_space_single(ast, StatArray[ix].t1_space);
2031         }
2032         ast->print(":");
2033         if (segment_granules && StatArray[ix].t2_space > 0) {
2034           print_blobType_single(ast, StatArray[ix].type);
2035         } else {
2036           print_space_single(ast, StatArray[ix].t2_space);
2037         }
2038         ast->print(":");
2039         if (segment_granules && StatArray[ix].stub_space > 0) {
2040           print_blobType_single(ast, StatArray[ix].type);
2041         } else {
2042           print_space_single(ast, StatArray[ix].stub_space);
2043         }
2044         ast->print(" ");
2045       }
2046       ast->print("|");
2047       BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
2048     }
2049   }
2050 }
2051 
2052 void CodeHeapState::print_age(outputStream* out, CodeHeap* heap) {
2053   if (!initialization_complete) {
2054     return;
2055   }
2056 
2057   const char* heapName   = get_heapName(heap);
2058   get_HeapStatGlobals(out, heapName);
2059 
2060   if ((StatArray == NULL) || (alloc_granules == 0)) {
2061     return;
2062   }
2063   BUFFEREDSTREAM_DECL(ast, out)
2064 
2065   unsigned int granules_per_line = 32;
2066   char*        low_bound         = heap->low_boundary();
2067 
2068   {
2069     printBox(ast, '=', "M E T H O D   A G E   by CompileID for ", heapName);
2070     ast->print_cr("  The age of a compiled method in the CodeHeap is not available as a\n"
2071                   "  time stamp. Instead, a relative age is deducted from the method's compilation ID.\n"
2072                   "  Age information is available for tier1 and tier2 methods only. There is no\n"
2073                   "  age information for stubs and blobs, because they have no compilation ID assigned.\n"
2074                   "  Information for the youngest method (highest ID) in the granule is printed.\n"
2075                   "  Refer to the legend to learn how method age is mapped to the displayed digit.");
2076     print_age_legend(ast);
2077     BUFFEREDSTREAM_FLUSH_LOCKED("")
2078   }
2079 
2080   {
2081     printBox(ast, '-', "Age distribution. '0' indicates youngest 1/256, '8': oldest half, ' ': no age information", NULL);
2082 
2083     granules_per_line = 128;
2084     for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2085       print_line_delim(out, ast, low_bound, ix, granules_per_line);
2086       unsigned int age1      = StatArray[ix].t1_age;
2087       unsigned int age2      = StatArray[ix].t2_age;
2088       unsigned int agex      = StatArray[ix].tx_age;
2089       unsigned int age       = age1 > age2 ? age1 : age2;
2090       age       = age > agex ? age : agex;
2091       print_age_single(ast, age);
2092     }
2093     ast->print("|");
2094     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
2095   }
2096 
2097   {
2098     if (nBlocks_t1 > 0) {
2099       printBox(ast, '-', "Tier1 age distribution. '0' indicates youngest 1/256, '8': oldest half, ' ': no age information", NULL);
2100 
2101       granules_per_line = 128;
2102       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2103         print_line_delim(out, ast, low_bound, ix, granules_per_line);
2104         print_age_single(ast, StatArray[ix].t1_age);
2105       }
2106       ast->print("|");
2107     } else {
2108       ast->print("No Tier1 nMethods found in CodeHeap.");
2109     }
2110     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
2111   }
2112 
2113   {
2114     if (nBlocks_t2 > 0) {
2115       printBox(ast, '-', "Tier2 age distribution. '0' indicates youngest 1/256, '8': oldest half, ' ': no age information", NULL);
2116 
2117       granules_per_line = 128;
2118       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2119         print_line_delim(out, ast, low_bound, ix, granules_per_line);
2120         print_age_single(ast, StatArray[ix].t2_age);
2121       }
2122       ast->print("|");
2123     } else {
2124       ast->print("No Tier2 nMethods found in CodeHeap.");
2125     }
2126     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
2127   }
2128 
2129   {
2130     if (nBlocks_alive > 0) {
2131       printBox(ast, '-', "not_used/not_entrant/not_installed age distribution. '0' indicates youngest 1/256, '8': oldest half, ' ': no age information", NULL);
2132 
2133       granules_per_line = 128;
2134       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2135         print_line_delim(out, ast, low_bound, ix, granules_per_line);
2136         print_age_single(ast, StatArray[ix].tx_age);
2137       }
2138       ast->print("|");
2139     } else {
2140       ast->print("No Tier2 nMethods found in CodeHeap.");
2141     }
2142     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
2143   }
2144 
2145   {
2146     if (!segment_granules) { // Prevent totally redundant printouts
2147       printBox(ast, '-', "age distribution by tier <a1>:<a2>. '0' indicates youngest 1/256, '8': oldest half, ' ': no age information", NULL);
2148 
2149       granules_per_line = 32;
2150       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2151         print_line_delim(out, ast, low_bound, ix, granules_per_line);
2152         print_age_single(ast, StatArray[ix].t1_age);
2153         ast->print(":");
2154         print_age_single(ast, StatArray[ix].t2_age);
2155         ast->print(" ");
2156       }
2157       ast->print("|");
2158       BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
2159     }
2160   }
2161 }
2162 
2163 
2164 void CodeHeapState::print_names(outputStream* out, CodeHeap* heap) {
2165   if (!initialization_complete) {
2166     return;
2167   }
2168 
2169   const char* heapName   = get_heapName(heap);
2170   get_HeapStatGlobals(out, heapName);
2171 
2172   if ((StatArray == NULL) || (alloc_granules == 0)) {
2173     return;
2174   }
2175   BUFFEREDSTREAM_DECL(ast, out)
2176 
2177   unsigned int granules_per_line   = 128;
2178   char*        low_bound           = heap->low_boundary();
2179   CodeBlob*    last_blob           = NULL;
2180   bool         name_in_addr_range  = true;
2181   bool         have_CodeCache_lock = CodeCache_lock->owned_by_self();
2182 
2183   //---<  print at least 128K per block (i.e. between headers)  >---
2184   if (granules_per_line*granule_size < 128*K) {
2185     granules_per_line = (unsigned int)((128*K)/granule_size);
2186   }
2187 
2188   printBox(ast, '=', "M E T H O D   N A M E S   for ", heapName);
2189   ast->print_cr("  Method names are dynamically retrieved from the code cache at print time.\n"
2190                 "  Due to the living nature of the code heap and because the CodeCache_lock\n"
2191                 "  is not continuously held, the displayed name might be wrong or no name\n"
2192                 "  might be found at all. The likelihood for that to happen increases\n"
2193                 "  over time passed between aggregtion and print steps.\n");
2194   BUFFEREDSTREAM_FLUSH_LOCKED("")
2195 
2196   for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2197     //---<  print a new blob on a new line  >---
2198     if (ix%granules_per_line == 0) {
2199       if (!name_in_addr_range) {
2200         ast->print_cr("No methods, blobs, or stubs found in this address range");
2201       }
2202       name_in_addr_range = false;
2203 
2204       size_t end_ix = (ix+granules_per_line <= alloc_granules) ? ix+granules_per_line : alloc_granules;
2205       ast->cr();
2206       ast->print_cr("--------------------------------------------------------------------");
2207       ast->print_cr("Address range [" INTPTR_FORMAT "," INTPTR_FORMAT "), " SIZE_FORMAT "k", p2i(low_bound+ix*granule_size), p2i(low_bound + end_ix*granule_size), (end_ix - ix)*granule_size/(size_t)K);
2208       ast->print_cr("--------------------------------------------------------------------");
2209       BUFFEREDSTREAM_FLUSH_IF("", 512)
2210     }
2211     // Only check granule if it contains at least one blob.
2212     unsigned int nBlobs  = StatArray[ix].t1_count   + StatArray[ix].t2_count + StatArray[ix].tx_count +
2213                            StatArray[ix].stub_count + StatArray[ix].dead_count;
2214     if (nBlobs > 0 ) {
2215     for (unsigned int is = 0; is < granule_size; is+=(unsigned int)seg_size) {
2216       // heap->find_start() is safe. Only works on _segmap.
2217       // Returns NULL or void*. Returned CodeBlob may be uninitialized.
2218       char*     this_seg  = low_bound + ix*granule_size + is;
2219       CodeBlob* this_blob = (CodeBlob*)(heap->find_start(this_seg));
2220       bool   blob_is_safe = blob_access_is_safe(this_blob, NULL);
2221       // blob could have been flushed, freed, and merged.
2222       // this_blob < last_blob is an indicator for that.
2223       if (blob_is_safe && (this_blob > last_blob)) {
2224         last_blob          = this_blob;
2225 
2226         //---<  get type and name  >---
2227         blobType       cbType = noType;
2228         if (segment_granules) {
2229           cbType = (blobType)StatArray[ix].type;
2230         } else {
2231           //---<  access these fields only if we own the CodeCache_lock  >---
2232           if (have_CodeCache_lock) {
2233             cbType = get_cbType(this_blob);
2234           }
2235         }
2236 
2237         //---<  access these fields only if we own the CodeCache_lock  >---
2238         const char* blob_name = "<unavailable>";
2239         nmethod*           nm = NULL;
2240         if (have_CodeCache_lock) {
2241           blob_name = this_blob->name();
2242           nm        = this_blob->as_nmethod_or_null();
2243           // this_blob->name() could return NULL if no name was given to CTOR. Inlined, maybe invisible on stack
2244           if ((blob_name == NULL) || !os::is_readable_pointer(blob_name)) {
2245             blob_name = "<unavailable>";
2246           }
2247         }
2248 
2249         //---<  print table header for new print range  >---
2250         if (!name_in_addr_range) {
2251           name_in_addr_range = true;
2252           ast->fill_to(51);
2253           ast->print("%9s", "compiler");
2254           ast->fill_to(61);
2255           ast->print_cr("%6s", "method");
2256           ast->print_cr("%18s %13s %17s %9s  %5s %18s  %s", "Addr(module)      ", "offset", "size", " type lvl", " temp", "blobType          ", "Name");
2257           BUFFEREDSTREAM_FLUSH_IF("", 512)
2258         }
2259 
2260         //---<  print line prefix (address and offset from CodeHeap start)  >---
2261         ast->print(INTPTR_FORMAT, p2i(this_blob));
2262         ast->fill_to(19);
2263         ast->print("(+" PTR32_FORMAT ")", (unsigned int)((char*)this_blob-low_bound));
2264         ast->fill_to(33);
2265 
2266         // access nmethod and Method fields only if we own the CodeCache_lock.
2267         // This fact is implicitly transported via nm != NULL.
2268         if (CompiledMethod::nmethod_access_is_safe(nm)) {
2269           Method* method = nm->method();
2270           ResourceMark rm;
2271           //---<  collect all data to locals as quickly as possible  >---
2272           unsigned int total_size = nm->total_size();
2273           int          hotness    = nm->hotness_counter();
2274           bool         get_name   = (cbType == nMethod_inuse) || (cbType == nMethod_notused);
2275           //---<  nMethod size in hex  >---
2276           ast->print(PTR32_FORMAT, total_size);
2277           ast->print("(" SIZE_FORMAT_W(4) "K)", total_size/K);
2278           //---<  compiler information  >---
2279           ast->fill_to(51);
2280           ast->print("%5s %3d", compTypeName[StatArray[ix].compiler], StatArray[ix].level);
2281           //---<  method temperature  >---
2282           ast->fill_to(62);
2283           ast->print("%5d", hotness);
2284           //---<  name and signature  >---
2285           ast->fill_to(62+6);
2286           ast->print("%s", blobTypeName[cbType]);
2287           ast->fill_to(82+6);
2288           if (cbType == nMethod_dead) {
2289             ast->print("%14s", " zombie method");
2290           }
2291 
2292           if (get_name) {
2293             Symbol* methName  = method->name();
2294             const char*   methNameS = (methName == NULL) ? NULL : methName->as_C_string();
2295             methNameS = (methNameS == NULL) ? "<method name unavailable>" : methNameS;
2296             Symbol* methSig   = method->signature();
2297             const char*   methSigS  = (methSig  == NULL) ? NULL : methSig->as_C_string();
2298             methSigS  = (methSigS  == NULL) ? "<method signature unavailable>" : methSigS;
2299             ast->print("%s", methNameS);
2300             ast->print("%s", methSigS);
2301           } else {
2302             ast->print("%s", blob_name);
2303           }
2304         } else if (blob_is_safe) {
2305           ast->fill_to(62+6);
2306           ast->print("%s", blobTypeName[cbType]);
2307           ast->fill_to(82+6);
2308           ast->print("%s", blob_name);
2309         } else {
2310           ast->fill_to(62+6);
2311           ast->print("<stale blob>");
2312         }
2313         ast->cr();
2314         BUFFEREDSTREAM_FLUSH_IF("", 512)
2315       } else if (!blob_is_safe && (this_blob != last_blob) && (this_blob != NULL)) {
2316         last_blob          = this_blob;
2317       }
2318     }
2319     } // nBlobs > 0
2320   }
2321   BUFFEREDSTREAM_FLUSH_LOCKED("\n\n")
2322 }
2323 
2324 
2325 void CodeHeapState::printBox(outputStream* ast, const char border, const char* text1, const char* text2) {
2326   unsigned int lineLen = 1 + 2 + 2 + 1;
2327   char edge, frame;
2328 
2329   if (text1 != NULL) {
2330     lineLen += (unsigned int)strlen(text1); // text1 is much shorter than MAX_INT chars.
2331   }
2332   if (text2 != NULL) {
2333     lineLen += (unsigned int)strlen(text2); // text2 is much shorter than MAX_INT chars.
2334   }
2335   if (border == '-') {
2336     edge  = '+';
2337     frame = '|';
2338   } else {
2339     edge  = border;
2340     frame = border;
2341   }
2342 
2343   ast->print("%c", edge);
2344   for (unsigned int i = 0; i < lineLen-2; i++) {
2345     ast->print("%c", border);
2346   }
2347   ast->print_cr("%c", edge);
2348 
2349   ast->print("%c  ", frame);
2350   if (text1 != NULL) {
2351     ast->print("%s", text1);
2352   }
2353   if (text2 != NULL) {
2354     ast->print("%s", text2);
2355   }
2356   ast->print_cr("  %c", frame);
2357 
2358   ast->print("%c", edge);
2359   for (unsigned int i = 0; i < lineLen-2; i++) {
2360     ast->print("%c", border);
2361   }
2362   ast->print_cr("%c", edge);
2363 }
2364 
2365 void CodeHeapState::print_blobType_legend(outputStream* out) {
2366   out->cr();
2367   printBox(out, '-', "Block types used in the following CodeHeap dump", NULL);
2368   for (int type = noType; type < lastType; type += 1) {
2369     out->print_cr("  %c - %s", blobTypeChar[type], blobTypeName[type]);
2370   }
2371   out->print_cr("  -----------------------------------------------------");
2372   out->cr();
2373 }
2374 
2375 void CodeHeapState::print_space_legend(outputStream* out) {
2376   unsigned int indicator = 0;
2377   unsigned int age_range = 256;
2378   unsigned int range_beg = latest_compilation_id;
2379   out->cr();
2380   printBox(out, '-', "Space ranges, based on granule occupancy", NULL);
2381   out->print_cr("    -   0%% == occupancy");
2382   for (int i=0; i<=9; i++) {
2383     out->print_cr("  %d - %3d%% < occupancy < %3d%%", i, 10*i, 10*(i+1));
2384   }
2385   out->print_cr("  * - 100%% == occupancy");
2386   out->print_cr("  ----------------------------------------------");
2387   out->cr();
2388 }
2389 
2390 void CodeHeapState::print_age_legend(outputStream* out) {
2391   unsigned int indicator = 0;
2392   unsigned int age_range = 256;
2393   unsigned int range_beg = latest_compilation_id;
2394   out->cr();
2395   printBox(out, '-', "Age ranges, based on compilation id", NULL);
2396   while (age_range > 0) {
2397     out->print_cr("  %d - %6d to %6d", indicator, range_beg, latest_compilation_id - latest_compilation_id/age_range);
2398     range_beg = latest_compilation_id - latest_compilation_id/age_range;
2399     age_range /= 2;
2400     indicator += 1;
2401   }
2402   out->print_cr("  -----------------------------------------");
2403   out->cr();
2404 }
2405 
2406 void CodeHeapState::print_blobType_single(outputStream* out, u2 /* blobType */ type) {
2407   out->print("%c", blobTypeChar[type]);
2408 }
2409 
2410 void CodeHeapState::print_count_single(outputStream* out, unsigned short count) {
2411   if (count >= 16)    out->print("*");
2412   else if (count > 0) out->print("%1.1x", count);
2413   else                out->print(" ");
2414 }
2415 
2416 void CodeHeapState::print_space_single(outputStream* out, unsigned short space) {
2417   size_t  space_in_bytes = ((unsigned int)space)<<log2_seg_size;
2418   char    fraction       = (space == 0) ? ' ' : (space_in_bytes >= granule_size-1) ? '*' : char('0'+10*space_in_bytes/granule_size);
2419   out->print("%c", fraction);
2420 }
2421 
2422 void CodeHeapState::print_age_single(outputStream* out, unsigned int age) {
2423   unsigned int indicator = 0;
2424   unsigned int age_range = 256;
2425   if (age > 0) {
2426     while ((age_range > 0) && (latest_compilation_id-age > latest_compilation_id/age_range)) {
2427       age_range /= 2;
2428       indicator += 1;
2429     }
2430     out->print("%c", char('0'+indicator));
2431   } else {
2432     out->print(" ");
2433   }
2434 }
2435 
2436 void CodeHeapState::print_line_delim(outputStream* out, outputStream* ast, char* low_bound, unsigned int ix, unsigned int gpl) {
2437   if (ix % gpl == 0) {
2438     if (ix > 0) {
2439       ast->print("|");
2440     }
2441     ast->cr();
2442     assert(out == ast, "must use the same stream!");
2443 
2444     ast->print(INTPTR_FORMAT, p2i(low_bound + ix*granule_size));
2445     ast->fill_to(19);
2446     ast->print("(+" PTR32_FORMAT "): |", (unsigned int)(ix*granule_size));
2447   }
2448 }
2449 
2450 void CodeHeapState::print_line_delim(outputStream* out, bufferedStream* ast, char* low_bound, unsigned int ix, unsigned int gpl) {
2451   assert(out != ast, "must not use the same stream!");
2452   if (ix % gpl == 0) {
2453     if (ix > 0) {
2454       ast->print("|");
2455     }
2456     ast->cr();
2457 
2458     // can't use BUFFEREDSTREAM_FLUSH_IF("", 512) here.
2459     // can't use this expression. bufferedStream::capacity() does not exist.
2460     // if ((ast->capacity() - ast->size()) < 512) {
2461     // Assume instead that default bufferedStream capacity (4K) was used.
2462     if (ast->size() > 3*K) {
2463       ttyLocker ttyl;
2464       out->print("%s", ast->as_string());
2465       ast->reset();
2466     }
2467 
2468     ast->print(INTPTR_FORMAT, p2i(low_bound + ix*granule_size));
2469     ast->fill_to(19);
2470     ast->print("(+" PTR32_FORMAT "): |", (unsigned int)(ix*granule_size));
2471   }
2472 }
2473 
2474 CodeHeapState::blobType CodeHeapState::get_cbType(CodeBlob* cb) {
2475   if ((cb != NULL) && os::is_readable_pointer(cb)) {
2476     if (cb->is_runtime_stub())                return runtimeStub;
2477     if (cb->is_deoptimization_stub())         return deoptimizationStub;
2478     if (cb->is_uncommon_trap_stub())          return uncommonTrapStub;
2479     if (cb->is_exception_stub())              return exceptionStub;
2480     if (cb->is_safepoint_stub())              return safepointStub;
2481     if (cb->is_adapter_blob())                return adapterBlob;
2482     if (cb->is_method_handles_adapter_blob()) return mh_adapterBlob;
2483     if (cb->is_buffer_blob())                 return bufferBlob;
2484 
2485     //---<  access these fields only if we own the CodeCache_lock  >---
2486     // Should be ensured by caller. aggregate() amd print_names() do that.
2487     if (CodeCache_lock->owned_by_self()) {
2488       nmethod*  nm = cb->as_nmethod_or_null();
2489       if (nm != NULL) { // no is_readable check required, nm = (nmethod*)cb.
2490         if (nm->is_not_installed()) return nMethod_inconstruction;
2491         if (nm->is_zombie())        return nMethod_dead;
2492         if (nm->is_unloaded())      return nMethod_unloaded;
2493         if (nm->is_in_use())        return nMethod_inuse;
2494         if (nm->is_alive() && !(nm->is_not_entrant()))   return nMethod_notused;
2495         if (nm->is_alive())         return nMethod_alive;
2496         return nMethod_dead;
2497       }
2498     }
2499   }
2500   return noType;
2501 }
2502 
2503 bool CodeHeapState::blob_access_is_safe(CodeBlob* this_blob, CodeBlob* prev_blob) {
2504   return (this_blob != NULL) && // a blob must have been found, obviously
2505          ((this_blob == prev_blob) || (prev_blob == NULL)) &&  // when re-checking, the same blob must have been found
2506          (this_blob->header_size() >= 0) &&
2507          (this_blob->relocation_size() >= 0) &&
2508          ((address)this_blob + this_blob->header_size() == (address)(this_blob->relocation_begin())) &&
2509          ((address)this_blob + CodeBlob::align_code_offset(this_blob->header_size() + this_blob->relocation_size()) == (address)(this_blob->content_begin())) &&
2510          os::is_readable_pointer((address)(this_blob->relocation_begin())) &&
2511          os::is_readable_pointer(this_blob->content_begin());
2512 }