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