1 /*
   2  * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "jvm.h"
  27 #include "classfile/symbolTable.hpp"
  28 #include "classfile/systemDictionary.hpp"
  29 #include "classfile/vmSymbols.hpp"
  30 #include "code/codeCache.hpp"
  31 #include "code/codeHeapState.hpp"
  32 #include "code/dependencyContext.hpp"
  33 #include "compiler/compileBroker.hpp"
  34 #include "compiler/compileLog.hpp"
  35 #include "compiler/compilerOracle.hpp"
  36 #include "compiler/directivesParser.hpp"
  37 #include "interpreter/linkResolver.hpp"
  38 #include "logging/log.hpp"
  39 #include "logging/logStream.hpp"
  40 #include "memory/allocation.inline.hpp"
  41 #include "memory/resourceArea.hpp"
  42 #include "oops/methodData.hpp"
  43 #include "oops/method.inline.hpp"
  44 #include "oops/oop.inline.hpp"
  45 #include "prims/nativeLookup.hpp"
  46 #include "prims/whitebox.hpp"
  47 #include "runtime/arguments.hpp"
  48 #include "runtime/atomic.hpp"
  49 #include "runtime/compilationPolicy.hpp"
  50 #include "runtime/init.hpp"
  51 #include "runtime/interfaceSupport.inline.hpp"
  52 #include "runtime/javaCalls.hpp"
  53 #include "runtime/os.hpp"
  54 #include "runtime/safepointVerifiers.hpp"
  55 #include "runtime/sharedRuntime.hpp"
  56 #include "runtime/sweeper.hpp"
  57 #include "runtime/timerTrace.hpp"
  58 #include "runtime/vframe.inline.hpp"
  59 #include "trace/tracing.hpp"
  60 #include "utilities/debug.hpp"
  61 #include "utilities/dtrace.hpp"
  62 #include "utilities/events.hpp"
  63 #include "utilities/formatBuffer.hpp"
  64 #ifdef COMPILER1
  65 #include "c1/c1_Compiler.hpp"
  66 #endif
  67 #if INCLUDE_JVMCI
  68 #include "jvmci/jvmciCompiler.hpp"
  69 #include "jvmci/jvmciRuntime.hpp"
  70 #include "jvmci/jvmciJavaClasses.hpp"
  71 #include "runtime/vframe.hpp"
  72 #endif
  73 #ifdef COMPILER2
  74 #include "opto/c2compiler.hpp"
  75 #endif
  76 
  77 #ifdef DTRACE_ENABLED
  78 
  79 // Only bother with this argument setup if dtrace is available
  80 
  81 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name)             \
  82   {                                                                      \
  83     Symbol* klass_name = (method)->klass_name();                         \
  84     Symbol* name = (method)->name();                                     \
  85     Symbol* signature = (method)->signature();                           \
  86     HOTSPOT_METHOD_COMPILE_BEGIN(                                        \
  87       (char *) comp_name, strlen(comp_name),                             \
  88       (char *) klass_name->bytes(), klass_name->utf8_length(),           \
  89       (char *) name->bytes(), name->utf8_length(),                       \
  90       (char *) signature->bytes(), signature->utf8_length());            \
  91   }
  92 
  93 #define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success)      \
  94   {                                                                      \
  95     Symbol* klass_name = (method)->klass_name();                         \
  96     Symbol* name = (method)->name();                                     \
  97     Symbol* signature = (method)->signature();                           \
  98     HOTSPOT_METHOD_COMPILE_END(                                          \
  99       (char *) comp_name, strlen(comp_name),                             \
 100       (char *) klass_name->bytes(), klass_name->utf8_length(),           \
 101       (char *) name->bytes(), name->utf8_length(),                       \
 102       (char *) signature->bytes(), signature->utf8_length(), (success)); \
 103   }
 104 
 105 #else //  ndef DTRACE_ENABLED
 106 
 107 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name)
 108 #define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success)
 109 
 110 #endif // ndef DTRACE_ENABLED
 111 
 112 bool CompileBroker::_initialized = false;
 113 volatile bool CompileBroker::_should_block = false;
 114 volatile int  CompileBroker::_print_compilation_warning = 0;
 115 volatile jint CompileBroker::_should_compile_new_jobs = run_compilation;
 116 
 117 // The installed compiler(s)
 118 AbstractCompiler* CompileBroker::_compilers[2];
 119 
 120 // These counters are used to assign an unique ID to each compilation.
 121 volatile jint CompileBroker::_compilation_id     = 0;
 122 volatile jint CompileBroker::_osr_compilation_id = 0;
 123 
 124 // Debugging information
 125 int  CompileBroker::_last_compile_type     = no_compile;
 126 int  CompileBroker::_last_compile_level    = CompLevel_none;
 127 char CompileBroker::_last_method_compiled[CompileBroker::name_buffer_length];
 128 
 129 // Performance counters
 130 PerfCounter* CompileBroker::_perf_total_compilation = NULL;
 131 PerfCounter* CompileBroker::_perf_osr_compilation = NULL;
 132 PerfCounter* CompileBroker::_perf_standard_compilation = NULL;
 133 
 134 PerfCounter* CompileBroker::_perf_total_bailout_count = NULL;
 135 PerfCounter* CompileBroker::_perf_total_invalidated_count = NULL;
 136 PerfCounter* CompileBroker::_perf_total_compile_count = NULL;
 137 PerfCounter* CompileBroker::_perf_total_osr_compile_count = NULL;
 138 PerfCounter* CompileBroker::_perf_total_standard_compile_count = NULL;
 139 
 140 PerfCounter* CompileBroker::_perf_sum_osr_bytes_compiled = NULL;
 141 PerfCounter* CompileBroker::_perf_sum_standard_bytes_compiled = NULL;
 142 PerfCounter* CompileBroker::_perf_sum_nmethod_size = NULL;
 143 PerfCounter* CompileBroker::_perf_sum_nmethod_code_size = NULL;
 144 
 145 PerfStringVariable* CompileBroker::_perf_last_method = NULL;
 146 PerfStringVariable* CompileBroker::_perf_last_failed_method = NULL;
 147 PerfStringVariable* CompileBroker::_perf_last_invalidated_method = NULL;
 148 PerfVariable*       CompileBroker::_perf_last_compile_type = NULL;
 149 PerfVariable*       CompileBroker::_perf_last_compile_size = NULL;
 150 PerfVariable*       CompileBroker::_perf_last_failed_type = NULL;
 151 PerfVariable*       CompileBroker::_perf_last_invalidated_type = NULL;
 152 
 153 // Timers and counters for generating statistics
 154 elapsedTimer CompileBroker::_t_total_compilation;
 155 elapsedTimer CompileBroker::_t_osr_compilation;
 156 elapsedTimer CompileBroker::_t_standard_compilation;
 157 elapsedTimer CompileBroker::_t_invalidated_compilation;
 158 elapsedTimer CompileBroker::_t_bailedout_compilation;
 159 
 160 int CompileBroker::_total_bailout_count          = 0;
 161 int CompileBroker::_total_invalidated_count      = 0;
 162 int CompileBroker::_total_compile_count          = 0;
 163 int CompileBroker::_total_osr_compile_count      = 0;
 164 int CompileBroker::_total_standard_compile_count = 0;
 165 
 166 int CompileBroker::_sum_osr_bytes_compiled       = 0;
 167 int CompileBroker::_sum_standard_bytes_compiled  = 0;
 168 int CompileBroker::_sum_nmethod_size             = 0;
 169 int CompileBroker::_sum_nmethod_code_size        = 0;
 170 
 171 long CompileBroker::_peak_compilation_time       = 0;
 172 
 173 CompileQueue* CompileBroker::_c2_compile_queue   = NULL;
 174 CompileQueue* CompileBroker::_c1_compile_queue   = NULL;
 175 
 176 
 177 
 178 class CompilationLog : public StringEventLog {
 179  public:
 180   CompilationLog() : StringEventLog("Compilation events") {
 181   }
 182 
 183   void log_compile(JavaThread* thread, CompileTask* task) {
 184     StringLogMessage lm;
 185     stringStream sstr = lm.stream();
 186     // msg.time_stamp().update_to(tty->time_stamp().ticks());
 187     task->print(&sstr, NULL, true, false);
 188     log(thread, "%s", (const char*)lm);
 189   }
 190 
 191   void log_nmethod(JavaThread* thread, nmethod* nm) {
 192     log(thread, "nmethod %d%s " INTPTR_FORMAT " code [" INTPTR_FORMAT ", " INTPTR_FORMAT "]",
 193         nm->compile_id(), nm->is_osr_method() ? "%" : "",
 194         p2i(nm), p2i(nm->code_begin()), p2i(nm->code_end()));
 195   }
 196 
 197   void log_failure(JavaThread* thread, CompileTask* task, const char* reason, const char* retry_message) {
 198     StringLogMessage lm;
 199     lm.print("%4d   COMPILE SKIPPED: %s", task->compile_id(), reason);
 200     if (retry_message != NULL) {
 201       lm.append(" (%s)", retry_message);
 202     }
 203     lm.print("\n");
 204     log(thread, "%s", (const char*)lm);
 205   }
 206 
 207   void log_metaspace_failure(const char* reason) {
 208     ResourceMark rm;
 209     StringLogMessage lm;
 210     lm.print("%4d   COMPILE PROFILING SKIPPED: %s", -1, reason);
 211     lm.print("\n");
 212     log(JavaThread::current(), "%s", (const char*)lm);
 213   }
 214 };
 215 
 216 static CompilationLog* _compilation_log = NULL;
 217 
 218 bool compileBroker_init() {
 219   if (LogEvents) {
 220     _compilation_log = new CompilationLog();
 221   }
 222 
 223   // init directives stack, adding default directive
 224   DirectivesStack::init();
 225 
 226   if (DirectivesParser::has_file()) {
 227     return DirectivesParser::parse_from_flag();
 228   } else if (CompilerDirectivesPrint) {
 229     // Print default directive even when no other was added
 230     DirectivesStack::print(tty);
 231   }
 232 
 233   return true;
 234 }
 235 
 236 CompileTaskWrapper::CompileTaskWrapper(CompileTask* task) {
 237   CompilerThread* thread = CompilerThread::current();
 238   thread->set_task(task);
 239 #if INCLUDE_JVMCI
 240   if (task->is_blocking() && CompileBroker::compiler(task->comp_level())->is_jvmci()) {
 241     task->set_jvmci_compiler_thread(thread);
 242   }
 243 #endif
 244   CompileLog*     log  = thread->log();
 245   if (log != NULL)  task->log_task_start(log);
 246 }
 247 
 248 CompileTaskWrapper::~CompileTaskWrapper() {
 249   CompilerThread* thread = CompilerThread::current();
 250   CompileTask* task = thread->task();
 251   CompileLog*  log  = thread->log();
 252   if (log != NULL)  task->log_task_done(log);
 253   thread->set_task(NULL);
 254   task->set_code_handle(NULL);
 255   thread->set_env(NULL);
 256   if (task->is_blocking()) {
 257     bool free_task = false;
 258     {
 259       MutexLocker notifier(task->lock(), thread);
 260       task->mark_complete();
 261 #if INCLUDE_JVMCI
 262       if (CompileBroker::compiler(task->comp_level())->is_jvmci()) {
 263         if (!task->has_waiter()) {
 264           // The waiting thread timed out and thus did not free the task.
 265           free_task = true;
 266         }
 267         task->set_jvmci_compiler_thread(NULL);
 268       }
 269 #endif
 270       if (!free_task) {
 271         // Notify the waiting thread that the compilation has completed
 272         // so that it can free the task.
 273         task->lock()->notify_all();
 274       }
 275     }
 276     if (free_task) {
 277       // The task can only be freed once the task lock is released.
 278       CompileTask::free(task);
 279     }
 280   } else {
 281     task->mark_complete();
 282 
 283     // By convention, the compiling thread is responsible for
 284     // recycling a non-blocking CompileTask.
 285     CompileTask::free(task);
 286   }
 287 }
 288 
 289 /**
 290  * Add a CompileTask to a CompileQueue.
 291  */
 292 void CompileQueue::add(CompileTask* task) {
 293   assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
 294 
 295   task->set_next(NULL);
 296   task->set_prev(NULL);
 297 
 298   if (_last == NULL) {
 299     // The compile queue is empty.
 300     assert(_first == NULL, "queue is empty");
 301     _first = task;
 302     _last = task;
 303   } else {
 304     // Append the task to the queue.
 305     assert(_last->next() == NULL, "not last");
 306     _last->set_next(task);
 307     task->set_prev(_last);
 308     _last = task;
 309   }
 310   ++_size;
 311 
 312   // Mark the method as being in the compile queue.
 313   task->method()->set_queued_for_compilation();
 314 
 315   if (CIPrintCompileQueue) {
 316     print_tty();
 317   }
 318 
 319   if (LogCompilation && xtty != NULL) {
 320     task->log_task_queued();
 321   }
 322 
 323   // Notify CompilerThreads that a task is available.
 324   MethodCompileQueue_lock->notify_all();
 325 }
 326 
 327 /**
 328  * Empties compilation queue by putting all compilation tasks onto
 329  * a freelist. Furthermore, the method wakes up all threads that are
 330  * waiting on a compilation task to finish. This can happen if background
 331  * compilation is disabled.
 332  */
 333 void CompileQueue::free_all() {
 334   MutexLocker mu(MethodCompileQueue_lock);
 335   CompileTask* next = _first;
 336 
 337   // Iterate over all tasks in the compile queue
 338   while (next != NULL) {
 339     CompileTask* current = next;
 340     next = current->next();
 341     {
 342       // Wake up thread that blocks on the compile task.
 343       MutexLocker ct_lock(current->lock());
 344       current->lock()->notify();
 345     }
 346     // Put the task back on the freelist.
 347     CompileTask::free(current);
 348   }
 349   _first = NULL;
 350 
 351   // Wake up all threads that block on the queue.
 352   MethodCompileQueue_lock->notify_all();
 353 }
 354 
 355 /**
 356  * Get the next CompileTask from a CompileQueue
 357  */
 358 CompileTask* CompileQueue::get() {
 359   // save methods from RedefineClasses across safepoint
 360   // across MethodCompileQueue_lock below.
 361   methodHandle save_method;
 362   methodHandle save_hot_method;
 363 
 364   MutexLocker locker(MethodCompileQueue_lock);
 365   // If _first is NULL we have no more compile jobs. There are two reasons for
 366   // having no compile jobs: First, we compiled everything we wanted. Second,
 367   // we ran out of code cache so compilation has been disabled. In the latter
 368   // case we perform code cache sweeps to free memory such that we can re-enable
 369   // compilation.
 370   while (_first == NULL) {
 371     // Exit loop if compilation is disabled forever
 372     if (CompileBroker::is_compilation_disabled_forever()) {
 373       return NULL;
 374     }
 375 
 376     // If there are no compilation tasks and we can compile new jobs
 377     // (i.e., there is enough free space in the code cache) there is
 378     // no need to invoke the sweeper. As a result, the hotness of methods
 379     // remains unchanged. This behavior is desired, since we want to keep
 380     // the stable state, i.e., we do not want to evict methods from the
 381     // code cache if it is unnecessary.
 382     // We need a timed wait here, since compiler threads can exit if compilation
 383     // is disabled forever. We use 5 seconds wait time; the exiting of compiler threads
 384     // is not critical and we do not want idle compiler threads to wake up too often.
 385     MethodCompileQueue_lock->wait(!Mutex::_no_safepoint_check_flag, 5*1000);
 386   }
 387 
 388   if (CompileBroker::is_compilation_disabled_forever()) {
 389     return NULL;
 390   }
 391 
 392   CompileTask* task;
 393   {
 394     NoSafepointVerifier nsv;
 395     task = CompilationPolicy::policy()->select_task(this);
 396   }
 397 
 398   if (task != NULL) {
 399     // Save method pointers across unlock safepoint.  The task is removed from
 400     // the compilation queue, which is walked during RedefineClasses.
 401     save_method = methodHandle(task->method());
 402     save_hot_method = methodHandle(task->hot_method());
 403 
 404     remove(task);
 405     purge_stale_tasks(); // may temporarily release MCQ lock
 406   }
 407 
 408   return task;
 409 }
 410 
 411 // Clean & deallocate stale compile tasks.
 412 // Temporarily releases MethodCompileQueue lock.
 413 void CompileQueue::purge_stale_tasks() {
 414   assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
 415   if (_first_stale != NULL) {
 416     // Stale tasks are purged when MCQ lock is released,
 417     // but _first_stale updates are protected by MCQ lock.
 418     // Once task processing starts and MCQ lock is released,
 419     // other compiler threads can reuse _first_stale.
 420     CompileTask* head = _first_stale;
 421     _first_stale = NULL;
 422     {
 423       MutexUnlocker ul(MethodCompileQueue_lock);
 424       for (CompileTask* task = head; task != NULL; ) {
 425         CompileTask* next_task = task->next();
 426         CompileTaskWrapper ctw(task); // Frees the task
 427         task->set_failure_reason("stale task");
 428         task = next_task;
 429       }
 430     }
 431   }
 432 }
 433 
 434 void CompileQueue::remove(CompileTask* task) {
 435    assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
 436   if (task->prev() != NULL) {
 437     task->prev()->set_next(task->next());
 438   } else {
 439     // max is the first element
 440     assert(task == _first, "Sanity");
 441     _first = task->next();
 442   }
 443 
 444   if (task->next() != NULL) {
 445     task->next()->set_prev(task->prev());
 446   } else {
 447     // max is the last element
 448     assert(task == _last, "Sanity");
 449     _last = task->prev();
 450   }
 451   --_size;
 452 }
 453 
 454 void CompileQueue::remove_and_mark_stale(CompileTask* task) {
 455   assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
 456   remove(task);
 457 
 458   // Enqueue the task for reclamation (should be done outside MCQ lock)
 459   task->set_next(_first_stale);
 460   task->set_prev(NULL);
 461   _first_stale = task;
 462 }
 463 
 464 // methods in the compile queue need to be marked as used on the stack
 465 // so that they don't get reclaimed by Redefine Classes
 466 void CompileQueue::mark_on_stack() {
 467   CompileTask* task = _first;
 468   while (task != NULL) {
 469     task->mark_on_stack();
 470     task = task->next();
 471   }
 472 }
 473 
 474 
 475 CompileQueue* CompileBroker::compile_queue(int comp_level) {
 476   if (is_c2_compile(comp_level)) return _c2_compile_queue;
 477   if (is_c1_compile(comp_level)) return _c1_compile_queue;
 478   return NULL;
 479 }
 480 
 481 void CompileBroker::print_compile_queues(outputStream* st) {
 482   st->print_cr("Current compiles: ");
 483   MutexLocker locker(MethodCompileQueue_lock);
 484 
 485   char buf[2000];
 486   int buflen = sizeof(buf);
 487   Threads::print_threads_compiling(st, buf, buflen);
 488 
 489   st->cr();
 490   if (_c1_compile_queue != NULL) {
 491     _c1_compile_queue->print(st);
 492   }
 493   if (_c2_compile_queue != NULL) {
 494     _c2_compile_queue->print(st);
 495   }
 496 }
 497 
 498 void CompileQueue::print(outputStream* st) {
 499   assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
 500   st->print_cr("%s:", name());
 501   CompileTask* task = _first;
 502   if (task == NULL) {
 503     st->print_cr("Empty");
 504   } else {
 505     while (task != NULL) {
 506       task->print(st, NULL, true, true);
 507       task = task->next();
 508     }
 509   }
 510   st->cr();
 511 }
 512 
 513 void CompileQueue::print_tty() {
 514   ttyLocker ttyl;
 515   print(tty);
 516 }
 517 
 518 CompilerCounters::CompilerCounters() {
 519   _current_method[0] = '\0';
 520   _compile_type = CompileBroker::no_compile;
 521 }
 522 
 523 // ------------------------------------------------------------------
 524 // CompileBroker::compilation_init
 525 //
 526 // Initialize the Compilation object
 527 void CompileBroker::compilation_init_phase1(TRAPS) {
 528   _last_method_compiled[0] = '\0';
 529 
 530   // No need to initialize compilation system if we do not use it.
 531   if (!UseCompiler) {
 532     return;
 533   }
 534   // Set the interface to the current compiler(s).
 535   int c1_count = CompilationPolicy::policy()->compiler_count(CompLevel_simple);
 536   int c2_count = CompilationPolicy::policy()->compiler_count(CompLevel_full_optimization);
 537 
 538 #if INCLUDE_JVMCI
 539   if (EnableJVMCI) {
 540     // This is creating a JVMCICompiler singleton.
 541     JVMCICompiler* jvmci = new JVMCICompiler();
 542 
 543     if (UseJVMCICompiler) {
 544       _compilers[1] = jvmci;
 545       if (FLAG_IS_DEFAULT(JVMCIThreads)) {
 546         if (BootstrapJVMCI) {
 547           // JVMCI will bootstrap so give it more threads
 548           c2_count = MIN2(32, os::active_processor_count());
 549         }
 550       } else {
 551         c2_count = JVMCIThreads;
 552       }
 553       if (FLAG_IS_DEFAULT(JVMCIHostThreads)) {
 554       } else {
 555         c1_count = JVMCIHostThreads;
 556       }
 557     }
 558   }
 559 #endif // INCLUDE_JVMCI
 560 
 561 #ifdef COMPILER1
 562   if (c1_count > 0) {
 563     _compilers[0] = new Compiler();
 564   }
 565 #endif // COMPILER1
 566 
 567 #ifdef COMPILER2
 568   if (true JVMCI_ONLY( && !UseJVMCICompiler)) {
 569     if (c2_count > 0) {
 570       _compilers[1] = new C2Compiler();
 571     }
 572   }
 573 #endif // COMPILER2
 574 
 575   // Start the compiler thread(s) and the sweeper thread
 576   init_compiler_sweeper_threads(c1_count, c2_count);
 577   // totalTime performance counter is always created as it is required
 578   // by the implementation of java.lang.management.CompilationMBean.
 579   {
 580     EXCEPTION_MARK;
 581     _perf_total_compilation =
 582                  PerfDataManager::create_counter(JAVA_CI, "totalTime",
 583                                                  PerfData::U_Ticks, CHECK);
 584   }
 585 
 586   if (UsePerfData) {
 587 
 588     EXCEPTION_MARK;
 589 
 590     // create the jvmstat performance counters
 591     _perf_osr_compilation =
 592                  PerfDataManager::create_counter(SUN_CI, "osrTime",
 593                                                  PerfData::U_Ticks, CHECK);
 594 
 595     _perf_standard_compilation =
 596                  PerfDataManager::create_counter(SUN_CI, "standardTime",
 597                                                  PerfData::U_Ticks, CHECK);
 598 
 599     _perf_total_bailout_count =
 600                  PerfDataManager::create_counter(SUN_CI, "totalBailouts",
 601                                                  PerfData::U_Events, CHECK);
 602 
 603     _perf_total_invalidated_count =
 604                  PerfDataManager::create_counter(SUN_CI, "totalInvalidates",
 605                                                  PerfData::U_Events, CHECK);
 606 
 607     _perf_total_compile_count =
 608                  PerfDataManager::create_counter(SUN_CI, "totalCompiles",
 609                                                  PerfData::U_Events, CHECK);
 610     _perf_total_osr_compile_count =
 611                  PerfDataManager::create_counter(SUN_CI, "osrCompiles",
 612                                                  PerfData::U_Events, CHECK);
 613 
 614     _perf_total_standard_compile_count =
 615                  PerfDataManager::create_counter(SUN_CI, "standardCompiles",
 616                                                  PerfData::U_Events, CHECK);
 617 
 618     _perf_sum_osr_bytes_compiled =
 619                  PerfDataManager::create_counter(SUN_CI, "osrBytes",
 620                                                  PerfData::U_Bytes, CHECK);
 621 
 622     _perf_sum_standard_bytes_compiled =
 623                  PerfDataManager::create_counter(SUN_CI, "standardBytes",
 624                                                  PerfData::U_Bytes, CHECK);
 625 
 626     _perf_sum_nmethod_size =
 627                  PerfDataManager::create_counter(SUN_CI, "nmethodSize",
 628                                                  PerfData::U_Bytes, CHECK);
 629 
 630     _perf_sum_nmethod_code_size =
 631                  PerfDataManager::create_counter(SUN_CI, "nmethodCodeSize",
 632                                                  PerfData::U_Bytes, CHECK);
 633 
 634     _perf_last_method =
 635                  PerfDataManager::create_string_variable(SUN_CI, "lastMethod",
 636                                        CompilerCounters::cmname_buffer_length,
 637                                        "", CHECK);
 638 
 639     _perf_last_failed_method =
 640             PerfDataManager::create_string_variable(SUN_CI, "lastFailedMethod",
 641                                        CompilerCounters::cmname_buffer_length,
 642                                        "", CHECK);
 643 
 644     _perf_last_invalidated_method =
 645         PerfDataManager::create_string_variable(SUN_CI, "lastInvalidatedMethod",
 646                                      CompilerCounters::cmname_buffer_length,
 647                                      "", CHECK);
 648 
 649     _perf_last_compile_type =
 650              PerfDataManager::create_variable(SUN_CI, "lastType",
 651                                               PerfData::U_None,
 652                                               (jlong)CompileBroker::no_compile,
 653                                               CHECK);
 654 
 655     _perf_last_compile_size =
 656              PerfDataManager::create_variable(SUN_CI, "lastSize",
 657                                               PerfData::U_Bytes,
 658                                               (jlong)CompileBroker::no_compile,
 659                                               CHECK);
 660 
 661 
 662     _perf_last_failed_type =
 663              PerfDataManager::create_variable(SUN_CI, "lastFailedType",
 664                                               PerfData::U_None,
 665                                               (jlong)CompileBroker::no_compile,
 666                                               CHECK);
 667 
 668     _perf_last_invalidated_type =
 669          PerfDataManager::create_variable(SUN_CI, "lastInvalidatedType",
 670                                           PerfData::U_None,
 671                                           (jlong)CompileBroker::no_compile,
 672                                           CHECK);
 673   }
 674 }
 675 
 676 // Completes compiler initialization. Compilation requests submitted
 677 // prior to this will be silently ignored.
 678 void CompileBroker::compilation_init_phase2() {
 679   _initialized = true;
 680 }
 681 
 682 JavaThread* CompileBroker::make_thread(const char* name, CompileQueue* queue, CompilerCounters* counters,
 683                                        AbstractCompiler* comp, bool compiler_thread, TRAPS) {
 684   JavaThread* thread = NULL;
 685   Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, CHECK_0);
 686   InstanceKlass* klass = InstanceKlass::cast(k);
 687   instanceHandle thread_oop = klass->allocate_instance_handle(CHECK_0);
 688   Handle string = java_lang_String::create_from_str(name, CHECK_0);
 689 
 690   // Initialize thread_oop to put it into the system threadGroup
 691   Handle thread_group (THREAD,  Universe::system_thread_group());
 692   JavaValue result(T_VOID);
 693   JavaCalls::call_special(&result, thread_oop,
 694                        klass,
 695                        vmSymbols::object_initializer_name(),
 696                        vmSymbols::threadgroup_string_void_signature(),
 697                        thread_group,
 698                        string,
 699                        CHECK_0);
 700 
 701   {
 702     MutexLocker mu(Threads_lock, THREAD);
 703     if (compiler_thread) {
 704       thread = new CompilerThread(queue, counters);
 705     } else {
 706       thread = new CodeCacheSweeperThread();
 707     }
 708     // At this point the new CompilerThread data-races with this startup
 709     // thread (which I believe is the primoridal thread and NOT the VM
 710     // thread).  This means Java bytecodes being executed at startup can
 711     // queue compile jobs which will run at whatever default priority the
 712     // newly created CompilerThread runs at.
 713 
 714 
 715     // At this point it may be possible that no osthread was created for the
 716     // JavaThread due to lack of memory. We would have to throw an exception
 717     // in that case. However, since this must work and we do not allow
 718     // exceptions anyway, check and abort if this fails. But first release the
 719     // lock.
 720 
 721     if (thread != NULL && thread->osthread() != NULL) {
 722 
 723       java_lang_Thread::set_thread(thread_oop(), thread);
 724 
 725       // Note that this only sets the JavaThread _priority field, which by
 726       // definition is limited to Java priorities and not OS priorities.
 727       // The os-priority is set in the CompilerThread startup code itself
 728 
 729       java_lang_Thread::set_priority(thread_oop(), NearMaxPriority);
 730 
 731       // Note that we cannot call os::set_priority because it expects Java
 732       // priorities and we are *explicitly* using OS priorities so that it's
 733       // possible to set the compiler thread priority higher than any Java
 734       // thread.
 735 
 736       int native_prio = CompilerThreadPriority;
 737       if (native_prio == -1) {
 738         if (UseCriticalCompilerThreadPriority) {
 739           native_prio = os::java_to_os_priority[CriticalPriority];
 740         } else {
 741           native_prio = os::java_to_os_priority[NearMaxPriority];
 742         }
 743       }
 744       os::set_native_priority(thread, native_prio);
 745 
 746       java_lang_Thread::set_daemon(thread_oop());
 747 
 748       thread->set_threadObj(thread_oop());
 749       if (compiler_thread) {
 750         thread->as_CompilerThread()->set_compiler(comp);
 751       }
 752       Threads::add(thread);
 753       Thread::start(thread);
 754     }
 755   }
 756 
 757   // First release lock before aborting VM.
 758   if (thread == NULL || thread->osthread() == NULL) {
 759     vm_exit_during_initialization("java.lang.OutOfMemoryError",
 760                                   os::native_thread_creation_failed_msg());
 761   }
 762 
 763   // Let go of Threads_lock before yielding
 764   os::naked_yield(); // make sure that the compiler thread is started early (especially helpful on SOLARIS)
 765 
 766   return thread;
 767 }
 768 
 769 
 770 void CompileBroker::init_compiler_sweeper_threads(int c1_compiler_count, int c2_compiler_count) {
 771   EXCEPTION_MARK;
 772 #if !defined(ZERO)
 773   assert(c2_compiler_count > 0 || c1_compiler_count > 0, "No compilers?");
 774 #endif // !ZERO
 775   // Initialize the compilation queue
 776   if (c2_compiler_count > 0) {
 777     const char* name = JVMCI_ONLY(UseJVMCICompiler ? "JVMCI compile queue" :) "C2 compile queue";
 778     _c2_compile_queue  = new CompileQueue(name);
 779     _compilers[1]->set_num_compiler_threads(c2_compiler_count);
 780   }
 781   if (c1_compiler_count > 0) {
 782     _c1_compile_queue  = new CompileQueue("C1 compile queue");
 783     _compilers[0]->set_num_compiler_threads(c1_compiler_count);
 784   }
 785 
 786   int compiler_count = c1_compiler_count + c2_compiler_count;
 787 
 788   char name_buffer[256];
 789   const bool compiler_thread = true;
 790   for (int i = 0; i < c2_compiler_count; i++) {
 791     // Create a name for our thread.
 792     sprintf(name_buffer, "%s CompilerThread%d", _compilers[1]->name(), i);
 793     CompilerCounters* counters = new CompilerCounters();
 794     make_thread(name_buffer, _c2_compile_queue, counters, _compilers[1], compiler_thread, CHECK);
 795   }
 796 
 797   for (int i = c2_compiler_count; i < compiler_count; i++) {
 798     // Create a name for our thread.
 799     sprintf(name_buffer, "C1 CompilerThread%d", i);
 800     CompilerCounters* counters = new CompilerCounters();
 801     // C1
 802     make_thread(name_buffer, _c1_compile_queue, counters, _compilers[0], compiler_thread, CHECK);
 803   }
 804 
 805   if (UsePerfData) {
 806     PerfDataManager::create_constant(SUN_CI, "threads", PerfData::U_Bytes, compiler_count, CHECK);
 807   }
 808 
 809   if (MethodFlushing) {
 810     // Initialize the sweeper thread
 811     make_thread("Sweeper thread", NULL, NULL, NULL, false, CHECK);
 812   }
 813 }
 814 
 815 
 816 /**
 817  * Set the methods on the stack as on_stack so that redefine classes doesn't
 818  * reclaim them. This method is executed at a safepoint.
 819  */
 820 void CompileBroker::mark_on_stack() {
 821   assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
 822   // Since we are at a safepoint, we do not need a lock to access
 823   // the compile queues.
 824   if (_c2_compile_queue != NULL) {
 825     _c2_compile_queue->mark_on_stack();
 826   }
 827   if (_c1_compile_queue != NULL) {
 828     _c1_compile_queue->mark_on_stack();
 829   }
 830 }
 831 
 832 // ------------------------------------------------------------------
 833 // CompileBroker::compile_method
 834 //
 835 // Request compilation of a method.
 836 void CompileBroker::compile_method_base(const methodHandle& method,
 837                                         int osr_bci,
 838                                         int comp_level,
 839                                         const methodHandle& hot_method,
 840                                         int hot_count,
 841                                         CompileTask::CompileReason compile_reason,
 842                                         bool blocking,
 843                                         Thread* thread) {
 844   guarantee(!method->is_abstract(), "cannot compile abstract methods");
 845   assert(method->method_holder()->is_instance_klass(),
 846          "sanity check");
 847   assert(!method->method_holder()->is_not_initialized(),
 848          "method holder must be initialized");
 849   assert(!method->is_method_handle_intrinsic(), "do not enqueue these guys");
 850 
 851   if (CIPrintRequests) {
 852     tty->print("request: ");
 853     method->print_short_name(tty);
 854     if (osr_bci != InvocationEntryBci) {
 855       tty->print(" osr_bci: %d", osr_bci);
 856     }
 857     tty->print(" level: %d comment: %s count: %d", comp_level, CompileTask::reason_name(compile_reason), hot_count);
 858     if (!hot_method.is_null()) {
 859       tty->print(" hot: ");
 860       if (hot_method() != method()) {
 861           hot_method->print_short_name(tty);
 862       } else {
 863         tty->print("yes");
 864       }
 865     }
 866     tty->cr();
 867   }
 868 
 869   // A request has been made for compilation.  Before we do any
 870   // real work, check to see if the method has been compiled
 871   // in the meantime with a definitive result.
 872   if (compilation_is_complete(method, osr_bci, comp_level)) {
 873     return;
 874   }
 875 
 876 #ifndef PRODUCT
 877   if (osr_bci != -1 && !FLAG_IS_DEFAULT(OSROnlyBCI)) {
 878     if ((OSROnlyBCI > 0) ? (OSROnlyBCI != osr_bci) : (-OSROnlyBCI == osr_bci)) {
 879       // Positive OSROnlyBCI means only compile that bci.  Negative means don't compile that BCI.
 880       return;
 881     }
 882   }
 883 #endif
 884 
 885   // If this method is already in the compile queue, then
 886   // we do not block the current thread.
 887   if (compilation_is_in_queue(method)) {
 888     // We may want to decay our counter a bit here to prevent
 889     // multiple denied requests for compilation.  This is an
 890     // open compilation policy issue. Note: The other possibility,
 891     // in the case that this is a blocking compile request, is to have
 892     // all subsequent blocking requesters wait for completion of
 893     // ongoing compiles. Note that in this case we'll need a protocol
 894     // for freeing the associated compile tasks. [Or we could have
 895     // a single static monitor on which all these waiters sleep.]
 896     return;
 897   }
 898 
 899   if (TieredCompilation) {
 900     // Tiered policy requires MethodCounters to exist before adding a method to
 901     // the queue. Create if we don't have them yet.
 902     method->get_method_counters(thread);
 903   }
 904 
 905   // Outputs from the following MutexLocker block:
 906   CompileTask* task     = NULL;
 907   CompileQueue* queue  = compile_queue(comp_level);
 908 
 909   // Acquire our lock.
 910   {
 911     MutexLocker locker(MethodCompileQueue_lock, thread);
 912 
 913     // Make sure the method has not slipped into the queues since
 914     // last we checked; note that those checks were "fast bail-outs".
 915     // Here we need to be more careful, see 14012000 below.
 916     if (compilation_is_in_queue(method)) {
 917       return;
 918     }
 919 
 920     // We need to check again to see if the compilation has
 921     // completed.  A previous compilation may have registered
 922     // some result.
 923     if (compilation_is_complete(method, osr_bci, comp_level)) {
 924       return;
 925     }
 926 
 927     // We now know that this compilation is not pending, complete,
 928     // or prohibited.  Assign a compile_id to this compilation
 929     // and check to see if it is in our [Start..Stop) range.
 930     int compile_id = assign_compile_id(method, osr_bci);
 931     if (compile_id == 0) {
 932       // The compilation falls outside the allowed range.
 933       return;
 934     }
 935 
 936 #if INCLUDE_JVMCI
 937     if (UseJVMCICompiler) {
 938       if (blocking) {
 939         // Don't allow blocking compiles for requests triggered by JVMCI.
 940         if (thread->is_Compiler_thread()) {
 941           blocking = false;
 942         }
 943 
 944         // Don't allow blocking compiles if inside a class initializer or while performing class loading
 945         vframeStream vfst((JavaThread*) thread);
 946         for (; !vfst.at_end(); vfst.next()) {
 947           if (vfst.method()->is_static_initializer() ||
 948               (vfst.method()->method_holder()->is_subclass_of(SystemDictionary::ClassLoader_klass()) &&
 949                   vfst.method()->name() == vmSymbols::loadClass_name())) {
 950             blocking = false;
 951             break;
 952           }
 953         }
 954 
 955         // Don't allow blocking compilation requests to JVMCI
 956         // if JVMCI itself is not yet initialized
 957         if (!JVMCIRuntime::is_HotSpotJVMCIRuntime_initialized() && compiler(comp_level)->is_jvmci()) {
 958           blocking = false;
 959         }
 960 
 961         // Don't allow blocking compilation requests if we are in JVMCIRuntime::shutdown
 962         // to avoid deadlock between compiler thread(s) and threads run at shutdown
 963         // such as the DestroyJavaVM thread.
 964         if (JVMCIRuntime::shutdown_called()) {
 965           blocking = false;
 966         }
 967       }
 968     }
 969 #endif // INCLUDE_JVMCI
 970 
 971     // We will enter the compilation in the queue.
 972     // 14012000: Note that this sets the queued_for_compile bits in
 973     // the target method. We can now reason that a method cannot be
 974     // queued for compilation more than once, as follows:
 975     // Before a thread queues a task for compilation, it first acquires
 976     // the compile queue lock, then checks if the method's queued bits
 977     // are set or it has already been compiled. Thus there can not be two
 978     // instances of a compilation task for the same method on the
 979     // compilation queue. Consider now the case where the compilation
 980     // thread has already removed a task for that method from the queue
 981     // and is in the midst of compiling it. In this case, the
 982     // queued_for_compile bits must be set in the method (and these
 983     // will be visible to the current thread, since the bits were set
 984     // under protection of the compile queue lock, which we hold now.
 985     // When the compilation completes, the compiler thread first sets
 986     // the compilation result and then clears the queued_for_compile
 987     // bits. Neither of these actions are protected by a barrier (or done
 988     // under the protection of a lock), so the only guarantee we have
 989     // (on machines with TSO (Total Store Order)) is that these values
 990     // will update in that order. As a result, the only combinations of
 991     // these bits that the current thread will see are, in temporal order:
 992     // <RESULT, QUEUE> :
 993     //     <0, 1> : in compile queue, but not yet compiled
 994     //     <1, 1> : compiled but queue bit not cleared
 995     //     <1, 0> : compiled and queue bit cleared
 996     // Because we first check the queue bits then check the result bits,
 997     // we are assured that we cannot introduce a duplicate task.
 998     // Note that if we did the tests in the reverse order (i.e. check
 999     // result then check queued bit), we could get the result bit before
1000     // the compilation completed, and the queue bit after the compilation
1001     // completed, and end up introducing a "duplicate" (redundant) task.
1002     // In that case, the compiler thread should first check if a method
1003     // has already been compiled before trying to compile it.
1004     // NOTE: in the event that there are multiple compiler threads and
1005     // there is de-optimization/recompilation, things will get hairy,
1006     // and in that case it's best to protect both the testing (here) of
1007     // these bits, and their updating (here and elsewhere) under a
1008     // common lock.
1009     task = create_compile_task(queue,
1010                                compile_id, method,
1011                                osr_bci, comp_level,
1012                                hot_method, hot_count, compile_reason,
1013                                blocking);
1014   }
1015 
1016   if (blocking) {
1017     wait_for_completion(task);
1018   }
1019 }
1020 
1021 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1022                                        int comp_level,
1023                                        const methodHandle& hot_method, int hot_count,
1024                                        CompileTask::CompileReason compile_reason,
1025                                        Thread* THREAD) {
1026   // Do nothing if compilebroker is not initalized or compiles are submitted on level none
1027   if (!_initialized || comp_level == CompLevel_none) {
1028     return NULL;
1029   }
1030 
1031   AbstractCompiler *comp = CompileBroker::compiler(comp_level);
1032   assert(comp != NULL, "Ensure we have a compiler");
1033 
1034   DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, comp);
1035   nmethod* nm = CompileBroker::compile_method(method, osr_bci, comp_level, hot_method, hot_count, compile_reason, directive, THREAD);
1036   DirectivesStack::release(directive);
1037   return nm;
1038 }
1039 
1040 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1041                                          int comp_level,
1042                                          const methodHandle& hot_method, int hot_count,
1043                                          CompileTask::CompileReason compile_reason,
1044                                          DirectiveSet* directive,
1045                                          Thread* THREAD) {
1046 
1047   // make sure arguments make sense
1048   assert(method->method_holder()->is_instance_klass(), "not an instance method");
1049   assert(osr_bci == InvocationEntryBci || (0 <= osr_bci && osr_bci < method->code_size()), "bci out of range");
1050   assert(!method->is_abstract() && (osr_bci == InvocationEntryBci || !method->is_native()), "cannot compile abstract/native methods");
1051   assert(!method->method_holder()->is_not_initialized(), "method holder must be initialized");
1052   assert(!TieredCompilation || comp_level <= TieredStopAtLevel, "Invalid compilation level");
1053   // allow any levels for WhiteBox
1054   assert(WhiteBoxAPI || TieredCompilation || comp_level == CompLevel_highest_tier, "only CompLevel_highest_tier must be used in non-tiered");
1055   // return quickly if possible
1056 
1057   // lock, make sure that the compilation
1058   // isn't prohibited in a straightforward way.
1059   AbstractCompiler* comp = CompileBroker::compiler(comp_level);
1060   if (comp == NULL || !comp->can_compile_method(method) ||
1061       compilation_is_prohibited(method, osr_bci, comp_level, directive->ExcludeOption)) {
1062     return NULL;
1063   }
1064 
1065 #if INCLUDE_JVMCI
1066   if (comp->is_jvmci() && !JVMCIRuntime::can_initialize_JVMCI()) {
1067     return NULL;
1068   }
1069 #endif
1070 
1071   if (osr_bci == InvocationEntryBci) {
1072     // standard compilation
1073     CompiledMethod* method_code = method->code();
1074     if (method_code != NULL && method_code->is_nmethod()) {
1075       if (compilation_is_complete(method, osr_bci, comp_level)) {
1076         return (nmethod*) method_code;
1077       }
1078     }
1079     if (method->is_not_compilable(comp_level)) {
1080       return NULL;
1081     }
1082   } else {
1083     // osr compilation
1084 #ifndef TIERED
1085     // seems like an assert of dubious value
1086     assert(comp_level == CompLevel_highest_tier,
1087            "all OSR compiles are assumed to be at a single compilation level");
1088 #endif // TIERED
1089     // We accept a higher level osr method
1090     nmethod* nm = method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1091     if (nm != NULL) return nm;
1092     if (method->is_not_osr_compilable(comp_level)) return NULL;
1093   }
1094 
1095   assert(!HAS_PENDING_EXCEPTION, "No exception should be present");
1096   // some prerequisites that are compiler specific
1097   if (comp->is_c2()) {
1098     method->constants()->resolve_string_constants(CHECK_AND_CLEAR_NULL);
1099     // Resolve all classes seen in the signature of the method
1100     // we are compiling.
1101     Method::load_signature_classes(method, CHECK_AND_CLEAR_NULL);
1102   }
1103 
1104   // If the method is native, do the lookup in the thread requesting
1105   // the compilation. Native lookups can load code, which is not
1106   // permitted during compilation.
1107   //
1108   // Note: A native method implies non-osr compilation which is
1109   //       checked with an assertion at the entry of this method.
1110   if (method->is_native() && !method->is_method_handle_intrinsic()) {
1111     bool in_base_library;
1112     address adr = NativeLookup::lookup(method, in_base_library, THREAD);
1113     if (HAS_PENDING_EXCEPTION) {
1114       // In case of an exception looking up the method, we just forget
1115       // about it. The interpreter will kick-in and throw the exception.
1116       method->set_not_compilable(); // implies is_not_osr_compilable()
1117       CLEAR_PENDING_EXCEPTION;
1118       return NULL;
1119     }
1120     assert(method->has_native_function(), "must have native code by now");
1121   }
1122 
1123   // RedefineClasses() has replaced this method; just return
1124   if (method->is_old()) {
1125     return NULL;
1126   }
1127 
1128   // JVMTI -- post_compile_event requires jmethod_id() that may require
1129   // a lock the compiling thread can not acquire. Prefetch it here.
1130   if (JvmtiExport::should_post_compiled_method_load()) {
1131     method->jmethod_id();
1132   }
1133 
1134   // do the compilation
1135   if (method->is_native()) {
1136     if (!PreferInterpreterNativeStubs || method->is_method_handle_intrinsic()) {
1137       // The following native methods:
1138       //
1139       // java.lang.Float.intBitsToFloat
1140       // java.lang.Float.floatToRawIntBits
1141       // java.lang.Double.longBitsToDouble
1142       // java.lang.Double.doubleToRawLongBits
1143       //
1144       // are called through the interpreter even if interpreter native stubs
1145       // are not preferred (i.e., calling through adapter handlers is preferred).
1146       // The reason is that on x86_32 signaling NaNs (sNaNs) are not preserved
1147       // if the version of the methods from the native libraries is called.
1148       // As the interpreter and the C2-intrinsified version of the methods preserves
1149       // sNaNs, that would result in an inconsistent way of handling of sNaNs.
1150       if ((UseSSE >= 1 &&
1151           (method->intrinsic_id() == vmIntrinsics::_intBitsToFloat ||
1152            method->intrinsic_id() == vmIntrinsics::_floatToRawIntBits)) ||
1153           (UseSSE >= 2 &&
1154            (method->intrinsic_id() == vmIntrinsics::_longBitsToDouble ||
1155             method->intrinsic_id() == vmIntrinsics::_doubleToRawLongBits))) {
1156         return NULL;
1157       }
1158 
1159       // To properly handle the appendix argument for out-of-line calls we are using a small trampoline that
1160       // pops off the appendix argument and jumps to the target (see gen_special_dispatch in SharedRuntime).
1161       //
1162       // Since normal compiled-to-compiled calls are not able to handle such a thing we MUST generate an adapter
1163       // in this case.  If we can't generate one and use it we can not execute the out-of-line method handle calls.
1164       AdapterHandlerLibrary::create_native_wrapper(method);
1165     } else {
1166       return NULL;
1167     }
1168   } else {
1169     // If the compiler is shut off due to code cache getting full
1170     // fail out now so blocking compiles dont hang the java thread
1171     if (!should_compile_new_jobs()) {
1172       CompilationPolicy::policy()->delay_compilation(method());
1173       return NULL;
1174     }
1175     bool is_blocking = !directive->BackgroundCompilationOption || CompileTheWorld || ReplayCompiles;
1176     compile_method_base(method, osr_bci, comp_level, hot_method, hot_count, compile_reason, is_blocking, THREAD);
1177   }
1178 
1179   // return requested nmethod
1180   // We accept a higher level osr method
1181   if (osr_bci == InvocationEntryBci) {
1182     CompiledMethod* code = method->code();
1183     if (code == NULL) {
1184       return (nmethod*) code;
1185     } else {
1186       return code->as_nmethod_or_null();
1187     }
1188   }
1189   return method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1190 }
1191 
1192 
1193 // ------------------------------------------------------------------
1194 // CompileBroker::compilation_is_complete
1195 //
1196 // See if compilation of this method is already complete.
1197 bool CompileBroker::compilation_is_complete(const methodHandle& method,
1198                                             int                 osr_bci,
1199                                             int                 comp_level) {
1200   bool is_osr = (osr_bci != standard_entry_bci);
1201   if (is_osr) {
1202     if (method->is_not_osr_compilable(comp_level)) {
1203       return true;
1204     } else {
1205       nmethod* result = method->lookup_osr_nmethod_for(osr_bci, comp_level, true);
1206       return (result != NULL);
1207     }
1208   } else {
1209     if (method->is_not_compilable(comp_level)) {
1210       return true;
1211     } else {
1212       CompiledMethod* result = method->code();
1213       if (result == NULL) return false;
1214       return comp_level == result->comp_level();
1215     }
1216   }
1217 }
1218 
1219 
1220 /**
1221  * See if this compilation is already requested.
1222  *
1223  * Implementation note: there is only a single "is in queue" bit
1224  * for each method.  This means that the check below is overly
1225  * conservative in the sense that an osr compilation in the queue
1226  * will block a normal compilation from entering the queue (and vice
1227  * versa).  This can be remedied by a full queue search to disambiguate
1228  * cases.  If it is deemed profitable, this may be done.
1229  */
1230 bool CompileBroker::compilation_is_in_queue(const methodHandle& method) {
1231   return method->queued_for_compilation();
1232 }
1233 
1234 // ------------------------------------------------------------------
1235 // CompileBroker::compilation_is_prohibited
1236 //
1237 // See if this compilation is not allowed.
1238 bool CompileBroker::compilation_is_prohibited(const methodHandle& method, int osr_bci, int comp_level, bool excluded) {
1239   bool is_native = method->is_native();
1240   // Some compilers may not support the compilation of natives.
1241   AbstractCompiler *comp = compiler(comp_level);
1242   if (is_native &&
1243       (!CICompileNatives || comp == NULL || !comp->supports_native())) {
1244     method->set_not_compilable_quietly(comp_level);
1245     return true;
1246   }
1247 
1248   bool is_osr = (osr_bci != standard_entry_bci);
1249   // Some compilers may not support on stack replacement.
1250   if (is_osr &&
1251       (!CICompileOSR || comp == NULL || !comp->supports_osr())) {
1252     method->set_not_osr_compilable(comp_level);
1253     return true;
1254   }
1255 
1256   // The method may be explicitly excluded by the user.
1257   double scale;
1258   if (excluded || (CompilerOracle::has_option_value(method, "CompileThresholdScaling", scale) && scale == 0)) {
1259     bool quietly = CompilerOracle::should_exclude_quietly();
1260     if (PrintCompilation && !quietly) {
1261       // This does not happen quietly...
1262       ResourceMark rm;
1263       tty->print("### Excluding %s:%s",
1264                  method->is_native() ? "generation of native wrapper" : "compile",
1265                  (method->is_static() ? " static" : ""));
1266       method->print_short_name(tty);
1267       tty->cr();
1268     }
1269     method->set_not_compilable(comp_level, !quietly, "excluded by CompileCommand");
1270   }
1271 
1272   return false;
1273 }
1274 
1275 /**
1276  * Generate serialized IDs for compilation requests. If certain debugging flags are used
1277  * and the ID is not within the specified range, the method is not compiled and 0 is returned.
1278  * The function also allows to generate separate compilation IDs for OSR compilations.
1279  */
1280 int CompileBroker::assign_compile_id(const methodHandle& method, int osr_bci) {
1281 #ifdef ASSERT
1282   bool is_osr = (osr_bci != standard_entry_bci);
1283   int id;
1284   if (method->is_native()) {
1285     assert(!is_osr, "can't be osr");
1286     // Adapters, native wrappers and method handle intrinsics
1287     // should be generated always.
1288     return Atomic::add(1, &_compilation_id);
1289   } else if (CICountOSR && is_osr) {
1290     id = Atomic::add(1, &_osr_compilation_id);
1291     if (CIStartOSR <= id && id < CIStopOSR) {
1292       return id;
1293     }
1294   } else {
1295     id = Atomic::add(1, &_compilation_id);
1296     if (CIStart <= id && id < CIStop) {
1297       return id;
1298     }
1299   }
1300 
1301   // Method was not in the appropriate compilation range.
1302   method->set_not_compilable_quietly();
1303   return 0;
1304 #else
1305   // CICountOSR is a develop flag and set to 'false' by default. In a product built,
1306   // only _compilation_id is incremented.
1307   return Atomic::add(1, &_compilation_id);
1308 #endif
1309 }
1310 
1311 // ------------------------------------------------------------------
1312 // CompileBroker::assign_compile_id_unlocked
1313 //
1314 // Public wrapper for assign_compile_id that acquires the needed locks
1315 uint CompileBroker::assign_compile_id_unlocked(Thread* thread, const methodHandle& method, int osr_bci) {
1316   MutexLocker locker(MethodCompileQueue_lock, thread);
1317   return assign_compile_id(method, osr_bci);
1318 }
1319 
1320 // ------------------------------------------------------------------
1321 // CompileBroker::preload_classes
1322 void CompileBroker::preload_classes(const methodHandle& method, TRAPS) {
1323   // Move this code over from c1_Compiler.cpp
1324   ShouldNotReachHere();
1325 }
1326 
1327 
1328 // ------------------------------------------------------------------
1329 // CompileBroker::create_compile_task
1330 //
1331 // Create a CompileTask object representing the current request for
1332 // compilation.  Add this task to the queue.
1333 CompileTask* CompileBroker::create_compile_task(CompileQueue*       queue,
1334                                                 int                 compile_id,
1335                                                 const methodHandle& method,
1336                                                 int                 osr_bci,
1337                                                 int                 comp_level,
1338                                                 const methodHandle& hot_method,
1339                                                 int                 hot_count,
1340                                                 CompileTask::CompileReason compile_reason,
1341                                                 bool                blocking) {
1342   CompileTask* new_task = CompileTask::allocate();
1343   new_task->initialize(compile_id, method, osr_bci, comp_level,
1344                        hot_method, hot_count, compile_reason,
1345                        blocking);
1346   queue->add(new_task);
1347   return new_task;
1348 }
1349 
1350 #if INCLUDE_JVMCI
1351 // The number of milliseconds to wait before checking if
1352 // JVMCI compilation has made progress.
1353 static const long JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE = 1000;
1354 
1355 // The number of JVMCI compilation progress checks that must fail
1356 // before unblocking a thread waiting for a blocking compilation.
1357 static const int JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS = 10;
1358 
1359 /**
1360  * Waits for a JVMCI compiler to complete a given task. This thread
1361  * waits until either the task completes or it sees no JVMCI compilation
1362  * progress for N consecutive milliseconds where N is
1363  * JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE *
1364  * JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS.
1365  *
1366  * @return true if this thread needs to free/recycle the task
1367  */
1368 bool CompileBroker::wait_for_jvmci_completion(JVMCICompiler* jvmci, CompileTask* task, JavaThread* thread) {
1369   MutexLocker waiter(task->lock(), thread);
1370   int progress_wait_attempts = 0;
1371   int methods_compiled = jvmci->methods_compiled();
1372   while (!task->is_complete() && !is_compilation_disabled_forever() &&
1373          task->lock()->wait(!Mutex::_no_safepoint_check_flag, JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE)) {
1374     CompilerThread* jvmci_compiler_thread = task->jvmci_compiler_thread();
1375 
1376     bool progress;
1377     if (jvmci_compiler_thread != NULL) {
1378       // If the JVMCI compiler thread is not blocked, we deem it to be making progress.
1379       progress = jvmci_compiler_thread->thread_state() != _thread_blocked;
1380     } else {
1381       // Still waiting on JVMCI compiler queue. This thread may be holding a lock
1382       // that all JVMCI compiler threads are blocked on. We use the counter for
1383       // successful JVMCI compilations to determine whether JVMCI compilation
1384       // is still making progress through the JVMCI compiler queue.
1385       progress = jvmci->methods_compiled() != methods_compiled;
1386     }
1387 
1388     if (!progress) {
1389       if (++progress_wait_attempts == JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS) {
1390         if (PrintCompilation) {
1391           task->print(tty, "wait for blocking compilation timed out");
1392         }
1393         break;
1394       }
1395     } else {
1396       progress_wait_attempts = 0;
1397       if (jvmci_compiler_thread == NULL) {
1398         methods_compiled = jvmci->methods_compiled();
1399       }
1400     }
1401   }
1402   task->clear_waiter();
1403   return task->is_complete();
1404 }
1405 #endif
1406 
1407 /**
1408  *  Wait for the compilation task to complete.
1409  */
1410 void CompileBroker::wait_for_completion(CompileTask* task) {
1411   if (CIPrintCompileQueue) {
1412     ttyLocker ttyl;
1413     tty->print_cr("BLOCKING FOR COMPILE");
1414   }
1415 
1416   assert(task->is_blocking(), "can only wait on blocking task");
1417 
1418   JavaThread* thread = JavaThread::current();
1419   thread->set_blocked_on_compilation(true);
1420 
1421   methodHandle method(thread, task->method());
1422   bool free_task;
1423 #if INCLUDE_JVMCI
1424   AbstractCompiler* comp = compiler(task->comp_level());
1425   if (comp->is_jvmci()) {
1426     free_task = wait_for_jvmci_completion((JVMCICompiler*) comp, task, thread);
1427   } else
1428 #endif
1429   {
1430     MutexLocker waiter(task->lock(), thread);
1431     free_task = true;
1432     while (!task->is_complete() && !is_compilation_disabled_forever()) {
1433       task->lock()->wait();
1434     }
1435   }
1436 
1437   thread->set_blocked_on_compilation(false);
1438   if (free_task) {
1439     if (is_compilation_disabled_forever()) {
1440       CompileTask::free(task);
1441       return;
1442     }
1443 
1444     // It is harmless to check this status without the lock, because
1445     // completion is a stable property (until the task object is recycled).
1446     assert(task->is_complete(), "Compilation should have completed");
1447     assert(task->code_handle() == NULL, "must be reset");
1448 
1449     // By convention, the waiter is responsible for recycling a
1450     // blocking CompileTask. Since there is only one waiter ever
1451     // waiting on a CompileTask, we know that no one else will
1452     // be using this CompileTask; we can free it.
1453     CompileTask::free(task);
1454   }
1455 }
1456 
1457 /**
1458  * Initialize compiler thread(s) + compiler object(s). The postcondition
1459  * of this function is that the compiler runtimes are initialized and that
1460  * compiler threads can start compiling.
1461  */
1462 bool CompileBroker::init_compiler_runtime() {
1463   CompilerThread* thread = CompilerThread::current();
1464   AbstractCompiler* comp = thread->compiler();
1465   // Final sanity check - the compiler object must exist
1466   guarantee(comp != NULL, "Compiler object must exist");
1467 
1468   int system_dictionary_modification_counter;
1469   {
1470     MutexLocker locker(Compile_lock, thread);
1471     system_dictionary_modification_counter = SystemDictionary::number_of_modifications();
1472   }
1473 
1474   {
1475     // Must switch to native to allocate ci_env
1476     ThreadToNativeFromVM ttn(thread);
1477     ciEnv ci_env(NULL, system_dictionary_modification_counter);
1478     // Cache Jvmti state
1479     ci_env.cache_jvmti_state();
1480     // Cache DTrace flags
1481     ci_env.cache_dtrace_flags();
1482 
1483     // Switch back to VM state to do compiler initialization
1484     ThreadInVMfromNative tv(thread);
1485     ResetNoHandleMark rnhm;
1486 
1487     // Perform per-thread and global initializations
1488     comp->initialize();
1489   }
1490 
1491   if (comp->is_failed()) {
1492     disable_compilation_forever();
1493     // If compiler initialization failed, no compiler thread that is specific to a
1494     // particular compiler runtime will ever start to compile methods.
1495     shutdown_compiler_runtime(comp, thread);
1496     return false;
1497   }
1498 
1499   // C1 specific check
1500   if (comp->is_c1() && (thread->get_buffer_blob() == NULL)) {
1501     warning("Initialization of %s thread failed (no space to run compilers)", thread->name());
1502     return false;
1503   }
1504 
1505   return true;
1506 }
1507 
1508 /**
1509  * If C1 and/or C2 initialization failed, we shut down all compilation.
1510  * We do this to keep things simple. This can be changed if it ever turns
1511  * out to be a problem.
1512  */
1513 void CompileBroker::shutdown_compiler_runtime(AbstractCompiler* comp, CompilerThread* thread) {
1514   // Free buffer blob, if allocated
1515   if (thread->get_buffer_blob() != NULL) {
1516     MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1517     CodeCache::free(thread->get_buffer_blob());
1518   }
1519 
1520   if (comp->should_perform_shutdown()) {
1521     // There are two reasons for shutting down the compiler
1522     // 1) compiler runtime initialization failed
1523     // 2) The code cache is full and the following flag is set: -XX:-UseCodeCacheFlushing
1524     warning("%s initialization failed. Shutting down all compilers", comp->name());
1525 
1526     // Only one thread per compiler runtime object enters here
1527     // Set state to shut down
1528     comp->set_shut_down();
1529 
1530     // Delete all queued compilation tasks to make compiler threads exit faster.
1531     if (_c1_compile_queue != NULL) {
1532       _c1_compile_queue->free_all();
1533     }
1534 
1535     if (_c2_compile_queue != NULL) {
1536       _c2_compile_queue->free_all();
1537     }
1538 
1539     // Set flags so that we continue execution with using interpreter only.
1540     UseCompiler    = false;
1541     UseInterpreter = true;
1542 
1543     // We could delete compiler runtimes also. However, there are references to
1544     // the compiler runtime(s) (e.g.,  nmethod::is_compiled_by_c1()) which then
1545     // fail. This can be done later if necessary.
1546   }
1547 }
1548 
1549 // ------------------------------------------------------------------
1550 // CompileBroker::compiler_thread_loop
1551 //
1552 // The main loop run by a CompilerThread.
1553 void CompileBroker::compiler_thread_loop() {
1554   CompilerThread* thread = CompilerThread::current();
1555   CompileQueue* queue = thread->queue();
1556   // For the thread that initializes the ciObjectFactory
1557   // this resource mark holds all the shared objects
1558   ResourceMark rm;
1559 
1560   // First thread to get here will initialize the compiler interface
1561 
1562   {
1563     ASSERT_IN_VM;
1564     MutexLocker only_one (CompileThread_lock, thread);
1565     if (!ciObjectFactory::is_initialized()) {
1566       ciObjectFactory::initialize();
1567     }
1568   }
1569 
1570   // Open a log.
1571   if (LogCompilation) {
1572     init_compiler_thread_log();
1573   }
1574   CompileLog* log = thread->log();
1575   if (log != NULL) {
1576     log->begin_elem("start_compile_thread name='%s' thread='" UINTX_FORMAT "' process='%d'",
1577                     thread->name(),
1578                     os::current_thread_id(),
1579                     os::current_process_id());
1580     log->stamp();
1581     log->end_elem();
1582   }
1583 
1584   // If compiler thread/runtime initialization fails, exit the compiler thread
1585   if (!init_compiler_runtime()) {
1586     return;
1587   }
1588 
1589   // Poll for new compilation tasks as long as the JVM runs. Compilation
1590   // should only be disabled if something went wrong while initializing the
1591   // compiler runtimes. This, in turn, should not happen. The only known case
1592   // when compiler runtime initialization fails is if there is not enough free
1593   // space in the code cache to generate the necessary stubs, etc.
1594   while (!is_compilation_disabled_forever()) {
1595     // We need this HandleMark to avoid leaking VM handles.
1596     HandleMark hm(thread);
1597 
1598     CompileTask* task = queue->get();
1599     if (task == NULL) {
1600       continue;
1601     }
1602 
1603     // Give compiler threads an extra quanta.  They tend to be bursty and
1604     // this helps the compiler to finish up the job.
1605     if (CompilerThreadHintNoPreempt) {
1606       os::hint_no_preempt();
1607     }
1608 
1609     // Assign the task to the current thread.  Mark this compilation
1610     // thread as active for the profiler.
1611     CompileTaskWrapper ctw(task);
1612     nmethodLocker result_handle;  // (handle for the nmethod produced by this task)
1613     task->set_code_handle(&result_handle);
1614     methodHandle method(thread, task->method());
1615 
1616     // Never compile a method if breakpoints are present in it
1617     if (method()->number_of_breakpoints() == 0) {
1618       // Compile the method.
1619       if ((UseCompiler || AlwaysCompileLoopMethods) && CompileBroker::should_compile_new_jobs()) {
1620         invoke_compiler_on_method(task);
1621       } else {
1622         // After compilation is disabled, remove remaining methods from queue
1623         method->clear_queued_for_compilation();
1624         task->set_failure_reason("compilation is disabled");
1625       }
1626     }
1627   }
1628 
1629   // Shut down compiler runtime
1630   shutdown_compiler_runtime(thread->compiler(), thread);
1631 }
1632 
1633 // ------------------------------------------------------------------
1634 // CompileBroker::init_compiler_thread_log
1635 //
1636 // Set up state required by +LogCompilation.
1637 void CompileBroker::init_compiler_thread_log() {
1638     CompilerThread* thread = CompilerThread::current();
1639     char  file_name[4*K];
1640     FILE* fp = NULL;
1641     intx thread_id = os::current_thread_id();
1642     for (int try_temp_dir = 1; try_temp_dir >= 0; try_temp_dir--) {
1643       const char* dir = (try_temp_dir ? os::get_temp_directory() : NULL);
1644       if (dir == NULL) {
1645         jio_snprintf(file_name, sizeof(file_name), "hs_c" UINTX_FORMAT "_pid%u.log",
1646                      thread_id, os::current_process_id());
1647       } else {
1648         jio_snprintf(file_name, sizeof(file_name),
1649                      "%s%shs_c" UINTX_FORMAT "_pid%u.log", dir,
1650                      os::file_separator(), thread_id, os::current_process_id());
1651       }
1652 
1653       fp = fopen(file_name, "wt");
1654       if (fp != NULL) {
1655         if (LogCompilation && Verbose) {
1656           tty->print_cr("Opening compilation log %s", file_name);
1657         }
1658         CompileLog* log = new(ResourceObj::C_HEAP, mtCompiler) CompileLog(file_name, fp, thread_id);
1659         if (log == NULL) {
1660           fclose(fp);
1661           return;
1662         }
1663         thread->init_log(log);
1664 
1665         if (xtty != NULL) {
1666           ttyLocker ttyl;
1667           // Record any per thread log files
1668           xtty->elem("thread_logfile thread='" INTX_FORMAT "' filename='%s'", thread_id, file_name);
1669         }
1670         return;
1671       }
1672     }
1673     warning("Cannot open log file: %s", file_name);
1674 }
1675 
1676 void CompileBroker::log_metaspace_failure() {
1677   const char* message = "some methods may not be compiled because metaspace "
1678                         "is out of memory";
1679   if (_compilation_log != NULL) {
1680     _compilation_log->log_metaspace_failure(message);
1681   }
1682   if (PrintCompilation) {
1683     tty->print_cr("COMPILE PROFILING SKIPPED: %s", message);
1684   }
1685 }
1686 
1687 
1688 // ------------------------------------------------------------------
1689 // CompileBroker::set_should_block
1690 //
1691 // Set _should_block.
1692 // Call this from the VM, with Threads_lock held and a safepoint requested.
1693 void CompileBroker::set_should_block() {
1694   assert(Threads_lock->owner() == Thread::current(), "must have threads lock");
1695   assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint already");
1696 #ifndef PRODUCT
1697   if (PrintCompilation && (Verbose || WizardMode))
1698     tty->print_cr("notifying compiler thread pool to block");
1699 #endif
1700   _should_block = true;
1701 }
1702 
1703 // ------------------------------------------------------------------
1704 // CompileBroker::maybe_block
1705 //
1706 // Call this from the compiler at convenient points, to poll for _should_block.
1707 void CompileBroker::maybe_block() {
1708   if (_should_block) {
1709 #ifndef PRODUCT
1710     if (PrintCompilation && (Verbose || WizardMode))
1711       tty->print_cr("compiler thread " INTPTR_FORMAT " poll detects block request", p2i(Thread::current()));
1712 #endif
1713     ThreadInVMfromNative tivfn(JavaThread::current());
1714   }
1715 }
1716 
1717 // wrapper for CodeCache::print_summary()
1718 static void codecache_print(bool detailed)
1719 {
1720   ResourceMark rm;
1721   stringStream s;
1722   // Dump code cache  into a buffer before locking the tty,
1723   {
1724     MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1725     CodeCache::print_summary(&s, detailed);
1726   }
1727   ttyLocker ttyl;
1728   tty->print("%s", s.as_string());
1729 }
1730 
1731 // wrapper for CodeCache::print_summary() using outputStream
1732 static void codecache_print(outputStream* out, bool detailed) {
1733   ResourceMark rm;
1734   stringStream s;
1735 
1736   // Dump code cache into a buffer
1737   {
1738     MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1739     CodeCache::print_summary(&s, detailed);
1740   }
1741 
1742   char* remaining_log = s.as_string();
1743   while (*remaining_log != '\0') {
1744     char* eol = strchr(remaining_log, '\n');
1745     if (eol == NULL) {
1746       out->print_cr("%s", remaining_log);
1747       remaining_log = remaining_log + strlen(remaining_log);
1748     } else {
1749       *eol = '\0';
1750       out->print_cr("%s", remaining_log);
1751       remaining_log = eol + 1;
1752     }
1753   }
1754 }
1755 
1756 void CompileBroker::post_compile(CompilerThread* thread, CompileTask* task, EventCompilation& event, bool success, ciEnv* ci_env) {
1757 
1758   if (success) {
1759     task->mark_success();
1760     if (ci_env != NULL) {
1761       task->set_num_inlined_bytecodes(ci_env->num_inlined_bytecodes());
1762     }
1763     if (_compilation_log != NULL) {
1764       nmethod* code = task->code();
1765       if (code != NULL) {
1766         _compilation_log->log_nmethod(thread, code);
1767       }
1768     }
1769   }
1770 
1771   // simulate crash during compilation
1772   assert(task->compile_id() != CICrashAt, "just as planned");
1773   if (event.should_commit()) {
1774     event.set_method(task->method());
1775     event.set_compileId(task->compile_id());
1776     event.set_compileLevel(task->comp_level());
1777     event.set_succeded(task->is_success());
1778     event.set_isOsr(task->osr_bci() != CompileBroker::standard_entry_bci);
1779     event.set_codeSize((task->code() == NULL) ? 0 : task->code()->total_size());
1780     event.set_inlinedBytes(task->num_inlined_bytecodes());
1781     event.commit();
1782   }
1783 }
1784 
1785 int DirectivesStack::_depth = 0;
1786 CompilerDirectives* DirectivesStack::_top = NULL;
1787 CompilerDirectives* DirectivesStack::_bottom = NULL;
1788 
1789 // ------------------------------------------------------------------
1790 // CompileBroker::invoke_compiler_on_method
1791 //
1792 // Compile a method.
1793 //
1794 void CompileBroker::invoke_compiler_on_method(CompileTask* task) {
1795   task->print_ul();
1796   if (PrintCompilation) {
1797     ResourceMark rm;
1798     task->print_tty();
1799   }
1800   elapsedTimer time;
1801 
1802   CompilerThread* thread = CompilerThread::current();
1803   ResourceMark rm(thread);
1804 
1805   if (LogEvents) {
1806     _compilation_log->log_compile(thread, task);
1807   }
1808 
1809   // Common flags.
1810   uint compile_id = task->compile_id();
1811   int osr_bci = task->osr_bci();
1812   bool is_osr = (osr_bci != standard_entry_bci);
1813   bool should_log = (thread->log() != NULL);
1814   bool should_break = false;
1815   const int task_level = task->comp_level();
1816   AbstractCompiler* comp = task->compiler();
1817 
1818   DirectiveSet* directive;
1819   {
1820     // create the handle inside it's own block so it can't
1821     // accidentally be referenced once the thread transitions to
1822     // native.  The NoHandleMark before the transition should catch
1823     // any cases where this occurs in the future.
1824     methodHandle method(thread, task->method());
1825     assert(!method->is_native(), "no longer compile natives");
1826 
1827     // Look up matching directives
1828     directive = DirectivesStack::getMatchingDirective(method, comp);
1829 
1830     // Save information about this method in case of failure.
1831     set_last_compile(thread, method, is_osr, task_level);
1832 
1833     DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, compiler_name(task_level));
1834   }
1835 
1836   should_break = directive->BreakAtExecuteOption || task->check_break_at_flags();
1837   if (should_log && !directive->LogOption) {
1838     should_log = false;
1839   }
1840 
1841   // Allocate a new set of JNI handles.
1842   push_jni_handle_block();
1843   Method* target_handle = task->method();
1844   int compilable = ciEnv::MethodCompilable;
1845   const char* failure_reason = NULL;
1846   const char* retry_message = NULL;
1847 
1848   int system_dictionary_modification_counter;
1849   {
1850     MutexLocker locker(Compile_lock, thread);
1851     system_dictionary_modification_counter = SystemDictionary::number_of_modifications();
1852   }
1853 
1854 #if INCLUDE_JVMCI
1855   if (UseJVMCICompiler && comp != NULL && comp->is_jvmci()) {
1856     JVMCICompiler* jvmci = (JVMCICompiler*) comp;
1857 
1858     TraceTime t1("compilation", &time);
1859     EventCompilation event;
1860 
1861     // Skip redefined methods
1862     if (target_handle->is_old()) {
1863         failure_reason = "redefined method";
1864         retry_message = "not retryable";
1865         compilable = ciEnv::MethodCompilable_never;
1866     } else {
1867         JVMCIEnv env(task, system_dictionary_modification_counter);
1868         methodHandle method(thread, target_handle);
1869         jvmci->compile_method(method, osr_bci, &env);
1870 
1871         failure_reason = env.failure_reason();
1872         if (!env.retryable()) {
1873           retry_message = "not retryable";
1874           compilable = ciEnv::MethodCompilable_not_at_tier;
1875         }
1876     }
1877     post_compile(thread, task, event, task->code() != NULL, NULL);
1878 
1879   } else
1880 #endif // INCLUDE_JVMCI
1881   {
1882     NoHandleMark  nhm;
1883     ThreadToNativeFromVM ttn(thread);
1884 
1885     ciEnv ci_env(task, system_dictionary_modification_counter);
1886     if (should_break) {
1887       ci_env.set_break_at_compile(true);
1888     }
1889     if (should_log) {
1890       ci_env.set_log(thread->log());
1891     }
1892     assert(thread->env() == &ci_env, "set by ci_env");
1893     // The thread-env() field is cleared in ~CompileTaskWrapper.
1894 
1895     // Cache Jvmti state
1896     ci_env.cache_jvmti_state();
1897 
1898     // Cache DTrace flags
1899     ci_env.cache_dtrace_flags();
1900 
1901     ciMethod* target = ci_env.get_method_from_handle(target_handle);
1902 
1903     TraceTime t1("compilation", &time);
1904     EventCompilation event;
1905 
1906     if (comp == NULL) {
1907       ci_env.record_method_not_compilable("no compiler", !TieredCompilation);
1908     } else {
1909       if (WhiteBoxAPI && WhiteBox::compilation_locked) {
1910         MonitorLockerEx locker(Compilation_lock, Mutex::_no_safepoint_check_flag);
1911         while (WhiteBox::compilation_locked) {
1912           locker.wait(Mutex::_no_safepoint_check_flag);
1913         }
1914       }
1915       comp->compile_method(&ci_env, target, osr_bci, directive);
1916     }
1917 
1918     if (!ci_env.failing() && task->code() == NULL) {
1919       //assert(false, "compiler should always document failure");
1920       // The compiler elected, without comment, not to register a result.
1921       // Do not attempt further compilations of this method.
1922       ci_env.record_method_not_compilable("compile failed", !TieredCompilation);
1923     }
1924 
1925     // Copy this bit to the enclosing block:
1926     compilable = ci_env.compilable();
1927 
1928     if (ci_env.failing()) {
1929       failure_reason = ci_env.failure_reason();
1930       retry_message = ci_env.retry_message();
1931       ci_env.report_failure(failure_reason);
1932     }
1933 
1934     post_compile(thread, task, event, !ci_env.failing(), &ci_env);
1935   }
1936   // Remove the JNI handle block after the ciEnv destructor has run in
1937   // the previous block.
1938   pop_jni_handle_block();
1939 
1940   if (failure_reason != NULL) {
1941     task->set_failure_reason(failure_reason);
1942     if (_compilation_log != NULL) {
1943       _compilation_log->log_failure(thread, task, failure_reason, retry_message);
1944     }
1945     if (PrintCompilation) {
1946       FormatBufferResource msg = retry_message != NULL ?
1947         FormatBufferResource("COMPILE SKIPPED: %s (%s)", failure_reason, retry_message) :
1948         FormatBufferResource("COMPILE SKIPPED: %s",      failure_reason);
1949       task->print(tty, msg);
1950     }
1951   }
1952 
1953   methodHandle method(thread, task->method());
1954 
1955   DTRACE_METHOD_COMPILE_END_PROBE(method, compiler_name(task_level), task->is_success());
1956 
1957   collect_statistics(thread, time, task);
1958 
1959   nmethod* nm = task->code();
1960   if (nm != NULL) {
1961     nm->maybe_print_nmethod(directive);
1962   }
1963   DirectivesStack::release(directive);
1964 
1965   if (PrintCompilation && PrintCompilation2) {
1966     tty->print("%7d ", (int) tty->time_stamp().milliseconds());  // print timestamp
1967     tty->print("%4d ", compile_id);    // print compilation number
1968     tty->print("%s ", (is_osr ? "%" : " "));
1969     if (task->code() != NULL) {
1970       tty->print("size: %d(%d) ", task->code()->total_size(), task->code()->insts_size());
1971     }
1972     tty->print_cr("time: %d inlined: %d bytes", (int)time.milliseconds(), task->num_inlined_bytecodes());
1973   }
1974 
1975   Log(compilation, codecache) log;
1976   if (log.is_debug()) {
1977     LogStream ls(log.debug());
1978     codecache_print(&ls, /* detailed= */ false);
1979   }
1980   if (PrintCodeCacheOnCompilation) {
1981     codecache_print(/* detailed= */ false);
1982   }
1983   // Disable compilation, if required.
1984   switch (compilable) {
1985   case ciEnv::MethodCompilable_never:
1986     if (is_osr)
1987       method->set_not_osr_compilable_quietly();
1988     else
1989       method->set_not_compilable_quietly();
1990     break;
1991   case ciEnv::MethodCompilable_not_at_tier:
1992     if (is_osr)
1993       method->set_not_osr_compilable_quietly(task_level);
1994     else
1995       method->set_not_compilable_quietly(task_level);
1996     break;
1997   }
1998 
1999   // Note that the queued_for_compilation bits are cleared without
2000   // protection of a mutex. [They were set by the requester thread,
2001   // when adding the task to the compile queue -- at which time the
2002   // compile queue lock was held. Subsequently, we acquired the compile
2003   // queue lock to get this task off the compile queue; thus (to belabour
2004   // the point somewhat) our clearing of the bits must be occurring
2005   // only after the setting of the bits. See also 14012000 above.
2006   method->clear_queued_for_compilation();
2007 
2008 #ifdef ASSERT
2009   if (CollectedHeap::fired_fake_oom()) {
2010     // The current compile received a fake OOM during compilation so
2011     // go ahead and exit the VM since the test apparently succeeded
2012     tty->print_cr("*** Shutting down VM after successful fake OOM");
2013     vm_exit(0);
2014   }
2015 #endif
2016 }
2017 
2018 /**
2019  * The CodeCache is full. Print warning and disable compilation.
2020  * Schedule code cache cleaning so compilation can continue later.
2021  * This function needs to be called only from CodeCache::allocate(),
2022  * since we currently handle a full code cache uniformly.
2023  */
2024 void CompileBroker::handle_full_code_cache(int code_blob_type) {
2025   UseInterpreter = true;
2026   if (UseCompiler || AlwaysCompileLoopMethods ) {
2027     if (xtty != NULL) {
2028       ResourceMark rm;
2029       stringStream s;
2030       // Dump code cache state into a buffer before locking the tty,
2031       // because log_state() will use locks causing lock conflicts.
2032       CodeCache::log_state(&s);
2033       // Lock to prevent tearing
2034       ttyLocker ttyl;
2035       xtty->begin_elem("code_cache_full");
2036       xtty->print("%s", s.as_string());
2037       xtty->stamp();
2038       xtty->end_elem();
2039     }
2040 
2041 #ifndef PRODUCT
2042     if (CompileTheWorld || ExitOnFullCodeCache) {
2043       codecache_print(/* detailed= */ true);
2044       before_exit(JavaThread::current());
2045       exit_globals(); // will delete tty
2046       vm_direct_exit(CompileTheWorld ? 0 : 1);
2047     }
2048 #endif
2049     if (UseCodeCacheFlushing) {
2050       // Since code cache is full, immediately stop new compiles
2051       if (CompileBroker::set_should_compile_new_jobs(CompileBroker::stop_compilation)) {
2052         NMethodSweeper::log_sweep("disable_compiler");
2053       }
2054     } else {
2055       disable_compilation_forever();
2056     }
2057 
2058     CodeCache::report_codemem_full(code_blob_type, should_print_compiler_warning());
2059   }
2060 }
2061 
2062 // ------------------------------------------------------------------
2063 // CompileBroker::set_last_compile
2064 //
2065 // Record this compilation for debugging purposes.
2066 void CompileBroker::set_last_compile(CompilerThread* thread, const methodHandle& method, bool is_osr, int comp_level) {
2067   ResourceMark rm;
2068   char* method_name = method->name()->as_C_string();
2069   strncpy(_last_method_compiled, method_name, CompileBroker::name_buffer_length);
2070   _last_method_compiled[CompileBroker::name_buffer_length - 1] = '\0'; // ensure null terminated
2071   char current_method[CompilerCounters::cmname_buffer_length];
2072   size_t maxLen = CompilerCounters::cmname_buffer_length;
2073 
2074   if (UsePerfData) {
2075     const char* class_name = method->method_holder()->name()->as_C_string();
2076 
2077     size_t s1len = strlen(class_name);
2078     size_t s2len = strlen(method_name);
2079 
2080     // check if we need to truncate the string
2081     if (s1len + s2len + 2 > maxLen) {
2082 
2083       // the strategy is to lop off the leading characters of the
2084       // class name and the trailing characters of the method name.
2085 
2086       if (s2len + 2 > maxLen) {
2087         // lop of the entire class name string, let snprintf handle
2088         // truncation of the method name.
2089         class_name += s1len; // null string
2090       }
2091       else {
2092         // lop off the extra characters from the front of the class name
2093         class_name += ((s1len + s2len + 2) - maxLen);
2094       }
2095     }
2096 
2097     jio_snprintf(current_method, maxLen, "%s %s", class_name, method_name);
2098   }
2099 
2100   if (CICountOSR && is_osr) {
2101     _last_compile_type = osr_compile;
2102   } else {
2103     _last_compile_type = normal_compile;
2104   }
2105   _last_compile_level = comp_level;
2106 
2107   if (UsePerfData) {
2108     CompilerCounters* counters = thread->counters();
2109     counters->set_current_method(current_method);
2110     counters->set_compile_type((jlong)_last_compile_type);
2111   }
2112 }
2113 
2114 
2115 // ------------------------------------------------------------------
2116 // CompileBroker::push_jni_handle_block
2117 //
2118 // Push on a new block of JNI handles.
2119 void CompileBroker::push_jni_handle_block() {
2120   JavaThread* thread = JavaThread::current();
2121 
2122   // Allocate a new block for JNI handles.
2123   // Inlined code from jni_PushLocalFrame()
2124   JNIHandleBlock* java_handles = thread->active_handles();
2125   JNIHandleBlock* compile_handles = JNIHandleBlock::allocate_block(thread);
2126   assert(compile_handles != NULL && java_handles != NULL, "should not be NULL");
2127   compile_handles->set_pop_frame_link(java_handles);  // make sure java handles get gc'd.
2128   thread->set_active_handles(compile_handles);
2129 }
2130 
2131 
2132 // ------------------------------------------------------------------
2133 // CompileBroker::pop_jni_handle_block
2134 //
2135 // Pop off the current block of JNI handles.
2136 void CompileBroker::pop_jni_handle_block() {
2137   JavaThread* thread = JavaThread::current();
2138 
2139   // Release our JNI handle block
2140   JNIHandleBlock* compile_handles = thread->active_handles();
2141   JNIHandleBlock* java_handles = compile_handles->pop_frame_link();
2142   thread->set_active_handles(java_handles);
2143   compile_handles->set_pop_frame_link(NULL);
2144   JNIHandleBlock::release_block(compile_handles, thread); // may block
2145 }
2146 
2147 // ------------------------------------------------------------------
2148 // CompileBroker::collect_statistics
2149 //
2150 // Collect statistics about the compilation.
2151 
2152 void CompileBroker::collect_statistics(CompilerThread* thread, elapsedTimer time, CompileTask* task) {
2153   bool success = task->is_success();
2154   methodHandle method (thread, task->method());
2155   uint compile_id = task->compile_id();
2156   bool is_osr = (task->osr_bci() != standard_entry_bci);
2157   nmethod* code = task->code();
2158   CompilerCounters* counters = thread->counters();
2159 
2160   assert(code == NULL || code->is_locked_by_vm(), "will survive the MutexLocker");
2161   MutexLocker locker(CompileStatistics_lock);
2162 
2163   // _perf variables are production performance counters which are
2164   // updated regardless of the setting of the CITime and CITimeEach flags
2165   //
2166 
2167   // account all time, including bailouts and failures in this counter;
2168   // C1 and C2 counters are counting both successful and unsuccessful compiles
2169   _t_total_compilation.add(time);
2170 
2171   if (!success) {
2172     _total_bailout_count++;
2173     if (UsePerfData) {
2174       _perf_last_failed_method->set_value(counters->current_method());
2175       _perf_last_failed_type->set_value(counters->compile_type());
2176       _perf_total_bailout_count->inc();
2177     }
2178     _t_bailedout_compilation.add(time);
2179   } else if (code == NULL) {
2180     if (UsePerfData) {
2181       _perf_last_invalidated_method->set_value(counters->current_method());
2182       _perf_last_invalidated_type->set_value(counters->compile_type());
2183       _perf_total_invalidated_count->inc();
2184     }
2185     _total_invalidated_count++;
2186     _t_invalidated_compilation.add(time);
2187   } else {
2188     // Compilation succeeded
2189 
2190     // update compilation ticks - used by the implementation of
2191     // java.lang.management.CompilationMBean
2192     _perf_total_compilation->inc(time.ticks());
2193     _peak_compilation_time = time.milliseconds() > _peak_compilation_time ? time.milliseconds() : _peak_compilation_time;
2194 
2195     if (CITime) {
2196       int bytes_compiled = method->code_size() + task->num_inlined_bytecodes();
2197       if (is_osr) {
2198         _t_osr_compilation.add(time);
2199         _sum_osr_bytes_compiled += bytes_compiled;
2200       } else {
2201         _t_standard_compilation.add(time);
2202         _sum_standard_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();
2203       }
2204 
2205 #if INCLUDE_JVMCI
2206       AbstractCompiler* comp = compiler(task->comp_level());
2207       if (comp) {
2208         CompilerStatistics* stats = comp->stats();
2209         if (stats) {
2210           if (is_osr) {
2211             stats->_osr.update(time, bytes_compiled);
2212           } else {
2213             stats->_standard.update(time, bytes_compiled);
2214           }
2215           stats->_nmethods_size += code->total_size();
2216           stats->_nmethods_code_size += code->insts_size();
2217         } else { // if (!stats)
2218           assert(false, "Compiler statistics object must exist");
2219         }
2220       } else { // if (!comp)
2221         assert(false, "Compiler object must exist");
2222       }
2223 #endif // INCLUDE_JVMCI
2224     }
2225 
2226     if (UsePerfData) {
2227       // save the name of the last method compiled
2228       _perf_last_method->set_value(counters->current_method());
2229       _perf_last_compile_type->set_value(counters->compile_type());
2230       _perf_last_compile_size->set_value(method->code_size() +
2231                                          task->num_inlined_bytecodes());
2232       if (is_osr) {
2233         _perf_osr_compilation->inc(time.ticks());
2234         _perf_sum_osr_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2235       } else {
2236         _perf_standard_compilation->inc(time.ticks());
2237         _perf_sum_standard_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2238       }
2239     }
2240 
2241     if (CITimeEach) {
2242       float bytes_per_sec = 1.0 * (method->code_size() + task->num_inlined_bytecodes()) / time.seconds();
2243       tty->print_cr("%3d   seconds: %f bytes/sec : %f (bytes %d + %d inlined)",
2244                     compile_id, time.seconds(), bytes_per_sec, method->code_size(), task->num_inlined_bytecodes());
2245     }
2246 
2247     // Collect counts of successful compilations
2248     _sum_nmethod_size      += code->total_size();
2249     _sum_nmethod_code_size += code->insts_size();
2250     _total_compile_count++;
2251 
2252     if (UsePerfData) {
2253       _perf_sum_nmethod_size->inc(     code->total_size());
2254       _perf_sum_nmethod_code_size->inc(code->insts_size());
2255       _perf_total_compile_count->inc();
2256     }
2257 
2258     if (is_osr) {
2259       if (UsePerfData) _perf_total_osr_compile_count->inc();
2260       _total_osr_compile_count++;
2261     } else {
2262       if (UsePerfData) _perf_total_standard_compile_count->inc();
2263       _total_standard_compile_count++;
2264     }
2265   }
2266   // set the current method for the thread to null
2267   if (UsePerfData) counters->set_current_method("");
2268 }
2269 
2270 const char* CompileBroker::compiler_name(int comp_level) {
2271   AbstractCompiler *comp = CompileBroker::compiler(comp_level);
2272   if (comp == NULL) {
2273     return "no compiler";
2274   } else {
2275     return (comp->name());
2276   }
2277 }
2278 
2279 #if INCLUDE_JVMCI
2280 void CompileBroker::print_times(AbstractCompiler* comp) {
2281   CompilerStatistics* stats = comp->stats();
2282   if (stats) {
2283     tty->print_cr("  %s {speed: %d bytes/s; standard: %6.3f s, %d bytes, %d methods; osr: %6.3f s, %d bytes, %d methods; nmethods_size: %d bytes; nmethods_code_size: %d bytes}",
2284                 comp->name(), stats->bytes_per_second(),
2285                 stats->_standard._time.seconds(), stats->_standard._bytes, stats->_standard._count,
2286                 stats->_osr._time.seconds(), stats->_osr._bytes, stats->_osr._count,
2287                 stats->_nmethods_size, stats->_nmethods_code_size);
2288   } else { // if (!stats)
2289     assert(false, "Compiler statistics object must exist");
2290   }
2291   comp->print_timers();
2292 }
2293 #endif // INCLUDE_JVMCI
2294 
2295 void CompileBroker::print_times(bool per_compiler, bool aggregate) {
2296 #if INCLUDE_JVMCI
2297   elapsedTimer standard_compilation;
2298   elapsedTimer total_compilation;
2299   elapsedTimer osr_compilation;
2300 
2301   int standard_bytes_compiled = 0;
2302   int osr_bytes_compiled = 0;
2303 
2304   int standard_compile_count = 0;
2305   int osr_compile_count = 0;
2306   int total_compile_count = 0;
2307 
2308   int nmethods_size = 0;
2309   int nmethods_code_size = 0;
2310   bool printedHeader = false;
2311 
2312   for (unsigned int i = 0; i < sizeof(_compilers) / sizeof(AbstractCompiler*); i++) {
2313     AbstractCompiler* comp = _compilers[i];
2314     if (comp != NULL) {
2315       if (per_compiler && aggregate && !printedHeader) {
2316         printedHeader = true;
2317         tty->cr();
2318         tty->print_cr("Individual compiler times (for compiled methods only)");
2319         tty->print_cr("------------------------------------------------");
2320         tty->cr();
2321       }
2322       CompilerStatistics* stats = comp->stats();
2323 
2324       if (stats) {
2325         standard_compilation.add(stats->_standard._time);
2326         osr_compilation.add(stats->_osr._time);
2327 
2328         standard_bytes_compiled += stats->_standard._bytes;
2329         osr_bytes_compiled += stats->_osr._bytes;
2330 
2331         standard_compile_count += stats->_standard._count;
2332         osr_compile_count += stats->_osr._count;
2333 
2334         nmethods_size += stats->_nmethods_size;
2335         nmethods_code_size += stats->_nmethods_code_size;
2336       } else { // if (!stats)
2337         assert(false, "Compiler statistics object must exist");
2338       }
2339 
2340       if (per_compiler) {
2341         print_times(comp);
2342       }
2343     }
2344   }
2345   total_compile_count = osr_compile_count + standard_compile_count;
2346   total_compilation.add(osr_compilation);
2347   total_compilation.add(standard_compilation);
2348 
2349   // In hosted mode, print the JVMCI compiler specific counters manually.
2350   if (!UseJVMCICompiler) {
2351     JVMCICompiler::print_compilation_timers();
2352   }
2353 #else // INCLUDE_JVMCI
2354   elapsedTimer standard_compilation = CompileBroker::_t_standard_compilation;
2355   elapsedTimer osr_compilation = CompileBroker::_t_osr_compilation;
2356   elapsedTimer total_compilation = CompileBroker::_t_total_compilation;
2357 
2358   int standard_bytes_compiled = CompileBroker::_sum_standard_bytes_compiled;
2359   int osr_bytes_compiled = CompileBroker::_sum_osr_bytes_compiled;
2360 
2361   int standard_compile_count = CompileBroker::_total_standard_compile_count;
2362   int osr_compile_count = CompileBroker::_total_osr_compile_count;
2363   int total_compile_count = CompileBroker::_total_compile_count;
2364 
2365   int nmethods_size = CompileBroker::_sum_nmethod_code_size;
2366   int nmethods_code_size = CompileBroker::_sum_nmethod_size;
2367 #endif // INCLUDE_JVMCI
2368 
2369   if (!aggregate) {
2370     return;
2371   }
2372   tty->cr();
2373   tty->print_cr("Accumulated compiler times");
2374   tty->print_cr("----------------------------------------------------------");
2375                //0000000000111111111122222222223333333333444444444455555555556666666666
2376                //0123456789012345678901234567890123456789012345678901234567890123456789
2377   tty->print_cr("  Total compilation time   : %7.3f s", total_compilation.seconds());
2378   tty->print_cr("    Standard compilation   : %7.3f s, Average : %2.3f s",
2379                 standard_compilation.seconds(),
2380                 standard_compilation.seconds() / standard_compile_count);
2381   tty->print_cr("    Bailed out compilation : %7.3f s, Average : %2.3f s",
2382                 CompileBroker::_t_bailedout_compilation.seconds(),
2383                 CompileBroker::_t_bailedout_compilation.seconds() / CompileBroker::_total_bailout_count);
2384   tty->print_cr("    On stack replacement   : %7.3f s, Average : %2.3f s",
2385                 osr_compilation.seconds(),
2386                 osr_compilation.seconds() / osr_compile_count);
2387   tty->print_cr("    Invalidated            : %7.3f s, Average : %2.3f s",
2388                 CompileBroker::_t_invalidated_compilation.seconds(),
2389                 CompileBroker::_t_invalidated_compilation.seconds() / CompileBroker::_total_invalidated_count);
2390 
2391   AbstractCompiler *comp = compiler(CompLevel_simple);
2392   if (comp != NULL) {
2393     tty->cr();
2394     comp->print_timers();
2395   }
2396   comp = compiler(CompLevel_full_optimization);
2397   if (comp != NULL) {
2398     tty->cr();
2399     comp->print_timers();
2400   }
2401   tty->cr();
2402   tty->print_cr("  Total compiled methods    : %8d methods", total_compile_count);
2403   tty->print_cr("    Standard compilation    : %8d methods", standard_compile_count);
2404   tty->print_cr("    On stack replacement    : %8d methods", osr_compile_count);
2405   int tcb = osr_bytes_compiled + standard_bytes_compiled;
2406   tty->print_cr("  Total compiled bytecodes  : %8d bytes", tcb);
2407   tty->print_cr("    Standard compilation    : %8d bytes", standard_bytes_compiled);
2408   tty->print_cr("    On stack replacement    : %8d bytes", osr_bytes_compiled);
2409   double tcs = total_compilation.seconds();
2410   int bps = tcs == 0.0 ? 0 : (int)(tcb / tcs);
2411   tty->print_cr("  Average compilation speed : %8d bytes/s", bps);
2412   tty->cr();
2413   tty->print_cr("  nmethod code size         : %8d bytes", nmethods_code_size);
2414   tty->print_cr("  nmethod total size        : %8d bytes", nmethods_size);
2415 }
2416 
2417 // Debugging output for failure
2418 void CompileBroker::print_last_compile() {
2419   if (_last_compile_level != CompLevel_none &&
2420       compiler(_last_compile_level) != NULL &&
2421       _last_compile_type != no_compile) {
2422     if (_last_compile_type == osr_compile) {
2423       tty->print_cr("Last parse:  [osr]%d+++(%d) %s",
2424                     _osr_compilation_id, _last_compile_level, _last_method_compiled);
2425     } else {
2426       tty->print_cr("Last parse:  %d+++(%d) %s",
2427                     _compilation_id, _last_compile_level, _last_method_compiled);
2428     }
2429   }
2430 }
2431 
2432 // Print general/accumulated JIT information.
2433 void CompileBroker::print_info(outputStream *out) {
2434   if (out == NULL) out = tty;
2435   out->cr();
2436   out->print_cr("======================");
2437   out->print_cr("   General JIT info   ");
2438   out->print_cr("======================");
2439   out->cr();
2440   out->print_cr("            JIT is : %7s",     should_compile_new_jobs() ? "on" : "off");
2441   out->print_cr("  Compiler threads : %7d",     (int)CICompilerCount);
2442   out->cr();
2443   out->print_cr("CodeCache overview");
2444   out->print_cr("--------------------------------------------------------");
2445   out->cr();
2446   out->print_cr("         Reserved size : " SIZE_FORMAT_W(7) " KB", CodeCache::max_capacity() / K);
2447   out->print_cr("        Committed size : " SIZE_FORMAT_W(7) " KB", CodeCache::capacity() / K);
2448   out->print_cr("  Unallocated capacity : " SIZE_FORMAT_W(7) " KB", CodeCache::unallocated_capacity() / K);
2449   out->cr();
2450 
2451   out->cr();
2452   out->print_cr("CodeCache cleaning overview");
2453   out->print_cr("--------------------------------------------------------");
2454   out->cr();
2455   NMethodSweeper::print(out);
2456   out->print_cr("--------------------------------------------------------");
2457   out->cr();
2458 }
2459 
2460 // Note: tty_lock must not be held upon entry to this function.
2461 //       Print functions called from herein do "micro-locking" on tty_lock.
2462 //       That's a tradeoff which keeps together important blocks of output.
2463 //       At the same time, continuous tty_lock hold time is kept in check,
2464 //       preventing concurrently printing threads from stalling a long time.
2465 void CompileBroker::print_heapinfo(outputStream* out, const char* function, const char* granularity) {
2466   TimeStamp ts_total;
2467   TimeStamp ts;
2468 
2469   bool allFun = !strcmp(function, "all");
2470   bool aggregate = !strcmp(function, "aggregate") || !strcmp(function, "analyze") || allFun;
2471   bool usedSpace = !strcmp(function, "UsedSpace") || allFun;
2472   bool freeSpace = !strcmp(function, "FreeSpace") || allFun;
2473   bool methodCount = !strcmp(function, "MethodCount") || allFun;
2474   bool methodSpace = !strcmp(function, "MethodSpace") || allFun;
2475   bool methodAge = !strcmp(function, "MethodAge") || allFun;
2476   bool methodNames = !strcmp(function, "MethodNames") || allFun;
2477   bool discard = !strcmp(function, "discard") || allFun;
2478 
2479   if (out == NULL) {
2480     out = tty;
2481   }
2482 
2483   if (!(aggregate || usedSpace || freeSpace || methodCount || methodSpace || methodAge || methodNames || discard)) {
2484     out->print_cr("\n__ CodeHeapStateAnalytics: Function %s is not supported", function);
2485     out->cr();
2486     return;
2487   }
2488 
2489   ts_total.update(); // record starting point
2490 
2491   if (aggregate) {
2492     print_info(out);
2493   }
2494 
2495   // We hold the CodeHeapStateAnalytics_lock all the time, from here until we leave this function.
2496   // That helps us getting a consistent view on the CodeHeap, at least for the "all" function.
2497   // When we request individual parts of the analysis via the jcmd interface, it is possible
2498   // that in between another thread (another jcmd user or the vm running into CodeCache OOM)
2499   // updated the aggregated data. That's a tolerable tradeoff because we can't hold a lock
2500   // across user interaction.
2501   ts.update(); // record starting point
2502   MutexLockerEx mu1(CodeHeapStateAnalytics_lock, Mutex::_no_safepoint_check_flag);
2503   out->cr();
2504   out->print_cr("__ CodeHeapStateAnalytics lock wait took %10.3f seconds _________", ts.seconds());
2505   out->cr();
2506 
2507   if (aggregate) {
2508     // It is sufficient to hold the CodeCache_lock only for the aggregate step.
2509     // All other functions operate on aggregated data - except MethodNames, but that should be safe.
2510     // The separate CodeHeapStateAnalytics_lock protects the printing functions against
2511     // concurrent aggregate steps. Acquire this lock before acquiring the CodeCache_lock.
2512     // CodeHeapStateAnalytics_lock could be held by a concurrent thread for a long time,
2513     // leading to an unnecessarily long hold time of the CodeCache_lock.
2514     ts.update(); // record starting point
2515     MutexLockerEx mu2(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2516     out->cr();
2517     out->print_cr("__ CodeCache lock wait took %10.3f seconds _________", ts.seconds());
2518     out->cr();
2519 
2520     ts.update(); // record starting point
2521     CodeCache::aggregate(out, granularity);
2522     out->cr();
2523     out->print_cr("__ CodeCache lock hold took %10.3f seconds _________", ts.seconds());
2524     out->cr();
2525   }
2526 
2527   if (usedSpace) CodeCache::print_usedSpace(out);
2528   if (freeSpace) CodeCache::print_freeSpace(out);
2529   if (methodCount) CodeCache::print_count(out);
2530   if (methodSpace) CodeCache::print_space(out);
2531   if (methodAge) CodeCache::print_age(out);
2532   if (methodNames) CodeCache::print_names(out);
2533   if (discard) CodeCache::discard(out);
2534 
2535   out->cr();
2536   out->print_cr("__ CodeHeapStateAnalytics total duration %10.3f seconds _________", ts_total.seconds());
2537   out->cr();
2538 }