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