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