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